blob: 2e019039f82afe201b20de6affafecf9f3a348bf [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Ana Krulecb9afd792020-06-11 13:16:15 -070026#include <android-base/properties.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080027#include <android/configuration.h>
28#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
30#include <android/hardware/configstore/1.1/types.h>
31#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080032#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070033#include <binder/IPCThreadState.h>
34#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070035#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070036#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080037#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070038#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070039#include <compositionengine/DisplayColorProfile.h>
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -070040#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080041#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080042#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070043#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070044#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080045#include <configstore/Utils.h>
46#include <cutils/compiler.h>
47#include <cutils/properties.h>
48#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080050#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070051#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070052#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070054#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080055#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080056#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080057#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080058#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080059#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070060#include <input/IInputFlinger.h>
Alec Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Laskowskia19f4b62020-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
Ady Abraham8532d012019-05-08 14:50:56 -0700151using android::hardware::power::V1_0::PowerHint;
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 Laskowskia19f4b62020-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 Laskowskia19f4b62020-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 Laskowskia19f4b62020-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 Mouri989ddbe2020-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 Abraham0a525092020-03-03 12:51:24 -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;
426
Dan Stozaec460082018-12-17 15:35:09 -0800427 property_get("debug.sf.luma_sampling", value, "1");
428 mLumaSampling = atoi(value);
429
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800430 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800431 mDisableClientCompositionCache = atoi(value);
432
Romain Guy11d63f42017-07-20 12:47:14 -0700433 // We should be reading 'persist.sys.sf.color_saturation' here
434 // but since /data may be encrypted, we need to wait until after vold
435 // comes online to attempt to read the property. The property is
436 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800437
438 if (useTrebleTestingOverride()) {
439 // Without the override SurfaceFlinger cannot connect to HIDL
440 // services that are not listed in the manifests. Considered
441 // deriving the setting from the set service name, but it
442 // would be brittle if the name that's not 'default' is used
443 // for production purposes later on.
444 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
445 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800446
447 useFrameRateApi = use_frame_rate_api(true);
Ana Krulecb9afd792020-06-11 13:16:15 -0700448
449 mKernelIdleTimerEnabled = mSupportKernelIdleTimer = sysprop::support_kernel_idle_timer(false);
450 base::SetProperty(KERNEL_IDLE_TIMER_PROP, mKernelIdleTimerEnabled ? "true" : "false");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451}
452
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700453SurfaceFlinger::~SurfaceFlinger() = default;
454
455void SurfaceFlinger::onFirstRef() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800456 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800457}
458
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700459void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800460 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700461 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800462
Andy McFadden13a082e2012-08-24 10:16:42 -0700463 // restore initial conditions (default device unblank, etc)
464 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800465
466 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700467 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800468}
469
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700470void SurfaceFlinger::run() {
471 while (true) {
472 mEventQueue->waitMessage();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800473 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700474}
475
476template <typename F, typename T>
477inline std::future<T> SurfaceFlinger::schedule(F&& f) {
478 auto [task, future] = makeTask(std::move(f));
479 mEventQueue->postMessage(std::move(task));
480 return std::move(future);
Robert Carr1db73f62016-12-21 12:58:51 -0800481}
482
483sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700484 const sp<Client> client = new Client(this);
485 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800486}
487
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700488sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700489 class DisplayToken : public BBinder {
490 sp<SurfaceFlinger> flinger;
491 virtual ~DisplayToken() {
492 // no more references, this display must be terminated
493 Mutex::Autolock _l(flinger->mStateLock);
494 flinger->mCurrentState.displays.removeItem(this);
495 flinger->setTransactionFlags(eDisplayTransactionNeeded);
496 }
497 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700498 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499 : flinger(flinger) {
500 }
501 };
502
503 sp<BBinder> token = new DisplayToken(this);
504
505 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506 // Display ID is assigned when virtual display is allocated by HWC.
507 DisplayDeviceState state;
508 state.isSecure = secure;
509 state.displayName = displayName;
510 mCurrentState.displays.add(token, state);
511 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700512 return token;
513}
514
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700515void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700516 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700517
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700518 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700519 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700520 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700521 return;
522 }
523
Dominik Laskowski075d3172018-05-24 15:50:06 -0700524 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700525 if (state.physical) {
526 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700527 return;
528 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700529 mInterceptor->saveDisplayDeletion(state.sequenceId);
530 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700531 setTransactionFlags(eDisplayTransactionNeeded);
532}
533
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800534std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
535 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700536
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800537 const auto internalDisplayId = getInternalDisplayIdLocked();
538 if (!internalDisplayId) {
539 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700540 }
541
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800542 std::vector<PhysicalDisplayId> displayIds;
543 displayIds.reserve(mPhysicalDisplayTokens.size());
544 displayIds.push_back(internalDisplayId->value);
545
546 for (const auto& [id, token] : mPhysicalDisplayTokens) {
547 if (id != *internalDisplayId) {
548 displayIds.push_back(id.value);
549 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700550 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700551
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800552 return displayIds;
553}
554
555sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
556 Mutex::Autolock lock(mStateLock);
557 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700558}
559
Ady Abraham37965d42018-11-01 13:43:32 -0700560status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
561 if (!outGetColorManagement) {
562 return BAD_VALUE;
563 }
564 *outGetColorManagement = useColorManagement;
565 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700566}
567
Lloyd Pique441d5042018-10-18 16:49:51 -0700568HWComposer& SurfaceFlinger::getHwComposer() const {
569 return mCompositionEngine->getHwComposer();
570}
571
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700572renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
573 return mCompositionEngine->getRenderEngine();
574}
575
Lloyd Pique70d91362018-10-18 16:02:55 -0700576compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
577 return *mCompositionEngine.get();
578}
579
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800580void SurfaceFlinger::bootFinished()
581{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700582 if (mBootFinished == true) {
583 ALOGE("Extra call to bootFinished");
584 return;
585 }
586 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700587 if (mStartPropertySetThread->join() != NO_ERROR) {
588 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800589 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800590 const nsecs_t now = systemTime();
591 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000592 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700593
Mikael Pessa90092f42019-08-26 17:22:04 -0700594 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000595 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700596
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700597 // wait patiently for the window manager death
598 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700599 mWindowManager = defaultServiceManager()->getService(name);
600 if (mWindowManager != 0) {
601 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700602 }
Robert Carr720e5062018-07-30 17:45:14 -0700603 sp<IBinder> input(defaultServiceManager()->getService(
604 String16("inputflinger")));
605 if (input == nullptr) {
606 ALOGE("Failed to link to input service");
607 } else {
608 mInputFlinger = interface_cast<IInputFlinger>(input);
609 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700610
Steven Thomas050b2c82017-03-06 11:45:16 -0800611 if (mVrFlinger) {
612 mVrFlinger->OnBootFinished();
613 }
614
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700615 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700616 // formerly we would just kill the process, but we now ask it to exit so it
617 // can choose where to stop the animation.
618 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700619
620 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
621 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
622 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700623
Dominik Laskowski20134642020-04-20 22:36:44 -0700624 static_cast<void>(schedule([this] {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800625 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700626 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800627 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800628
Ady Abraham8a82ba62020-01-17 12:43:17 -0800629 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700630 enableRefreshRateOverlay(true);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800631 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800632 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800633}
634
Dan Stoza436ccf32018-06-21 12:10:12 -0700635uint32_t SurfaceFlinger::getNewTexture() {
636 {
637 std::lock_guard lock(mTexturePoolMutex);
638 if (!mTexturePool.empty()) {
639 uint32_t name = mTexturePool.back();
640 mTexturePool.pop_back();
641 ATRACE_INT("TexturePoolSize", mTexturePool.size());
642 return name;
643 }
644
645 // The pool was too small, so increase it for the future
646 ++mTexturePoolSize;
647 }
648
649 // The pool was empty, so we need to get a new texture name directly using a
650 // blocking call to the main thread
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700651 return schedule([this] {
652 uint32_t name = 0;
653 getRenderEngine().genTextures(1, &name);
654 return name;
655 })
656 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700657}
658
Mathias Agopian3f844832013-08-07 21:24:32 -0700659void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700660 std::lock_guard lock(mTexturePoolMutex);
661 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
662 // to actually delete this or not based on mTexturePoolSize
663 mTexturePool.push_back(texture);
664 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700665}
666
Wei Wangf9b05ee2017-07-19 20:59:39 -0700667// Do not call property_set on main thread which will be blocked by init
668// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700669void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700670 ALOGI( "SurfaceFlinger's main thread ready to run. "
671 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700672 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800673
Steven Thomasb02664d2017-07-26 18:48:28 -0700674 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700675 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800676 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700677 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
678 renderengine::RenderEngineCreationArgs::Builder()
679 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
680 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
681 .setUseColorManagerment(useColorManagement)
682 .setEnableProtectedContext(enable_protected_contents(false))
683 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700684 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700685 .setContextPriority(useContextPriority
686 ? renderengine::RenderEngine::ContextPriority::HIGH
687 : renderengine::RenderEngine::ContextPriority::MEDIUM)
688 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800689 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700690
691 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
692 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700693 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800694 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800695 // Process any initial hotplug and resulting display changes.
696 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700697 const auto display = getDefaultDisplayDeviceLocked();
698 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700699 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700700 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800701
Steven Thomas050b2c82017-03-06 11:45:16 -0800702 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700703 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700704 // This callback is called from the vr flinger dispatch thread. We
705 // need to call signalTransaction(), which requires holding
706 // mStateLock when we're not on the main thread. Acquiring
707 // mStateLock from the vr flinger dispatch thread might trigger a
708 // deadlock in surface flinger (see b/66916578), so post a message
709 // to be handled on the main thread instead.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700710 static_cast<void>(schedule([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700711 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
712 mVrFlingerRequestsDisplay = requestDisplay;
713 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700714 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800715 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700716 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
717 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700718 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700719 .value_or(0),
720 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800721 if (!mVrFlinger) {
722 ALOGE("Failed to start vrflinger");
723 }
724 }
725
Mathias Agopian92a979a2012-08-02 18:32:23 -0700726 // initialize our drawing state
727 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700728
Andy McFadden13a082e2012-08-24 10:16:42 -0700729 // set initial conditions (e.g. unblank default device)
730 initializeDisplays();
731
Steven Thomas137d4bc2019-07-25 16:55:14 -0700732 char primeShaderCache[PROPERTY_VALUE_MAX];
733 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
734 if (atoi(primeShaderCache)) {
735 getRenderEngine().primeCache();
736 }
Dan Stoza4e637772016-07-28 13:31:51 -0700737
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700739
740 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700741 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700742 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743
744 if (mStartPropertySetThread->Start() != NO_ERROR) {
745 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800746 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800747
Dan Stoza9e56aa02015-11-02 13:00:03 -0800748 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700749}
750
Romain Guy11d63f42017-07-20 12:47:14 -0700751void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700752 Mutex::Autolock _l(mStateLock);
753
Romain Guy11d63f42017-07-20 12:47:14 -0700754 char value[PROPERTY_VALUE_MAX];
755
756 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800757 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700758 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800759 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100760
761 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700762 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800763
764 property_get("persist.sys.sf.color_mode", value, "0");
765 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700766
767 property_get("persist.sys.sf.disable_blurs", value, "0");
768 bool disableBlurs = atoi(value);
769 mDisableBlurs = disableBlurs;
770 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700771}
772
Mathias Agopiana67e4182012-06-19 17:26:12 -0700773void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800774 // Start boot animation service by setting a property mailbox
775 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700776 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800777 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700778 if (mStartPropertySetThread->join() != NO_ERROR) {
779 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800780 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700781}
782
Mathias Agopian875d8e12013-06-07 15:35:48 -0700783size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700784 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700785}
786
Mathias Agopian875d8e12013-06-07 15:35:48 -0700787size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700788 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700789}
790
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800791// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800792
Jamie Gennis582270d2011-08-17 18:19:00 -0700793bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800794 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800795 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800796 return authenticateSurfaceTextureLocked(bufferProducer);
797}
798
799bool SurfaceFlinger::authenticateSurfaceTextureLocked(
800 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800801 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800802 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800803}
804
Brian Anderson6b376712017-04-04 10:51:39 -0700805status_t SurfaceFlinger::getSupportedFrameTimestamps(
806 std::vector<FrameEvent>* outSupported) const {
807 *outSupported = {
808 FrameEvent::REQUESTED_PRESENT,
809 FrameEvent::ACQUIRE,
810 FrameEvent::LATCH,
811 FrameEvent::FIRST_REFRESH_START,
812 FrameEvent::LAST_REFRESH_START,
813 FrameEvent::GPU_COMPOSITION_DONE,
814 FrameEvent::DEQUEUE_READY,
815 FrameEvent::RELEASE,
816 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700817 ConditionalLock _l(mStateLock,
818 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700819 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700820 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
821 }
822 return NO_ERROR;
823}
824
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800825status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
826 if (!displayToken || !state) {
827 return BAD_VALUE;
828 }
829
830 Mutex::Autolock lock(mStateLock);
831
832 const auto display = getDisplayDeviceLocked(displayToken);
833 if (!display) {
834 return NAME_NOT_FOUND;
835 }
836
837 state->layerStack = display->getLayerStack();
838 state->orientation = display->getOrientation();
839
840 const Rect viewport = display->getViewport();
841 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
842
843 return NO_ERROR;
844}
845
846status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
847 if (!displayToken || !info) {
848 return BAD_VALUE;
849 }
850
851 Mutex::Autolock lock(mStateLock);
852
853 const auto display = getDisplayDeviceLocked(displayToken);
854 if (!display) {
855 return NAME_NOT_FOUND;
856 }
857
Dominik Laskowski55c85402020-01-21 16:25:47 -0800858 if (const auto connectionType = display->getConnectionType())
859 info->connectionType = *connectionType;
860 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800861 return INVALID_OPERATION;
862 }
863
864 if (mEmulatedDisplayDensity) {
865 info->density = mEmulatedDisplayDensity;
866 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800867 info->density = info->connectionType == DisplayConnectionType::Internal
868 ? mInternalDisplayDensity
869 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800870 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700871 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800872
873 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200874 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800875
876 return NO_ERROR;
877}
878
Dominik Laskowski22488f62019-03-28 09:53:04 -0700879status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800880 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700881 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700882 return BAD_VALUE;
883 }
884
Dominik Laskowski22488f62019-03-28 09:53:04 -0700885 Mutex::Autolock lock(mStateLock);
886
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800887 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700888 if (!displayId) {
889 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700890 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700891
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800892 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700893
Dan Stoza7f7da322014-05-02 15:26:25 -0700894 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700895
Dominik Laskowski075d3172018-05-24 15:50:06 -0700896 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800897 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700898
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800899 auto width = hwConfig->getWidth();
900 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700901
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800902 auto xDpi = hwConfig->getDpiX();
903 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700904
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800905 if (isInternal &&
906 (internalDisplayOrientation == ui::ROTATION_90 ||
907 internalDisplayOrientation == ui::ROTATION_270)) {
908 std::swap(width, height);
909 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700910 }
911
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800912 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800913
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800914 if (mEmulatedDisplayDensity) {
915 config.xDpi = mEmulatedDisplayDensity;
916 config.yDpi = mEmulatedDisplayDensity;
917 } else {
918 config.xDpi = xDpi;
919 config.yDpi = yDpi;
920 }
921
922 const nsecs_t period = hwConfig->getVsyncPeriod();
923 config.refreshRate = 1e9f / period;
924
925 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
926 config.appVsyncOffset = offsets.late.app;
927 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800928 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800929
Andy McFadden91b2ca82014-06-13 14:04:23 -0700930 // This is how far in advance a buffer must be queued for
931 // presentation at a given time. If you want a buffer to appear
932 // on the screen at time N, you must submit the buffer before
933 // (N - presentationDeadline).
934 //
935 // Normally it's one full refresh period (to give SF a chance to
936 // latch the buffer), but this can be reduced by configuring a
937 // DispSync offset. Any additional delays introduced by the hardware
938 // composer or panel must be accounted for here.
939 //
940 // We add an additional 1ms to allow for processing time and
941 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800942 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700943
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800944 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700945 }
946
Dan Stoza7f7da322014-05-02 15:26:25 -0700947 return NO_ERROR;
948}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700949
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
951 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700952 return BAD_VALUE;
953 }
954
Ana Krulecc2870422019-01-29 19:00:58 -0800955 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700956 return NO_ERROR;
957}
958
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700959int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700960 int activeConfig;
961 bool isPrimary;
962
963 {
964 Mutex::Autolock lock(mStateLock);
965
966 if (const auto display = getDisplayDeviceLocked(displayToken)) {
967 activeConfig = display->getActiveConfig().value();
968 isPrimary = display->isPrimary();
969 } else {
970 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
971 return NAME_NOT_FOUND;
972 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800973 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700974
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700975 if (isPrimary) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700976 if (const auto config = getDesiredActiveConfig()) {
977 return config->configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700978 }
Steven Thomasc9098452019-09-30 17:15:05 -0700979 }
Ady Abraham2139f732019-11-13 18:56:40 -0800980
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700981 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700982}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700983
Ady Abraham03b02dd2019-03-21 15:40:11 -0700984void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800986 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700987 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800988
Ady Abrahamb838aed2019-02-12 15:30:16 -0800989 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800990 if (mDesiredActiveConfigChanged) {
991 // If a config change is pending, just cache the latest request in
992 // mDesiredActiveConfig
993 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
994 mDesiredActiveConfig = info;
995 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
996 } else {
997 // Check is we are already at the desired config
998 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700999 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -08001000 return;
1001 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001002
Ady Abraham59db0a32020-03-02 18:04:20 -08001003 // Initiate a config change.
1004 mDesiredActiveConfigChanged = true;
1005 mDesiredActiveConfig = info;
1006
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 // This will trigger HWC refresh without resetting the idle timer.
1008 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -07001009 // Start receiving vsync samples now, so that we can detect a period
1010 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -07001011 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -07001012 // As we called to set period, we will call to onRefreshRateChangeCompleted once
1013 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001014 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -08001015
Ady Abrahamabc27602020-04-08 17:20:29 -07001016 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001017 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001018 mScheduler->setConfigChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001019 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07001020
1021 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -08001022 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -07001023 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001024}
1025
1026status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1027 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001028
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001029 if (!displayToken) {
1030 return BAD_VALUE;
1031 }
Ady Abraham838de062019-02-04 10:24:03 -08001032
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001033 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001034 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001035 if (!display) {
1036 ALOGE("Attempt to set allowed display configs for invalid display token %p",
1037 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001038 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001039 } else if (display->isVirtual()) {
1040 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001041 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001042 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001043 const HwcConfigIndexType config(mode);
1044 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
Steven Thomasf734df42020-04-13 21:09:28 -07001045 const scheduler::RefreshRateConfigs::Policy policy{config, {fps, fps}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001046 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001047
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001048 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1049 }
1050 });
1051
1052 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001053}
1054
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001055void SurfaceFlinger::setActiveConfigInternal() {
1056 ATRACE_CALL();
1057
Dominik Laskowski22488f62019-03-28 09:53:04 -07001058 const auto display = getDefaultDisplayDeviceLocked();
1059 if (!display) {
1060 return;
1061 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001062
Alec Mouri8de697e2020-03-19 10:52:01 -07001063 auto& oldRefreshRate =
1064 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1065
Dominik Laskowski22488f62019-03-28 09:53:04 -07001066 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001067 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001068 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001069 display->setActiveConfig(mUpcomingActiveConfig.configId);
1070
Ady Abraham2e1dd892020-03-05 13:48:36 -08001071 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001072 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001073 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001074 mTimeStats->incrementRefreshRateSwitches();
1075 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001076 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001077 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001078 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001079
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001080 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001081 const nsecs_t vsyncPeriod =
1082 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001083 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001084 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
1085 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001086 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001087}
1088
Ady Abraham53852a52019-05-28 18:07:44 -07001089void SurfaceFlinger::desiredActiveConfigChangeDone() {
1090 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1091 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1092 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001093
Ady Abraham2e1dd892020-03-05 13:48:36 -08001094 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001095 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001096 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1097 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001098 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001099 mScheduler->setConfigChangePending(false);
Ady Abraham53852a52019-05-28 18:07:44 -07001100}
1101
Ady Abraham27cbed72020-04-10 12:56:59 -07001102void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001103 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001104 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001105 // Store the local variable to release the lock.
Dominik Laskowski20134642020-04-20 22:36:44 -07001106 const auto desiredActiveConfig = getDesiredActiveConfig();
Ady Abraham27cbed72020-04-10 12:56:59 -07001107 if (!desiredActiveConfig) {
1108 // No desired active config pending to be applied
1109 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001110 }
1111
Ady Abraham2e1dd892020-03-05 13:48:36 -08001112 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001113 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001114 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1115 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001116 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001117 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001118 // display is not valid or we are already in the requested mode
1119 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001120 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001121 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001122 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001123
Ady Abraham838de062019-02-04 10:24:03 -08001124 // Desired active config was set, it is different than the config currently in use, however
1125 // allowed configs might have change by the time we process the refresh.
1126 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001127 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001128 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001129 return;
Ady Abraham838de062019-02-04 10:24:03 -08001130 }
Alec Mouri7f015182019-07-11 13:56:22 -07001131
Ady Abraham27cbed72020-04-10 12:56:59 -07001132 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001133 const auto displayId = display->getId();
1134 LOG_ALWAYS_FATAL_IF(!displayId);
1135
Ady Abrahamabc27602020-04-08 17:20:29 -07001136 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001137
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001138 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001139 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001140 constraints.desiredTimeNanos = systemTime();
1141 constraints.seamlessRequired = false;
1142
Peiyong Line9d809e2020-04-14 13:10:48 -07001143 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001144 auto status =
1145 getHwComposer().setActiveConfigWithConstraints(*displayId,
1146 mUpcomingActiveConfig.configId.value(),
1147 constraints, &outTimeline);
1148 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001149 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1150 // to be sent. We just log the error in this case.
1151 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001152 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001153 }
1154
1155 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1156 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001157 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001158}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001159
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001160status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1161 Vector<ColorMode>* outColorModes) {
1162 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001163 return BAD_VALUE;
1164 }
1165
Peiyong Lina52f0292018-03-14 17:26:31 -07001166 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001167 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001168 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001169 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1170
1171 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1172 if (!displayId) {
1173 return NAME_NOT_FOUND;
1174 }
1175
Dominik Laskowski075d3172018-05-24 15:50:06 -07001176 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001177 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001178 }
Michael Wright28f24d02016-07-12 13:30:53 -07001179 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001180
1181 // If it's built-in display and the configuration claims it's not wide color capable,
1182 // filter out all wide color modes. The typical reason why this happens is that the
1183 // hardware is not good enough to support GPU composition of wide color, and thus the
1184 // OEMs choose to disable this capability.
1185 if (isInternalDisplay && !hasWideColorDisplay) {
1186 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1187 isWideColorMode);
1188 } else {
1189 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1190 }
Michael Wright28f24d02016-07-12 13:30:53 -07001191
1192 return NO_ERROR;
1193}
1194
Daniel Solomon42d04562019-01-20 21:03:19 -08001195status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1196 ui::DisplayPrimaries &primaries) {
1197 if (!displayToken) {
1198 return BAD_VALUE;
1199 }
1200
1201 // Currently we only support this API for a single internal display.
1202 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001203 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001204 }
1205
1206 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1207 return NO_ERROR;
1208}
1209
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001210ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001211 Mutex::Autolock lock(mStateLock);
1212
1213 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001214 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001215 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001216 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001217}
1218
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001219status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001220 schedule([=]() MAIN_THREAD {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001221 Vector<ColorMode> modes;
1222 getDisplayColorModes(displayToken, &modes);
1223 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1224 if (mode < ColorMode::NATIVE || !exists) {
1225 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1226 decodeColorMode(mode).c_str(), mode, displayToken.get());
1227 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001228 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001229 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001230 if (!display) {
1231 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1232 decodeColorMode(mode).c_str(), mode, displayToken.get());
1233 } else if (display->isVirtual()) {
1234 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1235 decodeColorMode(mode).c_str(), mode);
1236 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001237 display->getCompositionDisplay()->setColorProfile(
1238 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1239 RenderIntent::COLORIMETRIC,
1240 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001241 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001242 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001243
Michael Wright28f24d02016-07-12 13:30:53 -07001244 return NO_ERROR;
1245}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001246
Galia Peycheva5492cb52019-10-30 14:13:16 +01001247status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1248 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001249 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001250 return BAD_VALUE;
1251 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001252
1253 Mutex::Autolock lock(mStateLock);
1254
Galia Peycheva5492cb52019-10-30 14:13:16 +01001255 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1256 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001257 return NAME_NOT_FOUND;
1258 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001259 *outSupport =
1260 getHwComposer().hasDisplayCapability(*displayId,
1261 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001262 return NO_ERROR;
1263}
1264
1265void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001266 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001267 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1268 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1269 } else {
1270 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1271 }
1272 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001273}
1274
1275status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1276 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001277 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001278 return BAD_VALUE;
1279 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001280
1281 Mutex::Autolock lock(mStateLock);
1282
Galia Peycheva5492cb52019-10-30 14:13:16 +01001283 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1284 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001285 return NAME_NOT_FOUND;
1286 }
1287
Peiyong Line9d809e2020-04-14 13:10:48 -07001288 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001289 getHwComposer().getSupportedContentTypes(*displayId, &types);
1290
1291 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001292 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001293 return NO_ERROR;
1294}
1295
1296void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001297 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001298 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001299 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001300 getHwComposer().setContentType(*displayId, type);
1301 } else {
1302 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1303 }
1304 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001305}
1306
Svetoslavd85084b2014-03-20 10:28:31 -07001307status_t SurfaceFlinger::clearAnimationFrameStats() {
1308 Mutex::Autolock _l(mStateLock);
1309 mAnimFrameTracker.clearStats();
1310 return NO_ERROR;
1311}
1312
1313status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1314 Mutex::Autolock _l(mStateLock);
1315 mAnimFrameTracker.getStats(outStats);
1316 return NO_ERROR;
1317}
1318
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001319status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1320 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001321 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001322
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001323 const auto display = getDisplayDeviceLocked(displayToken);
1324 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001325 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1326 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001327 }
1328
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001329 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001330 // meaning the luminance information is already queried from
1331 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001332 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001333 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1334 capabilities.getDesiredMaxLuminance(),
1335 capabilities.getDesiredMaxAverageLuminance(),
1336 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001337
1338 return NO_ERROR;
1339}
1340
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001341std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1342 const DisplayDevice& display) const {
1343 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1344 // avoid repetitive HAL IPC and EDID parsing.
1345 const auto displayId = display.getId();
1346 LOG_FATAL_IF(!displayId);
1347
1348 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1349 LOG_FATAL_IF(!hwcDisplayId);
1350
1351 uint8_t port;
1352 DisplayIdentificationData data;
1353 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1354 ALOGV("%s: No identification data.", __FUNCTION__);
1355 return {};
1356 }
1357
1358 const auto info = parseDisplayIdentificationData(port, data);
1359 if (!info) {
1360 return {};
1361 }
1362 return info->deviceProductInfo;
1363}
1364
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001365status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1366 ui::PixelFormat* outFormat,
1367 ui::Dataspace* outDataspace,
1368 uint8_t* outComponentMask) const {
1369 if (!outFormat || !outDataspace || !outComponentMask) {
1370 return BAD_VALUE;
1371 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001372
1373 Mutex::Autolock lock(mStateLock);
1374
1375 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1376 if (!displayId) {
1377 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001378 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001379
1380 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001381 outDataspace, outComponentMask);
1382}
1383
Kevin DuBois74e53772018-11-19 10:52:38 -08001384status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1385 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001386 uint64_t maxFrames) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001387 return schedule([=]() MAIN_THREAD -> status_t {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001388 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1389 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1390 componentMask,
1391 maxFrames);
1392 } else {
1393 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1394 return NAME_NOT_FOUND;
1395 }
1396 })
1397 .get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001398}
1399
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001400status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1401 uint64_t maxFrames, uint64_t timestamp,
1402 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001403 Mutex::Autolock lock(mStateLock);
1404
1405 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1406 if (!displayId) {
1407 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001408 }
1409
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001410 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001411}
1412
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001413status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1414 if (!outSupported) {
1415 return BAD_VALUE;
1416 }
1417 *outSupported = getRenderEngine().supportsProtectedContent();
1418 return NO_ERROR;
1419}
1420
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001421status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1422 bool* outIsWideColorDisplay) const {
1423 if (!displayToken || !outIsWideColorDisplay) {
1424 return BAD_VALUE;
1425 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001426
1427 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001428 const auto display = getDisplayDeviceLocked(displayToken);
1429 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001430 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001431 }
Peiyong Linff84a152019-05-17 18:36:19 -07001432
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001433 *outIsWideColorDisplay =
1434 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001435 return NO_ERROR;
1436}
1437
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001438status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001439 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001440 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001441
Dominik Laskowski6505f792019-09-18 11:10:05 -07001442 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1443 mEventQueue->setEventConnection(
1444 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001445 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001446 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001447
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001448 return NO_ERROR;
1449}
1450
1451status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001452 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001453 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001454}
1455
Vishnu Nair43bccf82020-06-05 10:53:37 -07001456status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001457 outLayers->clear();
Vishnu Nair43bccf82020-06-05 10:53:37 -07001458 schedule([=] {
1459 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
1460 mDrawingState.traverseInZOrder([&](Layer* layer) {
1461 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1462 });
1463 }).wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001464 return NO_ERROR;
1465}
1466
Peiyong Linc6780972018-10-28 15:24:08 -07001467status_t SurfaceFlinger::getCompositionPreference(
1468 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1469 Dataspace* outWideColorGamutDataspace,
1470 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001471 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001472 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001473 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001474 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001475 return NO_ERROR;
1476}
1477
Dan Stozaec460082018-12-17 15:35:09 -08001478status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1479 const sp<IBinder>& stopLayerHandle,
1480 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001481 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001482 return BAD_VALUE;
1483 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001484
1485 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1486 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001487 return NO_ERROR;
1488}
1489
Dan Stozaec460082018-12-17 15:35:09 -08001490status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001491 if (!listener) {
1492 return BAD_VALUE;
1493 }
Dan Stozaec460082018-12-17 15:35:09 -08001494 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001495 return NO_ERROR;
1496}
Dan Gittik57e63c52019-01-18 16:37:54 +00001497
1498status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1499 bool* outSupport) const {
1500 if (!displayToken || !outSupport) {
1501 return BAD_VALUE;
1502 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001503
1504 Mutex::Autolock lock(mStateLock);
1505
Dan Gittik57e63c52019-01-18 16:37:54 +00001506 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1507 if (!displayId) {
1508 return NAME_NOT_FOUND;
1509 }
1510 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001511 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001512 return NO_ERROR;
1513}
1514
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001515status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001516 if (!displayToken) {
1517 return BAD_VALUE;
1518 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001519
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001520 return promise::chain(schedule([=]() MAIN_THREAD {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001521 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1522 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1523 } else {
1524 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001525 return promise::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001526 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001527 }))
1528 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001529 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001530}
1531
Ady Abraham8532d012019-05-08 14:50:56 -07001532status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1533 PowerHint powerHint = static_cast<PowerHint>(hintId);
1534
1535 if (powerHint == PowerHint::INTERACTION) {
1536 mScheduler->notifyTouchEvent();
1537 }
1538
1539 return NO_ERROR;
1540}
1541
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001542// ----------------------------------------------------------------------------
1543
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001544sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001545 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001546 const auto& handle =
1547 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001548
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001549 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001550}
1551
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001552void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001553 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001554 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001555 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001556}
1557
1558void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001559 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001560 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001561 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001562}
1563
1564void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001565 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001566 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001567}
1568
Dominik Laskowski83b88212018-12-11 13:34:06 -08001569nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001570 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001571 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1572 return 0;
1573 }
1574
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001575 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001576}
1577
Peiyong Line9d809e2020-04-14 13:10:48 -07001578void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001579 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001580 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001581 ATRACE_NAME("SF onVsync");
1582
Steven Thomas3cfac282017-02-06 12:29:30 -08001583 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001584 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001585 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001586 return;
1587 }
1588
Dominik Laskowski075d3172018-05-24 15:50:06 -07001589 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001590 return;
1591 }
1592
Dominik Laskowski075d3172018-05-24 15:50:06 -07001593 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001594 // For now, we don't do anything with external display vsyncs.
1595 return;
1596 }
1597
Alec Mourif8e689c2019-05-20 18:32:22 -07001598 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001599 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001600 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001601 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001602 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001603}
1604
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001605void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001606 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1607 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001608}
1609
Ady Abraham2139f732019-11-13 18:56:40 -08001610bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001611 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001612}
1613
Ady Abraham2139f732019-11-13 18:56:40 -08001614void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1615 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001616 const auto display = getDefaultDisplayDeviceLocked();
1617 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001618 return;
1619 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001620 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001621
Ana Krulec7d1d6832018-12-27 11:10:09 -08001622 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001623 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001624 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001625 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001626 return;
1627 }
1628
Ady Abrahamabc27602020-04-08 17:20:29 -07001629 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001630}
1631
Peiyong Line9d809e2020-04-14 13:10:48 -07001632void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001633 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001634 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001635 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001636
Lloyd Piqueba04e622017-12-14 17:11:26 -08001637 // Ignore events that do not have the right sequenceId.
1638 if (sequenceId != getBE().mComposerSequenceId) {
1639 return;
1640 }
1641
Steven Thomasb02664d2017-07-26 18:48:28 -07001642 // Only lock if we're not on the main thread. This function is normally
1643 // called on a hwbinder thread, but for the primary display it's called on
1644 // the main thread with the state lock already held, so don't attempt to
1645 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001646 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001647
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001648 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001649
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001650 if (std::this_thread::get_id() == mMainThreadId) {
1651 // Process all pending hot plug events immediately if we are on the main thread.
1652 processDisplayHotplugEventsLocked();
1653 }
1654
Lloyd Piqueba04e622017-12-14 17:11:26 -08001655 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001656}
1657
Ady Abraham7159f572019-10-11 11:10:18 -07001658void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001659 int32_t sequenceId, hal::HWDisplayId /*display*/,
1660 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001661 Mutex::Autolock lock(mStateLock);
1662 if (sequenceId != getBE().mComposerSequenceId) {
1663 return;
1664 }
1665 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001666}
1667
Peiyong Line9d809e2020-04-14 13:10:48 -07001668void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001669 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1670 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1671}
1672
Peiyong Line9d809e2020-04-14 13:10:48 -07001673void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001674 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001675 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001676 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001677 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001678 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001679}
1680
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001681void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001682 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001683
1684 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1685 // display power state.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001686 static_cast<void>(schedule([=]() MAIN_THREAD { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001687}
1688
1689void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1690 ATRACE_CALL();
1691
Peiyong Line9d809e2020-04-14 13:10:48 -07001692 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001693
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001694 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001695 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1696 if (display && display->isPoweredOn()) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02001697 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001698 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001699 }
Mathias Agopian86303202012-07-24 22:46:10 -07001700}
1701
Steven Thomasb02664d2017-07-26 18:48:28 -07001702void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001703 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001704 // Clear the drawing state so that the logic inside of
1705 // handleTransactionLocked will fire. It will determine the delta between
1706 // mCurrentState and mDrawingState and re-apply all changes when we make the
1707 // transition.
1708 mDrawingState.displays.clear();
1709 mDisplays.clear();
1710}
1711
Steven Thomas050b2c82017-03-06 11:45:16 -08001712void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001713 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001714 if (!mVrFlinger)
1715 return;
1716 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001717 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001718 return;
1719 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001720
Lloyd Pique441d5042018-10-18 16:49:51 -07001721 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001722 ALOGE("Vr flinger is only supported for remote hardware composer"
1723 " service connections. Ignoring request to transition to vr"
1724 " flinger.");
1725 mVrFlingerRequestsDisplay = false;
1726 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001727 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001728
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001729 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001730
Steven Thomas0123ac62018-07-12 11:32:34 -07001731 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001732 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001733
Peiyong Lin65248e02020-04-18 21:15:07 -07001734 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001735
1736 // Clear out all the output layers from the composition engine for all
1737 // displays before destroying the hardware composer interface. This ensures
1738 // any HWC layers are destroyed through that interface before it becomes
1739 // invalid.
1740 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001741 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001742 }
1743
Steven Thomas0123ac62018-07-12 11:32:34 -07001744 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1745 // called below. Clear the reference now so we don't accidentally use it
1746 // later.
1747 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001748
Steven Thomasb02664d2017-07-26 18:48:28 -07001749 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001750 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001751 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001752
Steven Thomasb02664d2017-07-26 18:48:28 -07001753 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001754 // Delete the current instance before creating the new one
1755 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1756 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1757 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001758 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001759
Lloyd Pique441d5042018-10-18 16:49:51 -07001760 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001761 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001762
1763 if (vrFlingerRequestsDisplay) {
1764 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001765 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001766
1767 mVisibleRegionsDirty = true;
1768 invalidateHwcGeometry();
1769
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001770 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001771 display = getDefaultDisplayDeviceLocked();
1772 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001773 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001774
Steven Thomasb02664d2017-07-26 18:48:28 -07001775 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001776 const nsecs_t vsyncPeriod = getVsyncPeriod();
1777 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001778
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001779 // The present fences returned from vr_hwc are not an accurate
1780 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001781 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001782
Steven Thomasb02664d2017-07-26 18:48:28 -07001783 // Use phase of 0 since phase is not known.
1784 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001785 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001786 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001787
Ana Krulecc2870422019-01-29 19:00:58 -08001788 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001789
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001790 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001791 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001792}
1793
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001794sp<Fence> SurfaceFlinger::previousFrameFence() {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001795 // We are storing the last 2 present fences. If sf's phase offset is to be
1796 // woken up before the actual vsync but targeting the next vsync, we need to check
1797 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001798 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1799 : mPreviousPresentFences[1];
1800}
1801
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001802bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001803 ATRACE_CALL();
1804 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001805
Ady Abraham11579302019-09-19 12:35:58 -07001806 if (fence == Fence::NO_FENCE) {
1807 return false;
1808 }
1809
Dan Stoza59083052020-04-28 10:13:20 -07001810 const status_t status = fence->wait(graceTimeMs);
1811 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1812 // which calls wait(0) again internally
1813 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001814}
1815
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001816nsecs_t SurfaceFlinger::previousFramePresentTime() {
Alec Mouri6d414b52020-03-17 11:18:05 -07001817 const sp<Fence>& fence = previousFrameFence();
1818
1819 if (fence == Fence::NO_FENCE) {
1820 return Fence::SIGNAL_TIME_INVALID;
1821 }
1822
1823 return fence->getSignalTime();
1824}
1825
Ady Abraham5facfb12020-04-22 15:18:31 -07001826nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001827 DisplayStatInfo stats;
1828 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001829 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001830 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001831 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001832}
1833
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001834void SurfaceFlinger::onMessageReceived(int32_t what, nsecs_t expectedVSyncTime) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001835 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001836 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001837 case MessageQueue::INVALIDATE: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001838 onMessageInvalidate(expectedVSyncTime);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001839 break;
1840 }
1841 case MessageQueue::REFRESH: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001842 onMessageRefresh();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001843 break;
1844 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001845 }
1846}
1847
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001848void SurfaceFlinger::onMessageInvalidate(nsecs_t expectedVSyncTime) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001849 ATRACE_CALL();
1850
1851 const nsecs_t frameStart = systemTime();
1852 // calculate the expected present time once and use the cached
1853 // value throughout this frame to make sure all layers are
1854 // seeing this same value.
1855 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
1856 mExpectedPresentTime = expectedVSyncTime;
1857
1858 // When Backpressure propagation is enabled we want to give a small grace period
1859 // for the present fence to fire instead of just giving up on this frame to handle cases
1860 // where present fence is just about to get signaled.
1861 const int graceTimeForPresentFenceMs =
1862 (mPropagateBackpressure &&
1863 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1864 ? 1
1865 : 0;
1866
1867 // Pending frames may trigger backpressure propagation.
1868 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1869 previousFramePending(graceTimeForPresentFenceMs)};
1870
1871 // Frame missed counts for metrics tracking.
1872 // A frame is missed if the prior frame is still pending. If no longer pending,
1873 // then we still count the frame as missed if the predicted present time
1874 // was further in the past than when the fence actually fired.
1875
1876 // Add some slop to correct for drift. This should generally be
1877 // smaller than a typical frame duration, but should not be so small
1878 // that it reports reasonable drift as a missed frame.
1879 DisplayStatInfo stats;
1880 mScheduler->getDisplayStatInfo(&stats);
1881 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1882 const nsecs_t previousPresentTime = previousFramePresentTime();
1883 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
1884 framePending ||
1885 (previousPresentTime >= 0 &&
1886 (lastExpectedPresentTime <
1887 previousPresentTime - frameMissedSlop))};
1888 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
1889 mHadDeviceComposition && frameMissed};
1890 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
1891 mHadClientComposition && frameMissed};
1892
1893 if (frameMissed) {
1894 mFrameMissedCount++;
1895 mTimeStats->incrementMissedFrames();
1896 if (mMissedFrameJankCount == 0) {
1897 mMissedFrameJankStart = systemTime();
1898 }
1899 mMissedFrameJankCount++;
1900 }
1901
1902 if (hwcFrameMissed) {
1903 mHwcFrameMissedCount++;
1904 }
1905
1906 if (gpuFrameMissed) {
1907 mGpuFrameMissedCount++;
1908 }
1909
1910 // If we are in the middle of a config change and the fence hasn't
1911 // fired yet just wait for the next invalidate
1912 if (mSetActiveConfigPending) {
1913 if (framePending) {
1914 mEventQueue->invalidate();
1915 return;
1916 }
1917
1918 // We received the present fence from the HWC, so we assume it successfully updated
1919 // the config, hence we update SF.
1920 mSetActiveConfigPending = false;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001921 ON_MAIN_THREAD(setActiveConfigInternal());
Dan Stoza28d46a52020-04-28 09:54:54 -07001922 }
1923
1924 if (framePending && mPropagateBackpressure) {
1925 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
1926 signalLayerUpdate();
1927 return;
1928 }
1929 }
1930
1931 // Our jank window is always at least 100ms since we missed a
1932 // frame...
1933 static constexpr nsecs_t kMinJankyDuration =
1934 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1935 // ...but if it's larger than 1s then we missed the trace cutoff.
1936 static constexpr nsecs_t kMaxJankyDuration =
1937 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001938 nsecs_t jankDurationToUpload = -1;
Dan Stoza28d46a52020-04-28 09:54:54 -07001939 // If we're in a user build then don't push any atoms
1940 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001941 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dan Stoza28d46a52020-04-28 09:54:54 -07001942 // Only report jank when the display is on, as displays in DOZE
1943 // power mode may operate at a different frame rate than is
1944 // reported in their config, which causes noticeable (but less
1945 // severe) jank.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001946 if (display && display->getPowerMode() == hal::PowerMode::ON) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001947 const nsecs_t currentTime = systemTime();
1948 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1949 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001950 jankDurationToUpload = jankDuration;
Dan Stoza28d46a52020-04-28 09:54:54 -07001951 }
1952
1953 // We either reported a jank event or we missed the trace
1954 // window, so clear counters here.
1955 if (jankDuration > kMinJankyDuration) {
1956 mMissedFrameJankCount = 0;
1957 mMissedFrameJankStart = 0;
1958 }
1959 }
1960 }
1961
1962 // Now that we're going to make it to the handleMessageTransaction()
1963 // call below it's safe to call updateVrFlinger(), which will
1964 // potentially trigger a display handoff.
1965 updateVrFlinger();
1966
1967 if (mTracingEnabledChanged) {
1968 mTracingEnabled = mTracing.isEnabled();
1969 mTracingEnabledChanged = false;
1970 }
1971
1972 bool refreshNeeded;
1973 {
1974 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1975
1976 refreshNeeded = handleMessageTransaction();
1977 refreshNeeded |= handleMessageInvalidate();
1978 if (mTracingEnabled) {
1979 mAddCompositionStateToTrace =
1980 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1981 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1982 mTracing.notifyLocked("visibleRegionsDirty");
1983 }
1984 }
1985 }
1986
1987 // Layers need to get updated (in the previous line) before we can use them for
1988 // choosing the refresh rate.
1989 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1990 // and may eventually call to ~Layer() if it holds the last reference
1991 {
1992 Mutex::Autolock _l(mStateLock);
1993 mScheduler->chooseRefreshRateForContent();
1994 }
1995
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001996 ON_MAIN_THREAD(performSetActiveConfig());
Dan Stoza28d46a52020-04-28 09:54:54 -07001997
1998 updateCursorAsync();
1999 updateInputFlinger();
2000
2001 refreshNeeded |= mRepaintEverything;
2002 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002003 mLastJankDuration = jankDurationToUpload;
Dan Stoza28d46a52020-04-28 09:54:54 -07002004 // Signal a refresh if a transaction modified the window state,
2005 // a new buffer was latched, or if HWC has requested a full
2006 // repaint
2007 if (mFrameStartTime <= 0) {
2008 // We should only use the time of the first invalidate
2009 // message that signals a refresh as the beginning of the
2010 // frame. Otherwise the real frame time will be
2011 // underestimated.
2012 mFrameStartTime = frameStart;
2013 }
2014 signalRefresh();
2015 }
2016}
2017
Dan Stoza6b9454d2014-11-07 16:00:59 -08002018bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08002019 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002020 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002021
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002022 bool flushedATransaction = flushTransactionQueues();
2023
Valerie Hau47826a72020-06-15 12:34:40 -07002024 bool runHandleTransaction =
2025 (transactionFlags && (transactionFlags != eTransactionFlushNeeded)) ||
2026 flushedATransaction;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002027
2028 if (runHandleTransaction) {
2029 handleTransaction(eTransactionMask);
2030 } else {
2031 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002032 }
2033
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002034 if (transactionFlushNeeded()) {
2035 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002036 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002037
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002038 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002039}
2040
Dan Stoza28d46a52020-04-28 09:54:54 -07002041void SurfaceFlinger::onMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002042 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002043
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002044 mRefreshPending = false;
2045
Lloyd Piqueab039b52019-02-13 14:22:42 -08002046 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002047 const auto& displays = ON_MAIN_THREAD(mDisplays);
2048 refreshArgs.outputs.reserve(displays.size());
2049 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002050 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2051 }
2052 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002053 if (auto layerFE = layer->getCompositionEngineLayerFE())
2054 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002055 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002056 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2057 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002058 if (auto layerFE = layer->getCompositionEngineLayerFE())
2059 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002060 }
2061
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002062 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002063 refreshArgs.outputColorSetting = useColorManagement
2064 ? mDisplayColorSetting
2065 : compositionengine::OutputColorSetting::kUnmanaged;
2066 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2067 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002068
2069 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2070 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002071 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002072 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002073
2074 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2075 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2076 mDrawingState.colorMatrixChanged = false;
2077 }
2078
2079 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2080
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002081 if (mDebugRegion != 0) {
2082 refreshArgs.devOptFlashDirtyRegionsDelay =
2083 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2084 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002085
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002086 mGeometryInvalid = false;
2087
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002088 // Store the present time just before calling to the composition engine so we could notify
2089 // the scheduler.
2090 const auto presentTime = systemTime();
2091
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002092 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002093 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2094 // Reset the frame start time now that we've recorded this frame.
2095 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002096
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002097 mScheduler->onDisplayRefreshed(presentTime);
2098
David Sodmanfa9b2af2017-12-24 13:28:59 -08002099 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002100 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002101
Alec Mouri8f7a0102020-04-15 12:11:10 -07002102 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2103
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002104 mHadClientComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2105 const auto& state = pair.second->getCompositionDisplay()->getState();
2106 return state.usesClientComposition && !state.reusedClientComposition;
2107 });
2108 mHadDeviceComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2109 const auto& state = pair.second->getCompositionDisplay()->getState();
2110 return state.usesDeviceComposition;
2111 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002112 mReusedClientComposition =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002113 std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2114 const auto& state = pair.second->getCompositionDisplay()->getState();
2115 return state.reusedClientComposition;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002116 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002117
Alec Mouri8f7a0102020-04-15 12:11:10 -07002118 // Only report a strategy change if we move in and out of composition with hw overlays
2119 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2120 mTimeStats->incrementCompositionStrategyChanges();
2121 }
2122
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002123 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002124
David Sodman7e4ae112018-02-09 15:02:28 -08002125 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002126 if (mVisibleRegionsDirty) {
2127 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002128 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002129 mTracing.notify("visibleRegionsDirty");
2130 }
2131 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002132
2133 if (mCompositionEngine->needsAnotherUpdate()) {
2134 signalLayerUpdate();
2135 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002136}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002137
David Sodmanfa9b2af2017-12-24 13:28:59 -08002138bool SurfaceFlinger::handleMessageInvalidate() {
2139 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002140 bool refreshNeeded = handlePageFlip();
2141
Vishnu Nair4351ad52019-02-11 14:13:02 -08002142 if (mVisibleRegionsDirty) {
2143 computeLayerBounds();
2144 }
2145
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002146 for (auto& layer : mLayersPendingRefresh) {
2147 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002148 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002149 invalidateLayerStack(layer, visibleReg);
2150 }
2151 mLayersPendingRefresh.clear();
2152 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002153}
2154
Ana Krulece588e312018-09-18 12:32:24 -07002155void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2156 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002157 // Update queue of past composite+present times and determine the
2158 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002159 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002160 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002161 while (!getBE().mCompositePresentTimes.empty()) {
2162 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002163 // Cached values should have been updated before calling this method,
2164 // which helps avoid duplicate syscalls.
2165 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2166 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2167 break;
2168 }
2169 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002170 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002171 }
2172
2173 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002174 while (getBE().mCompositePresentTimes.size() > 16) {
2175 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002176 }
2177
Ana Krulece588e312018-09-18 12:32:24 -07002178 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002179}
2180
Ana Krulece588e312018-09-18 12:32:24 -07002181void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2182 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002183 // Integer division and modulo round toward 0 not -inf, so we need to
2184 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002185 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2186 ? (stats.vsyncPeriod -
2187 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2188 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002189
Ady Abraham9e16a482019-12-03 17:19:41 -08002190 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002191 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002192 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002193 }
2194
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002195 // Snap the latency to a value that removes scheduling jitter from the
2196 // composition and present times, which often have >1ms of jitter.
2197 // Reducing jitter is important if an app attempts to extrapolate
2198 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002199 // Snapping also allows an app to precisely calculate
2200 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002201 nsecs_t bias = stats.vsyncPeriod / 2;
2202 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2203 nsecs_t snappedCompositeToPresentLatency =
2204 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002205
David Sodman99974d22017-11-28 12:04:33 -08002206 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002207 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2208 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002209 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002210}
2211
David Sodman2b406362017-12-15 13:33:47 -08002212void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002213{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002214 ATRACE_CALL();
2215 ALOGV("postComposition");
2216
Brian Andersonf6386862016-10-31 16:34:13 -07002217 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002218 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002219 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002220 }
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002221
2222 const auto* display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002223
David Sodman73beded2017-11-15 11:56:06 -08002224 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002225 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002226 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002227 glCompositionDoneFenceTime =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002228 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002229 ->getRenderSurface()
2230 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002231 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002232 } else {
2233 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2234 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002235
David Sodman73beded2017-11-15 11:56:06 -08002236 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002237 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002238 mPreviousPresentFences[0] =
2239 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Ady Abrahambe0f9482019-04-24 15:41:53 -07002240 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002241 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002242
Ana Krulece588e312018-09-18 12:32:24 -07002243 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002244 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002245
Lloyd Piqueab039b52019-02-13 14:22:42 -08002246 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2247 // be sampled a little later than when we started doing work for this frame,
2248 // but that should be okay since updateCompositorTiming has snapping logic.
2249 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2250 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002251 CompositorTiming compositorTiming;
2252 {
David Sodman99974d22017-11-28 12:04:33 -08002253 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2254 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002255 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002256
Edgar Arriaga844fa672020-01-16 14:21:42 -08002257 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002258 const bool frameLatched = layer->onPostComposition(display, glCompositionDoneFenceTime,
2259 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002260 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002261 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002262 }
Robert Carr2047fae2016-11-28 14:09:09 -08002263 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002264
Valerie Hau4b678442020-04-14 10:50:42 -07002265 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2266 mTransactionCompletedThread.sendCallbacks();
2267
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002268 if (display && display->isPrimary() && display->getPowerMode() == hal::PowerMode::ON &&
2269 presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002270 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002271 }
2272
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002273 const bool isDisplayConnected = display && getHwComposer().isConnected(*display->getId());
2274
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002275 if (!hasSyncFramework) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002276 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002277 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002278 }
2279 }
2280
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002281 if (mAnimCompositionPending) {
2282 mAnimCompositionPending = false;
2283
Brian Anderson4e606e32017-03-16 15:34:57 -07002284 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002285 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002286 std::move(presentFenceTime));
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002287 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002288 // The HWC doesn't support present fences, so use the refresh
2289 // timestamp instead.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002290 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002291 mAnimFrameTracker.setActualPresentTime(presentTime);
2292 }
2293 mAnimFrameTracker.advanceFrame();
2294 }
Dan Stozab90cf072015-03-05 11:05:59 -08002295
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002296 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002297 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002298 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002299 }
2300
Vishnu Nair9b079a22020-01-21 14:36:08 -08002301 if (mReusedClientComposition) {
2302 mTimeStats->incrementClientCompositionReusedFrames();
2303 }
2304
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002305 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002306
Alec Mouri717bcb62020-02-10 17:07:19 -08002307 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2308 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2309 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2310
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002311 if (mLastJankDuration > 0) {
2312 ATRACE_NAME("Jank detected");
2313 const int32_t jankyDurationMillis = mLastJankDuration / (1000 * 1000);
2314 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED, jankyDurationMillis,
2315 mMissedFrameJankCount);
2316 mLastJankDuration = -1;
2317 }
2318
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002319 if (isDisplayConnected && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002320 return;
2321 }
2322
2323 nsecs_t currentTime = systemTime();
2324 if (mHasPoweredOff) {
2325 mHasPoweredOff = false;
2326 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002327 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002328 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002329 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2330 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002331 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002332 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002333 }
David Sodman4a36e932017-11-07 14:29:47 -08002334 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002335 }
David Sodman4a36e932017-11-07 14:29:47 -08002336 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002337
Alec Mouri4dde1782019-09-30 17:27:13 -07002338 // Cleanup any outstanding resources due to rendering a prior frame.
2339 getRenderEngine().cleanupPostRender();
2340
Dan Stoza436ccf32018-06-21 12:10:12 -07002341 {
2342 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002343 if (mTexturePool.size() < mTexturePoolSize) {
2344 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002345 const size_t offset = mTexturePool.size();
2346 mTexturePool.resize(mTexturePoolSize);
2347 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2348 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002349 } else if (mTexturePool.size() > mTexturePoolSize) {
2350 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2351 const size_t offset = mTexturePoolSize;
2352 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2353 mTexturePool.resize(mTexturePoolSize);
2354 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002355 }
2356 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002357
Kevin DuBois413287f2019-02-25 08:46:47 -08002358 if (mLumaSampling && mRegionSamplingThread) {
2359 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002360 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002361
2362 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2363 // side-effect of getTotalSize(), so we check that again here
2364 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002365 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002366 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2367 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002368}
2369
Lloyd Pique7eebe692020-04-22 22:40:06 -07002370FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2371 return displayDevice.getViewport().toFloatRect();
2372}
2373
Vishnu Nair4351ad52019-02-11 14:13:02 -08002374void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002375 for (const auto& pair : ON_MAIN_THREAD(mDisplays)) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08002376 const auto& displayDevice = pair.second;
2377 const auto display = displayDevice->getCompositionDisplay();
2378 for (const auto& layer : mDrawingState.layersSortedByZ) {
2379 // only consider the layers on the given layer stack
2380 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002381 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002382 }
2383
Lloyd Pique7eebe692020-04-22 22:40:06 -07002384 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002385 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002386 }
2387 }
2388}
2389
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002390void SurfaceFlinger::postFrame() {
2391 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002392 if (display && getHwComposer().isConnected(*display->getId())) {
2393 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002394 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2395 logFrameStats();
2396 }
2397 }
2398}
2399
Mathias Agopian87baae12012-07-31 12:38:26 -07002400void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002401{
Mathias Agopian841cde52012-03-01 15:44:37 -08002402 ATRACE_CALL();
2403
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002404 // here we keep a copy of the drawing state (that is the state that's
2405 // going to be overwritten by handleTransactionLocked()) outside of
2406 // mStateLock so that the side-effects of the State assignment
2407 // don't happen with mStateLock held (which can cause deadlocks).
2408 State drawingState(mDrawingState);
2409
Mathias Agopianca4d3602011-05-19 15:38:14 -07002410 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002411 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002412
Mathias Agopianca4d3602011-05-19 15:38:14 -07002413 // Here we're guaranteed that some transaction flags are set
2414 // so we can call handleTransactionLocked() unconditionally.
2415 // We call getTransactionFlags(), which will also clear the flags,
2416 // with mStateLock held to guarantee that mCurrentState won't change
2417 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002418
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002419 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002420 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002421 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002422
Mathias Agopianca4d3602011-05-19 15:38:14 -07002423 mDebugInTransaction = 0;
2424 invalidateHwcGeometry();
2425 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002426}
2427
Lloyd Piqueba04e622017-12-14 17:11:26 -08002428void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2429 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 const std::optional<DisplayIdentificationInfo> info =
2431 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002432
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002434 continue;
2435 }
2436
Dominik Laskowski55c85402020-01-21 16:25:47 -08002437 const DisplayId displayId = info->id;
2438 const auto it = mPhysicalDisplayTokens.find(displayId);
2439
Peiyong Line9d809e2020-04-14 13:10:48 -07002440 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002441 if (it == mPhysicalDisplayTokens.end()) {
2442 ALOGV("Creating display %s", to_string(displayId).c_str());
2443
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002444 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002445 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002446 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002447
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002449 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2450 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002451 state.isSecure = true; // All physical displays are currently considered secure.
2452 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002453
2454 sp<IBinder> token = new BBinder();
2455 mCurrentState.displays.add(token, state);
2456 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2457
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002459 } else {
2460 ALOGV("Recreating display %s", to_string(displayId).c_str());
2461
2462 const auto token = it->second;
2463 auto& state = mCurrentState.displays.editValueFor(token);
2464 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002465 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002466 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002467 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002468
Dominik Laskowski55c85402020-01-21 16:25:47 -08002469 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002470 if (index >= 0) {
2471 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2472 mInterceptor->saveDisplayDeletion(state.sequenceId);
2473 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002474 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002475 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002476 }
2477
2478 processDisplayChangesLocked();
2479 }
2480
2481 mPendingHotplugEvents.clear();
2482}
2483
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002484void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002485 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2486 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002487}
2488
Lloyd Pique99d3da52018-01-22 17:48:03 -08002489sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002490 const wp<IBinder>& displayToken,
2491 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002492 const DisplayDeviceState& state,
2493 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002494 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002495 auto displayId = compositionDisplay->getDisplayId();
2496 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002497 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002498 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002499 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002500 creationArgs.hasWideColorGamut = false;
2501 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002502
Dominik Laskowski55c85402020-01-21 16:25:47 -08002503 if (const auto& physical = state.physical) {
2504 creationArgs.connectionType = physical->type;
2505 }
2506
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002507 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002508 creationArgs.isPrimary = isInternalDisplay;
2509
2510 if (useColorManagement && displayId) {
2511 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002512 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002513 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002514 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002516
Dominik Laskowski7e045462018-05-30 13:02:02 -07002517 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002518 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002519 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002520 }
tangrobin6753a022018-08-10 10:58:54 +08002521 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522
Dominik Laskowski075d3172018-05-24 15:50:06 -07002523 if (displayId) {
2524 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002525 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002526 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002527 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002528
Lloyd Pique90c115d2018-09-18 21:39:42 -07002529 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002530 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002531 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002532
Lloyd Pique99d3da52018-01-22 17:48:03 -08002533 // Make sure that composition can never be stalled by a virtual display
2534 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002535 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002536 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002537 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2538 }
2539
Dominik Laskowski718f9602019-11-09 20:01:35 -08002540 creationArgs.physicalOrientation =
2541 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002542
Lloyd Pique99d3da52018-01-22 17:48:03 -08002543 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002544 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002545
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002546 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547
2548 if (maxFrameBufferAcquiredBuffers >= 3) {
2549 nativeWindowSurface->preallocateBuffers();
2550 }
2551
2552 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002553 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002554 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002555 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002556 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002558 display->getCompositionDisplay()->setColorProfile(
2559 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2560 RenderIntent::COLORIMETRIC,
2561 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002562 if (!state.isVirtual()) {
2563 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002564 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2565 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002566 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002568 display->setLayerStack(state.layerStack);
2569 display->setProjection(state.orientation, state.viewport, state.frame);
2570 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002571
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002572 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002573}
2574
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002575void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2576 const DisplayDeviceState& state) {
2577 int width = 0;
2578 int height = 0;
2579 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2580 if (state.physical) {
2581 const auto& activeConfig =
2582 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2583 width = activeConfig->getWidth();
2584 height = activeConfig->getHeight();
2585 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2586 } else if (state.surface != nullptr) {
2587 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2588 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2589 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2590 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2591 int intPixelFormat;
2592 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2593 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2594 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2595 } else {
2596 // Virtual displays without a surface are dormant:
2597 // they have external state (layer stack, projection,
2598 // etc.) but no internal state (i.e. a DisplayDevice).
2599 return;
2600 }
2601
2602 compositionengine::DisplayCreationArgsBuilder builder;
2603 if (const auto& physical = state.physical) {
2604 builder.setPhysical({physical->id, physical->type});
2605 }
2606 builder.setPixels(ui::Size(width, height));
2607 builder.setPixelFormat(pixelFormat);
2608 builder.setIsSecure(state.isSecure);
2609 builder.setLayerStackId(state.layerStack);
2610 builder.setPowerAdvisor(&mPowerAdvisor);
2611 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2612 builder.setName(state.displayName);
2613 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2614
2615 sp<compositionengine::DisplaySurface> displaySurface;
2616 sp<IGraphicBufferProducer> producer;
2617 sp<IGraphicBufferProducer> bqProducer;
2618 sp<IGraphicBufferConsumer> bqConsumer;
2619 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2620
2621 std::optional<DisplayId> displayId = compositionDisplay->getId();
2622
2623 if (state.isVirtual()) {
2624 sp<VirtualDisplaySurface> vds =
2625 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2626 bqConsumer, state.displayName);
2627
2628 displaySurface = vds;
2629 producer = vds;
2630 } else {
2631 ALOGE_IF(state.surface != nullptr,
2632 "adding a supported display, but rendering "
2633 "surface is provided (%p), ignoring it",
2634 state.surface.get());
2635
2636 LOG_ALWAYS_FATAL_IF(!displayId);
2637 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2638 maxGraphicsWidth, maxGraphicsHeight);
2639 producer = bqProducer;
2640 }
2641
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002642 LOG_FATAL_IF(!displaySurface);
2643 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2644 displaySurface, producer);
2645 mDisplays.emplace(displayToken, display);
2646 if (!state.isVirtual()) {
2647 LOG_FATAL_IF(!displayId);
2648 dispatchDisplayHotplugEvent(displayId->value, true);
2649 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002650
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002651 if (display->isPrimary()) {
2652 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002653 }
2654}
2655
2656void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2657 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2658 // Save display ID before disconnecting.
2659 const auto displayId = display->getId();
2660 display->disconnect();
2661
2662 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002663 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002664 dispatchDisplayHotplugEvent(displayId->value, false);
2665 }
2666 }
2667
2668 mDisplays.erase(displayToken);
2669}
2670
2671void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2672 const DisplayDeviceState& currentState,
2673 const DisplayDeviceState& drawingState) {
2674 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2675 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002676 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002677 // changing the surface is like destroying and recreating the DisplayDevice
2678 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2679 display->disconnect();
2680 }
2681 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002682 if (const auto& physical = currentState.physical) {
2683 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2684 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002685 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002686 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002687 const auto display = getDisplayDeviceLocked(displayToken);
2688 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002689 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002690 return;
2691 }
2692
2693 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2694 if (currentState.layerStack != drawingState.layerStack) {
2695 display->setLayerStack(currentState.layerStack);
2696 }
2697 if ((currentState.orientation != drawingState.orientation) ||
2698 (currentState.viewport != drawingState.viewport) ||
2699 (currentState.frame != drawingState.frame)) {
2700 display->setProjection(currentState.orientation, currentState.viewport,
2701 currentState.frame);
2702 }
2703 if (currentState.width != drawingState.width ||
2704 currentState.height != drawingState.height) {
2705 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07002706
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002707 if (display->isPrimary()) {
2708 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2709 }
Dominik Laskowski20134642020-04-20 22:36:44 -07002710
2711 if (mRefreshRateOverlay) {
2712 mRefreshRateOverlay->setViewport(display->getSize());
2713 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002714 }
2715 }
2716}
2717
Lloyd Pique347200f2017-12-14 17:00:15 -08002718void SurfaceFlinger::processDisplayChangesLocked() {
2719 // here we take advantage of Vector's copy-on-write semantics to
2720 // improve performance by skipping the transaction entirely when
2721 // know that the lists are identical
2722 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2723 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2724 if (!curr.isIdenticalTo(draw)) {
2725 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002726
2727 // find the displays that were removed
2728 // (ie: in drawing state but not in current state)
2729 // also handle displays that changed
2730 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002731 for (size_t i = 0; i < draw.size(); i++) {
2732 const wp<IBinder>& displayToken = draw.keyAt(i);
2733 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002734 if (j < 0) {
2735 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002736 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002737 } else {
2738 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002739 const DisplayDeviceState& currentState = curr[j];
2740 const DisplayDeviceState& drawingState = draw[i];
2741 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002742 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002743 }
2744
2745 // find displays that were added
2746 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002747 for (size_t i = 0; i < curr.size(); i++) {
2748 const wp<IBinder>& displayToken = curr.keyAt(i);
2749 if (draw.indexOfKey(displayToken) < 0) {
2750 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002751 }
2752 }
2753 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002754
2755 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002756}
2757
Mathias Agopian87baae12012-07-31 12:38:26 -07002758void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002759{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002760 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2761
Dan Stoza7dde5992015-05-22 09:51:44 -07002762 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002763 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002764 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002765 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002766
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767 /*
2768 * Traversal of the children
2769 * (perform the transaction for each of them if needed)
2770 */
2771
Valerie Haud50e7412020-06-16 17:58:14 -07002772 if ((transactionFlags & eTraversalNeeded) || mForceTraversal) {
2773 mForceTraversal = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002774 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002776 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777
2778 const uint32_t flags = layer->doTransaction(0);
2779 if (flags & Layer::eVisibleRegion)
2780 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002781
2782 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002783 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002784 }
Robert Carr2047fae2016-11-28 14:09:09 -08002785 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786 }
2787
2788 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002789 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790 */
2791
Mathias Agopiane57f2922012-08-09 16:29:12 -07002792 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002793 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002794 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002795 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796
Vishnu Nair6213bd92020-05-08 17:42:25 -07002797 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002798 // The transform hint might have changed for some layers
2799 // (either because a display has changed, or because a layer
2800 // as changed).
2801 //
2802 // Walk through all the layers in currentLayers,
2803 // and update their transform hint.
2804 //
2805 // If a layer is visible only on a single display, then that
2806 // display is used to calculate the hint, otherwise we use the
2807 // default display.
2808 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002809 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002810 // the hint is set before we acquire a buffer from the surface texture.
2811 //
2812 // NOTE: layer transactions have taken place already, so we use their
2813 // drawing state. However, SurfaceFlinger's own transaction has not
2814 // happened yet, so we must use the current state layer list
2815 // (soon to become the drawing state list).
2816 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002817 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002818 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002819 bool first = true;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002820 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08002821 // NOTE: we rely on the fact that layers are sorted by
2822 // layerStack first (so we don't have to traverse the list
2823 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002824 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002825 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002826 currentlayerStack = layerStack;
2827 // figure out if this layerstack is mirrored
2828 // (more than one display) if so, pick the default display,
2829 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002830 hintDisplay = nullptr;
2831 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002832 if (display->getCompositionDisplay()
2833 ->belongsInOutput(layer->getLayerStack(),
2834 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002835 if (hintDisplay) {
2836 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002837 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002838 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002839 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002840 }
2841 }
2842 }
2843 }
Chet Haase91d25932013-04-11 15:24:55 -07002844
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002845 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002846 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2847 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002848
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002849 // could be null when this layer is using a layerStack
2850 // that is not visible on any display. Also can occur at
2851 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002852 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002853 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002854
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002855 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002856 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002857 if (hintDisplay) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002858 layer->updateTransformHint(hintDisplay->getTransformHint());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002859 }
Robert Carr2047fae2016-11-28 14:09:09 -08002860
2861 first = false;
2862 });
Mathias Agopian84300952012-11-21 16:02:13 -08002863 }
2864
Mathias Agopian3559b072012-08-15 13:46:03 -07002865 /*
2866 * Perform our own transaction if needed
2867 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002868
2869 if (mLayersAdded) {
2870 mLayersAdded = false;
2871 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002872 mVisibleRegionsDirty = true;
2873 }
2874
2875 // some layers might have been removed, so
2876 // we need to update the regions they're exposing.
2877 if (mLayersRemoved) {
2878 mLayersRemoved = false;
2879 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002880 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002881 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002882 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002884 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002885 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002886 }
Robert Carr2047fae2016-11-28 14:09:09 -08002887 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888 }
2889
Vishnu Nairec0ab382019-02-13 15:32:56 -08002890 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002892}
2893
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002894void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002895 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002896 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002897 return;
2898 }
2899
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002900 if (mVisibleRegionsDirty || mInputInfoChanged) {
2901 mInputInfoChanged = false;
2902 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002903 } else if (mInputWindowCommands.syncInputWindows) {
2904 // If the caller requested to sync input windows, but there are no
2905 // changes to input windows, notify immediately.
2906 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002907 }
2908
Arthur Hung6cbb9752019-09-05 16:38:18 +08002909 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002910}
2911
2912void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002913 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002914
2915 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Robert Carredd13602020-04-13 17:24:34 -07002916 if (layer->needsInputInfo()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002917 // When calculating the screen bounds we ignore the transparent region since it may
2918 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002919 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002920 }
2921 });
chaviw291d88a2019-02-14 10:33:58 -08002922
2923 mInputFlinger->setInputWindows(inputHandles,
2924 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2925 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002926}
2927
Vishnu Nairec0ab382019-02-13 15:32:56 -08002928void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002929 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002930 mPendingInputWindowCommands.clear();
2931}
2932
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002933void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002934 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002935 for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002936 if (display->getId()) {
2937 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002938 }
2939 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002940
2941 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002942}
2943
Ady Abraham2139f732019-11-13 18:56:40 -08002944void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002945 Scheduler::ConfigEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08002946 // If this is called from the main thread mStateLock must be locked before
2947 // Currently the only way to call this function from the main thread is from
2948 // Sheduler::chooseRefreshRateForContent
2949
2950 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002951 changeRefreshRateLocked(refreshRate, event);
2952}
2953
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002954void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2955 if (mScheduler) {
2956 // In practice it's not allowed to hotplug in/out the primary display once it's been
2957 // connected during startup, but some tests do it, so just warn and return.
2958 ALOGW("Can't re-init scheduler");
2959 return;
2960 }
2961
Ady Abraham2139f732019-11-13 18:56:40 -08002962 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002963 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002964 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002965 primaryDisplayId),
2966 currentConfig);
2967 mRefreshRateStats =
2968 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002969 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002970 mRefreshRateStats->setConfigMode(currentConfig);
2971
Ady Abraham9e16a482019-12-03 17:19:41 -08002972 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2973
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002974 // start the EventThread
2975 mScheduler =
2976 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002977 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002978 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002979 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002980 impl::EventThread::InterceptVSyncsCallback());
2981 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002982 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002983 [this](nsecs_t timestamp) {
2984 mInterceptor->saveVSyncEvent(timestamp);
2985 });
2986
2987 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2988 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002989 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002990
2991 mRegionSamplingThread =
2992 new RegionSamplingThread(*this, *mScheduler,
2993 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002994 // Dispatch a config change request for the primary display on scheduler
2995 // initialization, so that the EventThreads always contain a reference to a
2996 // prior configuration.
2997 //
2998 // This is a bit hacky, but this avoids a back-pointer into the main SF
2999 // classes from EventThread, and there should be no run-time binder cost
3000 // anyway since there are no connected apps at this point.
3001 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07003002 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07003003 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, primaryDisplayId.value,
3004 currentConfig, vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003005}
3006
Mathias Agopian4fec8732012-06-29 14:12:52 -07003007void SurfaceFlinger::commitTransaction()
3008{
Vishnu Nair60db8c02020-04-02 11:55:16 -07003009 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003010 mTransactionPending = false;
3011 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003012 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003013}
3014
Lloyd Pique58e24a32019-08-01 15:50:14 -07003015void SurfaceFlinger::commitTransactionLocked() {
3016 if (!mLayersPendingRemoval.isEmpty()) {
3017 // Notify removed layers now that they can't be drawn from
3018 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003019 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003020
3021 // Ensure any buffers set to display on any children are released.
3022 if (l->isRemovedFromCurrentState()) {
3023 l->latchAndReleaseBuffer();
3024 }
3025
3026 // If the layer has been removed and has no parent, then it will not be reachable
3027 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3028 // ensure we can copy its current to drawing state.
3029 if (!l->getParent()) {
3030 mOffscreenLayers.emplace(l.get());
3031 }
3032 }
3033 mLayersPendingRemoval.clear();
3034 }
3035
3036 // If this transaction is part of a window animation then the next frame
3037 // we composite should be considered an animation as well.
3038 mAnimCompositionPending = mAnimTransactionPending;
3039
3040 mDrawingState = mCurrentState;
3041 // clear the "changed" flags in current state
3042 mCurrentState.colorMatrixChanged = false;
3043
Edgar Arriaga844fa672020-01-16 14:21:42 -08003044 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003045 layer->commitChildList();
3046
3047 // If the layer can be reached when traversing mDrawingState, then the layer is no
3048 // longer offscreen. Remove the layer from the offscreenLayer set.
3049 if (mOffscreenLayers.count(layer)) {
3050 mOffscreenLayers.erase(layer);
3051 }
3052 });
3053
3054 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003055 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003056}
3057
chaviw74d90ad2019-04-26 14:45:26 -07003058void SurfaceFlinger::commitOffscreenLayers() {
3059 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003060 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003061 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3062 if (!trFlags) return;
3063
3064 layer->doTransaction(0);
3065 layer->commitChildList();
3066 });
3067 }
3068}
3069
Chia-I Wuab0c3192017-08-01 11:29:00 -07003070void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07003071 for (const auto& [token, displayDevice] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003072 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003073 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003074 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003075 }
3076 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003077}
3078
Dan Stoza6b9454d2014-11-07 16:00:59 -08003079bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080{
Ady Abraham09bd3922019-04-08 10:44:56 -07003081 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003082 ALOGV("handlePageFlip");
3083
Brian Andersond6927fb2016-07-23 23:37:30 -07003084 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003085
Mathias Agopian4fec8732012-06-29 14:12:52 -07003086 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003087 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003088 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003089
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003090 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3091
Eric Penner51c59cd2014-07-28 19:51:58 -07003092 // Store the set of layers that need updates. This set must not change as
3093 // buffers are being latched, as this could result in a deadlock.
3094 // Example: Two producers share the same command stream and:
3095 // 1.) Layer 0 is latched
3096 // 2.) Layer 0 gets a new frame
3097 // 2.) Layer 1 gets a new frame
3098 // 3.) Layer 1 is latched.
3099 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3100 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003101 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003102 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003103 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003104 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003105 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003106 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003107 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003108 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003109 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003110 } else {
3111 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003112 }
Robert Carr2047fae2016-11-28 14:09:09 -08003113 });
3114
chaviw49a108c2019-08-12 11:23:06 -07003115 // The client can continue submitting buffers for offscreen layers, but they will not
3116 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3117 // layers to ensure dequeueBuffer doesn't block indefinitely.
3118 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003119 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003120 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3121 }
3122
Lloyd Piquef2c79392018-12-20 16:23:33 -08003123 if (!mLayersWithQueuedFrames.empty()) {
3124 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3125 // writes to Layer current state. See also b/119481871
3126 Mutex::Autolock lock(mStateLock);
3127
3128 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003129 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003130 mLayersPendingRefresh.push_back(layer);
3131 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003132 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003133 if (layer->isBufferLatched()) {
3134 newDataLatched = true;
3135 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003136 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003137 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003138
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003139 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003140
3141 // If we will need to wake up at some time in the future to deal with a
3142 // queued frame that shouldn't be displayed during this vsync period, wake
3143 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003144 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003145 signalLayerUpdate();
3146 }
3147
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003148 // enter boot animation on first buffer latch
3149 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3150 ALOGI("Enter boot animation");
3151 mBootStage = BootStage::BOOTANIMATION;
3152 }
3153
Edgar Arriaga844fa672020-01-16 14:21:42 -08003154 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003155
Dan Stoza6b9454d2014-11-07 16:00:59 -08003156 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003157 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158}
3159
Mathias Agopianad456f92011-01-13 17:53:01 -08003160void SurfaceFlinger::invalidateHwcGeometry()
3161{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003162 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003163}
3164
Robert Carrc0df3122019-04-11 13:18:21 -07003165status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3166 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3167 const sp<IBinder>& parentHandle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003168 const sp<Layer>& parentLayer, bool addToCurrentState,
3169 uint32_t* outTransformHint) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003170 // add this layer to the current state list
3171 {
3172 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003173 sp<Layer> parent;
3174 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003175 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003176 if (parent == nullptr) {
3177 return NAME_NOT_FOUND;
3178 }
3179 } else {
3180 parent = parentLayer;
3181 }
3182
Ady Abraham0a525092020-03-03 12:51:24 -08003183 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003184 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003185 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003186 return NO_MEMORY;
3187 }
Robert Carrc0df3122019-04-11 13:18:21 -07003188
3189 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3190
Robert Carrb89ea9d2018-12-10 13:01:14 -08003191 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003192 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003193 } else if (parent == nullptr) {
3194 lbc->onRemovedFromCurrentState();
3195 } else if (parent->isRemovedFromCurrentState()) {
3196 parent->addChild(lbc);
3197 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003198 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003199 parent->addChild(lbc);
3200 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003201
Yiwei Zhang243b3782018-05-15 17:40:04 -07003202 if (gbc != nullptr) {
3203 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3204 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3205 mMaxGraphicBufferProducerListSize,
3206 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3207 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003208 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003209 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003210
3211 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07003212 lbc->updateTransformHint(display->getTransformHint());
Vishnu Nair6213bd92020-05-08 17:42:25 -07003213 }
3214 if (outTransformHint) {
3215 *outTransformHint = lbc->getTransformHint();
3216 }
3217
Robert Carr1f0a16a2016-10-24 16:27:39 -07003218 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003219 }
3220
Mathias Agopian96f08192010-06-02 23:28:45 -07003221 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003222 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003223
Dan Stoza7d89d062015-04-30 13:29:25 -07003224 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003225}
3226
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003227void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3228 static_cast<void>(schedule([=] {
3229 Mutex::Autolock lock(mStateLock);
3230 mGraphicBufferProducerList.erase(binder);
3231 }));
3232}
3233
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003234uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003235 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003236}
3237
Mathias Agopian3f844832013-08-07 21:24:32 -07003238uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003239 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240}
3241
Mathias Agopian3f844832013-08-07 21:24:32 -07003242uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ady Abrahambf1349c2020-06-12 14:26:18 -07003243 return setTransactionFlags(flags, Scheduler::TransactionStart::Normal);
Dan Stoza84d619e2018-03-28 17:07:36 -07003244}
3245
3246uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003247 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003248 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003249 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003250 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003251 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252 }
3253 return old;
3254}
3255
Valerie Haud50e7412020-06-16 17:58:14 -07003256void SurfaceFlinger::setTraversalNeeded() {
3257 mForceTraversal = true;
Robert Carr7ec777d2020-05-29 12:02:51 -07003258}
3259
Marissa Wall713b63f2018-10-17 15:42:43 -07003260bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003261 // to prevent onHandleDestroyed from being called while the lock is held,
3262 // we must keep a copy of the transactions (specifically the composer
3263 // states) around outside the scope of the lock
3264 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003265 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003266 {
3267 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003268
Valerie Haufce31b82019-04-30 16:41:14 -07003269 auto it = mTransactionQueues.begin();
3270 while (it != mTransactionQueues.end()) {
3271 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003272
Valerie Haufce31b82019-04-30 16:41:14 -07003273 while (!transactionQueue.empty()) {
3274 const auto& transaction = transactionQueue.front();
3275 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3276 transaction.states)) {
3277 setTransactionFlags(eTransactionFlushNeeded);
3278 break;
3279 }
3280 transactions.push_back(transaction);
3281 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3282 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003283 transaction.buffer, transaction.postTime,
3284 transaction.privileged, transaction.hasListenerCallbacks,
3285 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003286 transactionQueue.pop();
3287 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003288 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003289
Valerie Haufce31b82019-04-30 16:41:14 -07003290 if (transactionQueue.empty()) {
3291 it = mTransactionQueues.erase(it);
3292 mTransactionCV.broadcast();
3293 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003294 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003295 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003296 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003297 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003298 return flushedATransaction;
3299}
3300
3301bool SurfaceFlinger::transactionFlushNeeded() {
3302 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003303}
3304
chaviwca27f252018-02-06 16:46:39 -08003305
Marissa Wall17b4e452018-12-26 16:32:34 -08003306bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3307 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003308
3309 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003310 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3311 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3312 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3313 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3314 return false;
3315 }
3316
Marissa Wall713b63f2018-10-17 15:42:43 -07003317 for (const ComposerState& state : states) {
3318 const layer_state_t& s = state.state;
3319 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3320 continue;
3321 }
3322 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003323 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003324 }
3325 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003326 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003327}
3328
Valerie Hau9dab9732019-08-20 09:29:25 -07003329void SurfaceFlinger::setTransactionState(
3330 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3331 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3332 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3333 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003334 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003335
Valerie Haubc6ddb12019-03-08 11:10:15 -08003336 const int64_t postTime = systemTime();
3337
Robert Carr14167e02019-02-13 13:50:55 -08003338 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3339
Mathias Agopian698c0872011-06-28 19:09:31 -07003340 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003341
Marissa Wall713b63f2018-10-17 15:42:43 -07003342 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003343 auto itr = mTransactionQueues.find(applyToken);
3344 // if this is an animation frame, wait until prior animation frame has
3345 // been applied by SF
3346 if (flags & eAnimation) {
3347 while (itr != mTransactionQueues.end()) {
3348 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3349 if (CC_UNLIKELY(err != NO_ERROR)) {
3350 ALOGW_IF(err == TIMED_OUT,
3351 "setTransactionState timed out "
3352 "waiting for animation frame to apply");
3353 break;
3354 }
3355 itr = mTransactionQueues.find(applyToken);
3356 }
3357 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003358
Ady Abraham5facfb12020-04-22 15:18:31 -07003359 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003360 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003361 if (!pendingTransactions) {
3362 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3363 }
3364
3365 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003366 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003367 uncacheBuffer, postTime, privileged,
3368 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003369 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003370 return;
3371 }
3372
Valerie Haubc6ddb12019-03-08 11:10:15 -08003373 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003374 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3375 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003376}
3377
Valerie Hau9dab9732019-08-20 09:29:25 -07003378void SurfaceFlinger::applyTransactionState(
3379 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3380 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3381 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3382 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3383 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003384 uint32_t transactionFlags = 0;
3385
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003386 if (flags & eAnimation) {
3387 // For window updates that are part of an animation we must wait for
3388 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003389 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003390 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003391 if (CC_UNLIKELY(err != NO_ERROR)) {
3392 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003393 // caller after a few seconds.
3394 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3395 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003396 mAnimTransactionPending = false;
3397 break;
3398 }
3399 }
3400 }
3401
chaviwca27f252018-02-06 16:46:39 -08003402 for (const DisplayState& display : displays) {
3403 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003404 }
3405
Valerie Hau9dab9732019-08-20 09:29:25 -07003406 // start and end registration for listeners w/ no surface so they can get their callback. Note
3407 // that listeners with SurfaceControls will start registration during setClientStateLocked
3408 // below.
3409 for (const auto& listener : listenerCallbacks) {
3410 mTransactionCompletedThread.startRegistration(listener);
3411 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003412 }
3413
Valerie Hau9dab9732019-08-20 09:29:25 -07003414 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003415 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003416 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003417 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3418 listenerCallbacksWithSurfaces);
Ady Abraham5def7332020-05-29 16:13:47 -07003419 if ((flags & eAnimation) && state.state.surface) {
3420 if (const auto layer = fromHandleLocked(state.state.surface).promote(); layer) {
3421 mScheduler->recordLayerHistory(layer.get(), desiredPresentTime,
3422 LayerHistory::LayerUpdateType::AnimationTX);
3423 }
3424 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07003425 }
3426
Valerie Hau9dab9732019-08-20 09:29:25 -07003427 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003428 mTransactionCompletedThread.endRegistration(listenerCallback);
3429 }
3430
Marissa Walle2ffb422018-10-12 11:33:52 -07003431 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003432 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003433 mTransactionCompletedThread.sendCallbacks();
3434 }
3435 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003436
chaviw273171b2018-12-26 11:46:30 -08003437 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3438
Marissa Wall947d34e2019-03-29 14:03:53 -07003439 if (uncacheBuffer.isValid()) {
3440 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003441 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003442 }
3443
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003444 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3445 // anyway. This can be used as a flush mechanism for previous async transactions.
3446 // Empty animation transaction can be used to simulate back-pressure, so also force a
3447 // transaction for empty animation transactions.
3448 if (transactionFlags == 0 &&
3449 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003450 transactionFlags = eTransactionNeeded;
3451 }
3452
Marissa Wall06255332019-03-27 13:48:27 -07003453 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3454 // so we don't have to wake up again next frame to preform an uneeded traversal.
3455 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3456 transactionFlags = transactionFlags & (~eTraversalNeeded);
Valerie Haud50e7412020-06-16 17:58:14 -07003457 mForceTraversal = true;
Marissa Wall06255332019-03-27 13:48:27 -07003458 }
3459
Ady Abrahambf1349c2020-06-12 14:26:18 -07003460 const auto transactionStart = [](uint32_t flags) {
3461 if (flags & eEarlyWakeup) {
3462 return Scheduler::TransactionStart::Early;
3463 }
3464 if (flags & eExplicitEarlyWakeupEnd) {
3465 return Scheduler::TransactionStart::EarlyEnd;
3466 }
3467 if (flags & eExplicitEarlyWakeupStart) {
3468 return Scheduler::TransactionStart::EarlyStart;
3469 }
3470 return Scheduler::TransactionStart::Normal;
3471 }(flags);
3472
Mathias Agopian386aa982011-11-07 21:58:03 -08003473 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003474 if (mInterceptor->isEnabled()) {
3475 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003476 }
Irvel468051e2016-06-13 16:44:44 -07003477
Ady Abrahambf1349c2020-06-12 14:26:18 -07003478 // TODO(b/159125966): Remove eEarlyWakeup completly as no client should use this flag
3479 if (flags & eEarlyWakeup) {
3480 ALOGW("eEarlyWakeup is deprecated. Use eExplicitEarlyWakeup[Start|End]");
3481 }
3482
3483 if (!privileged && (flags & (eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd))) {
3484 ALOGE("Only WindowManager is allowed to use eExplicitEarlyWakeup[Start|End] flags");
3485 flags &= ~(eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd);
3486 }
3487
Mathias Agopian386aa982011-11-07 21:58:03 -08003488 // this triggers the transaction
Ady Abrahambf1349c2020-06-12 14:26:18 -07003489 setTransactionFlags(transactionFlags, transactionStart);
Mathias Agopian386aa982011-11-07 21:58:03 -08003490
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003491 if (flags & eAnimation) {
3492 mAnimTransactionPending = true;
3493 }
Robert Carr238f4a22020-04-29 13:04:02 -07003494
3495 // if this is a synchronous transaction, wait for it to take effect
3496 // before returning.
3497 const bool synchronous = flags & eSynchronous;
3498 const bool syncInput = inputWindowCommands.syncInputWindows;
3499 if (!synchronous && !syncInput) {
3500 return;
3501 }
3502
3503 if (synchronous) {
3504 mTransactionPending = true;
3505 }
3506 if (syncInput) {
chaviw4fe36852019-04-15 16:25:49 -07003507 mPendingSyncInputWindows = true;
3508 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003509
Robert Carr238f4a22020-04-29 13:04:02 -07003510
Valerie Hau0779ded2019-03-19 12:43:04 -07003511 // applyTransactionState can be called by either the main SF thread or by
3512 // another process through setTransactionState. While a given process may wish
3513 // to wait on synchronous transactions, the main SF thread should never
3514 // be blocked. Therefore, we only wait if isMainThread is false.
3515 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003516 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3517 if (CC_UNLIKELY(err != NO_ERROR)) {
3518 // just in case something goes wrong in SF, return to the
3519 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003520 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3521 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003522 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003523 break;
3524 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003525 }
Ady Abrahambf1349c2020-06-12 14:26:18 -07003526 } else {
3527 // even if a transaction is not needed, we need to update VsyncModulator
3528 // about explicit early indications
3529 if (transactionStart == Scheduler::TransactionStart::EarlyStart ||
3530 transactionStart == Scheduler::TransactionStart::EarlyEnd) {
3531 mVSyncModulator->setTransactionStart(transactionStart);
3532 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003533 }
3534}
3535
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003536uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3537 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3538 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003539
Mathias Agopiane57f2922012-08-09 16:29:12 -07003540 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003541 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3542
3543 const uint32_t what = s.what;
3544 if (what & DisplayState::eSurfaceChanged) {
3545 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3546 state.surface = s.surface;
3547 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003548 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003549 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003550 if (what & DisplayState::eLayerStackChanged) {
3551 if (state.layerStack != s.layerStack) {
3552 state.layerStack = s.layerStack;
3553 flags |= eDisplayTransactionNeeded;
3554 }
3555 }
3556 if (what & DisplayState::eDisplayProjectionChanged) {
3557 if (state.orientation != s.orientation) {
3558 state.orientation = s.orientation;
3559 flags |= eDisplayTransactionNeeded;
3560 }
3561 if (state.frame != s.frame) {
3562 state.frame = s.frame;
3563 flags |= eDisplayTransactionNeeded;
3564 }
3565 if (state.viewport != s.viewport) {
3566 state.viewport = s.viewport;
3567 flags |= eDisplayTransactionNeeded;
3568 }
3569 }
3570 if (what & DisplayState::eDisplaySizeChanged) {
3571 if (state.width != s.width) {
3572 state.width = s.width;
3573 flags |= eDisplayTransactionNeeded;
3574 }
3575 if (state.height != s.height) {
3576 state.height = s.height;
3577 flags |= eDisplayTransactionNeeded;
3578 }
3579 }
3580
Mathias Agopiane57f2922012-08-09 16:29:12 -07003581 return flags;
3582}
3583
Steven Thomasd4071902020-03-24 16:02:53 -07003584bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003585 IPCThreadState* ipc = IPCThreadState::self();
3586 const int pid = ipc->getCallingPid();
3587 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003588 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003589 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3590 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003591 return false;
3592 }
3593 return true;
3594}
3595
Marissa Wall3dad52d2019-03-22 14:03:19 -07003596uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003597 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3598 bool privileged,
3599 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003600 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003601
Valerie Hau9dab9732019-08-20 09:29:25 -07003602 for (auto& listener : s.listeners) {
3603 // note that startRegistration will not re-register if the listener has
3604 // already be registered for a prior surface control
3605 mTransactionCompletedThread.startRegistration(listener);
3606 listenerCallbacks.insert(listener);
3607 }
3608
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003609 sp<Layer> layer = nullptr;
3610 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003611 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003612 } else {
3613 // The client may provide us a null handle. Treat it as if the layer was removed.
3614 ALOGW("Attempt to set client state with a null layer handle");
3615 }
chaviw8b3871a2017-11-01 17:41:01 -07003616 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003617 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003618 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003619 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003620 }
chaviw8b3871a2017-11-01 17:41:01 -07003621 return 0;
3622 }
3623
chaviw8b3871a2017-11-01 17:41:01 -07003624 uint32_t flags = 0;
3625
Garfield Tan8a3083e2018-12-03 13:21:07 -08003626 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003627
3628 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3629 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003630 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003631 layer->pushPendingState();
3632 }
3633
Valerie Hau871d6352020-01-29 08:44:02 -08003634 // Only set by BLAST adapter layers
3635 if (what & layer_state_t::eProducerDisconnect) {
3636 layer->onDisconnect();
3637 }
3638
chaviw8b3871a2017-11-01 17:41:01 -07003639 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003640 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003641 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003642 }
chaviw8b3871a2017-11-01 17:41:01 -07003643 }
3644 if (what & layer_state_t::eLayerChanged) {
3645 // NOTE: index needs to be calculated before we update the state
3646 const auto& p = layer->getParent();
3647 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003648 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003649 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003650 mCurrentState.layersSortedByZ.removeAt(idx);
3651 mCurrentState.layersSortedByZ.add(layer);
3652 // we need traversal (state changed)
3653 // AND transaction (list changed)
3654 flags |= eTransactionNeeded|eTraversalNeeded;
3655 }
chaviw8b3871a2017-11-01 17:41:01 -07003656 } else {
3657 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003658 flags |= eTransactionNeeded|eTraversalNeeded;
3659 }
3660 }
chaviw8b3871a2017-11-01 17:41:01 -07003661 }
3662 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003663 // NOTE: index needs to be calculated before we update the state
3664 const auto& p = layer->getParent();
3665 if (p == nullptr) {
3666 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3667 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3668 mCurrentState.layersSortedByZ.removeAt(idx);
3669 mCurrentState.layersSortedByZ.add(layer);
3670 // we need traversal (state changed)
3671 // AND transaction (list changed)
3672 flags |= eTransactionNeeded|eTraversalNeeded;
3673 }
3674 } else {
3675 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3676 flags |= eTransactionNeeded|eTraversalNeeded;
3677 }
chaviw8b3871a2017-11-01 17:41:01 -07003678 }
3679 }
3680 if (what & layer_state_t::eSizeChanged) {
3681 if (layer->setSize(s.w, s.h)) {
3682 flags |= eTraversalNeeded;
3683 }
3684 }
3685 if (what & layer_state_t::eAlphaChanged) {
3686 if (layer->setAlpha(s.alpha))
3687 flags |= eTraversalNeeded;
3688 }
3689 if (what & layer_state_t::eColorChanged) {
3690 if (layer->setColor(s.color))
3691 flags |= eTraversalNeeded;
3692 }
Peiyong Lind3788632018-09-18 16:01:31 -07003693 if (what & layer_state_t::eColorTransformChanged) {
3694 if (layer->setColorTransform(s.colorTransform)) {
3695 flags |= eTraversalNeeded;
3696 }
3697 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003698 if (what & layer_state_t::eBackgroundColorChanged) {
3699 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3700 flags |= eTraversalNeeded;
3701 }
3702 }
chaviw8b3871a2017-11-01 17:41:01 -07003703 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003704 // TODO: b/109894387
3705 //
3706 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3707 // rotation. To see the problem observe that if we have a square parent, and a child
3708 // of the same size, then we rotate the child 45 degrees around it's center, the child
3709 // must now be cropped to a non rectangular 8 sided region.
3710 //
3711 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3712 // private API, and the WindowManager only uses rotation in one case, which is on a top
3713 // level layer in which cropping is not an issue.
3714 //
3715 // However given that abuse of rotation matrices could lead to surfaces extending outside
3716 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3717 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3718 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003719 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003720 flags |= eTraversalNeeded;
3721 }
3722 if (what & layer_state_t::eTransparentRegionChanged) {
3723 if (layer->setTransparentRegionHint(s.transparentRegion))
3724 flags |= eTraversalNeeded;
3725 }
3726 if (what & layer_state_t::eFlagsChanged) {
3727 if (layer->setFlags(s.flags, s.mask))
3728 flags |= eTraversalNeeded;
3729 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003730 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003731 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003732 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003733 if (what & layer_state_t::eCornerRadiusChanged) {
3734 if (layer->setCornerRadius(s.cornerRadius))
3735 flags |= eTraversalNeeded;
3736 }
Lucas Dupin130e55c2020-05-26 16:11:18 -07003737 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003738 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3739 }
chaviw8b3871a2017-11-01 17:41:01 -07003740 if (what & layer_state_t::eLayerStackChanged) {
3741 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3742 // We only allow setting layer stacks for top level layers,
3743 // everything else inherits layer stack from its parent.
3744 if (layer->hasParent()) {
3745 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003746 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003747 } else if (idx < 0) {
3748 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003749 "that also does not appear in the top level layer list. Something"
3750 " has gone wrong.",
3751 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003752 } else if (layer->setLayerStack(s.layerStack)) {
3753 mCurrentState.layersSortedByZ.removeAt(idx);
3754 mCurrentState.layersSortedByZ.add(layer);
3755 // we need traversal (state changed)
3756 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07003757 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003758 }
3759 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003760 if (what & layer_state_t::eDeferTransaction_legacy) {
3761 if (s.barrierHandle_legacy != nullptr) {
3762 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3763 } else if (s.barrierGbp_legacy != nullptr) {
3764 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003765 if (authenticateSurfaceTextureLocked(gbp)) {
3766 const auto& otherLayer =
3767 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003768 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003769 } else {
3770 ALOGE("Attempt to defer transaction to to an"
3771 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003772 }
3773 }
chaviw8b3871a2017-11-01 17:41:01 -07003774 // We don't trigger a traversal here because if no other state is
3775 // changed, we don't want this to cause any more work
3776 }
chaviw8b3871a2017-11-01 17:41:01 -07003777 if (what & layer_state_t::eReparentChildren) {
3778 if (layer->reparentChildren(s.reparentHandle)) {
3779 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003780 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003781 }
chaviw8b3871a2017-11-01 17:41:01 -07003782 if (what & layer_state_t::eDetachChildren) {
3783 layer->detachChildren();
3784 }
3785 if (what & layer_state_t::eOverrideScalingModeChanged) {
3786 layer->setOverrideScalingMode(s.overrideScalingMode);
3787 // We don't trigger a traversal here because if no other state is
3788 // changed, we don't want this to cause any more work
3789 }
Marissa Wall61c58622018-07-18 10:12:20 -07003790 if (what & layer_state_t::eTransformChanged) {
3791 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3792 }
3793 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3794 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3795 flags |= eTraversalNeeded;
3796 }
3797 if (what & layer_state_t::eCropChanged) {
3798 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3799 }
Marissa Wall861616d2018-10-22 12:52:23 -07003800 if (what & layer_state_t::eFrameChanged) {
3801 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3802 }
Marissa Wall61c58622018-07-18 10:12:20 -07003803 if (what & layer_state_t::eAcquireFenceChanged) {
3804 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3805 }
3806 if (what & layer_state_t::eDataspaceChanged) {
3807 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3808 }
3809 if (what & layer_state_t::eHdrMetadataChanged) {
3810 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3811 }
3812 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3813 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3814 }
3815 if (what & layer_state_t::eApiChanged) {
3816 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3817 }
3818 if (what & layer_state_t::eSidebandStreamChanged) {
3819 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3820 }
Robert Carr720e5062018-07-30 17:45:14 -07003821 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003822 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003823 layer->setInputInfo(s.inputInfo);
3824 flags |= eTraversalNeeded;
3825 } else {
3826 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3827 }
Robert Carr720e5062018-07-30 17:45:14 -07003828 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003829 if (what & layer_state_t::eMetadataChanged) {
3830 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3831 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003832 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3833 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3834 flags |= eTraversalNeeded;
3835 }
3836 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003837 if (what & layer_state_t::eShadowRadiusChanged) {
3838 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3839 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003840 if (what & layer_state_t::eFrameRateSelectionPriority) {
3841 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3842 flags |= eTraversalNeeded;
3843 }
3844 }
Steven Thomas3172e202020-01-06 19:25:30 -08003845 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003846 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3847 "SurfaceFlinger::setClientStateLocked") &&
3848 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3849 Layer::FrameRate::convertCompatibility(
3850 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003851 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003852 }
Steven Thomas3172e202020-01-06 19:25:30 -08003853 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003854 if (what & layer_state_t::eFixedTransformHintChanged) {
3855 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
3856 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
3857 }
3858 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003859 // This has to happen after we reparent children because when we reparent to null we remove
3860 // child layers from current state and remove its relative z. If the children are reparented in
3861 // the same transaction, then we have to make sure we reparent the children first so we do not
3862 // lose its relative z order.
3863 if (what & layer_state_t::eReparent) {
3864 bool hadParent = layer->hasParent();
3865 if (layer->reparent(s.parentHandleForChild)) {
3866 if (!hadParent) {
3867 mCurrentState.layersSortedByZ.remove(layer);
3868 }
3869 flags |= eTransactionNeeded | eTraversalNeeded;
3870 }
3871 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003872 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003873 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3874 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003875 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3876 }
3877 }
Marissa Wall78b72202019-03-15 14:58:34 -07003878 bool bufferChanged = what & layer_state_t::eBufferChanged;
3879 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3880 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003881 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003882 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003883 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3884 if (success) {
3885 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3886 success = ClientCache::getInstance()
3887 .registerErasedRecipient(s.cachedBuffer,
3888 wp<ClientCache::ErasedRecipient>(this));
3889 if (!success) {
3890 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3891 }
3892 }
Marissa Wall78b72202019-03-15 14:58:34 -07003893 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003894 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003895 } else if (bufferChanged) {
3896 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003897 }
Marissa Wall78b72202019-03-15 14:58:34 -07003898 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003899 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3900 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003901 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003902 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003903 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003904 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3905 // Do not put anything that updates layer state or modifies flags after
3906 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003907 return flags;
3908}
3909
chaviw273171b2018-12-26 11:46:30 -08003910uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3911 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003912 if (inputWindowCommands.syncInputWindows) {
3913 flags |= eTraversalNeeded;
3914 }
3915
Vishnu Nairec0ab382019-02-13 15:32:56 -08003916 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003917 return flags;
3918}
3919
chaviwfe94a222019-08-21 13:52:59 -07003920status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3921 sp<IBinder>* outHandle) {
3922 if (!mirrorFromHandle) {
3923 return NAME_NOT_FOUND;
3924 }
3925
3926 sp<Layer> mirrorLayer;
3927 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003928 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003929
3930 {
3931 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003932 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003933 if (!mirrorFrom) {
3934 return NAME_NOT_FOUND;
3935 }
3936
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003937 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3938 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003939 if (result != NO_ERROR) {
3940 return result;
3941 }
3942
3943 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3944 }
3945
Vishnu Nair6213bd92020-05-08 17:42:25 -07003946 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false,
3947 nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07003948}
3949
Marissa Wall2d814fb2019-04-09 18:52:57 +00003950status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3951 uint32_t h, PixelFormat format, uint32_t flags,
3952 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003953 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003954 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3955 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003956 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003957 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003958 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003959 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003960 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003961
Robert Carrc0df3122019-04-11 13:18:21 -07003962 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3963 "Expected only one of parentLayer or parentHandle to be non-null. "
3964 "Programmer error?");
3965
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003966 status_t result = NO_ERROR;
3967
3968 sp<Layer> layer;
3969
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003970 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003971
Evan Roskya1f1e152019-01-24 16:17:46 -08003972 bool primaryDisplayOnly = false;
3973
3974 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3975 // TODO b/64227542
3976 if (metadata.has(METADATA_WINDOW_TYPE)) {
3977 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3978 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003979 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003980 primaryDisplayOnly = true;
3981 }
3982 }
3983
Mathias Agopian3165cc22012-08-08 19:42:09 -07003984 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003985 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003986 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3987 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003988
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003989 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003990 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003991 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003992 std::move(metadata), handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003993 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003994 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003995 // check if buffer size is set for color layer.
3996 if (w > 0 || h > 0) {
3997 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3998 int(w), int(h));
3999 return BAD_VALUE;
4000 }
4001
Vishnu Nairfa247b12020-02-11 08:58:26 -08004002 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
4003 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004004 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004005 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004006 // check if buffer size is set for container layer.
4007 if (w > 0 || h > 0) {
4008 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4009 int(w), int(h));
4010 return BAD_VALUE;
4011 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004012 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
4013 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004014 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004015 default:
4016 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004017 break;
4018 }
4019
Dan Stoza7d89d062015-04-30 13:29:25 -07004020 if (result != NO_ERROR) {
4021 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004022 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004023
Evan Roskya1f1e152019-01-24 16:17:46 -08004024 if (primaryDisplayOnly) {
4025 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004026 }
4027
Robert Carrb89ea9d2018-12-10 13:01:14 -08004028 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004029 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004030 addToCurrentState, outTransformHint);
Dan Stoza7d89d062015-04-30 13:29:25 -07004031 if (result != NO_ERROR) {
4032 return result;
4033 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004034 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004035
4036 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004037 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038}
4039
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004040std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
4041 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06004042
4043 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004044 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004045
Dan Stoza436ccf32018-06-21 12:10:12 -07004046 // Grab the state lock since we're accessing mCurrentState
4047 Mutex::Autolock lock(mStateLock);
4048
Cody Northropbc755282017-03-31 12:00:08 -06004049 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004050 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06004051 while (matchFound) {
4052 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08004053 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004054 if (layer->getName() == uniqueName) {
4055 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004056 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004057 }
4058 });
4059 }
4060
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004061 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004062 return uniqueName;
4063}
4064
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004065status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07004066 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004067 LayerMetadata metadata, PixelFormat& format,
4068 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004069 sp<IGraphicBufferProducer>* gbp,
4070 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004071 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004072 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073 case PIXEL_FORMAT_TRANSPARENT:
4074 case PIXEL_FORMAT_TRANSLUCENT:
4075 format = PIXEL_FORMAT_RGBA_8888;
4076 break;
4077 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004078 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004079 break;
4080 }
4081
chaviwb4c6e582019-08-16 14:35:07 -07004082 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004083 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004084 args.textureName = getNewTexture();
4085 {
4086 // Grab the SF state lock during this since it's the only safe way to access
4087 // RenderEngine when creating a BufferLayerConsumer
4088 // TODO: Check if this lock is still needed here
4089 Mutex::Autolock lock(mStateLock);
4090 layer = getFactory().createBufferQueueLayer(args);
4091 }
4092
Marissa Wallfd668622018-05-10 10:21:13 -07004093 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004094 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004095 *handle = layer->getHandle();
4096 *gbp = layer->getProducer();
4097 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004098 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004099
Marissa Wallfd668622018-05-10 10:21:13 -07004100 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004101 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004102}
4103
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004104status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004105 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004106 LayerMetadata metadata, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004107 sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004108 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004109 args.textureName = getNewTexture();
4110 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07004111 *handle = layer->getHandle();
4112 *outLayer = layer;
4113
4114 return NO_ERROR;
4115}
4116
Vishnu Nairfa247b12020-02-11 08:58:26 -08004117status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4118 uint32_t h, uint32_t flags, LayerMetadata metadata,
4119 sp<IBinder>* handle, sp<Layer>* outLayer) {
4120 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004121 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004122 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004123 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004124}
4125
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004126status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004127 uint32_t w, uint32_t h, uint32_t flags,
4128 LayerMetadata metadata, sp<IBinder>* handle,
4129 sp<Layer>* outLayer) {
4130 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004131 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004132 *handle = (*outLayer)->getHandle();
4133 return NO_ERROR;
4134}
4135
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004136void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004137 mLayersPendingRemoval.add(layer);
4138 mLayersRemoved = true;
4139 setTransactionFlags(eTransactionNeeded);
4140}
4141
Robert Carr695d5282018-12-18 15:27:58 -08004142void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004143{
Robert Carr2e102c92018-10-23 12:11:15 -07004144 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004145 // If a layer has a parent, we allow it to out-live it's handle
4146 // with the idea that the parent holds a reference and will eventually
4147 // be cleaned up. However no one cleans up the top-level so we do so
4148 // here.
4149 if (layer->getParent() == nullptr) {
4150 mCurrentState.layersSortedByZ.remove(layer);
4151 }
4152 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004153
4154 auto it = mLayersByLocalBinderToken.begin();
4155 while (it != mLayersByLocalBinderToken.end()) {
4156 if (it->second == layer) {
4157 it = mLayersByLocalBinderToken.erase(it);
4158 } else {
4159 it++;
4160 }
4161 }
4162
Robert Carr695d5282018-12-18 15:27:58 -08004163 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004164}
4165
Mathias Agopianb60314a2012-04-10 22:09:54 -07004166// ---------------------------------------------------------------------------
4167
Andy McFadden13a082e2012-08-24 10:16:42 -07004168void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004169 const auto display = getDefaultDisplayDeviceLocked();
4170 if (!display) return;
4171
4172 const sp<IBinder> token = display->getDisplayToken().promote();
4173 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004174
Jesse Hall01e29052013-02-19 16:13:35 -08004175 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004176 Vector<ComposerState> state;
4177 Vector<DisplayState> displays;
4178 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004179 d.what = DisplayState::eDisplayProjectionChanged |
4180 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004181 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004182 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004183 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004184 d.frame.makeInvalid();
4185 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004186 d.width = 0;
4187 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004188 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004189 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4190 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004191
Peiyong Lin65248e02020-04-18 21:15:07 -07004192 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004193
Dominik Laskowski83b88212018-12-11 13:34:06 -08004194 const nsecs_t vsyncPeriod = getVsyncPeriod();
4195 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004196
Brian Andersond0010582017-03-07 13:20:31 -08004197 // Use phase of 0 since phase is not known.
4198 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004199 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004200 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004201}
4202
4203void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004204 // Async since we may be called from the main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004205 static_cast<void>(schedule([this]() MAIN_THREAD { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004206}
4207
Peiyong Lin65248e02020-04-18 21:15:07 -07004208void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004209 if (display->isVirtual()) {
4210 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004211 return;
4212 }
4213
Dominik Laskowski075d3172018-05-24 15:50:06 -07004214 const auto displayId = display->getId();
4215 LOG_ALWAYS_FATAL_IF(!displayId);
4216
Dominik Laskowski34157762018-10-31 13:07:19 -07004217 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004218
Peiyong Lin65248e02020-04-18 21:15:07 -07004219 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004220 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004221 return;
4222 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004223
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004224 display->setPowerMode(mode);
4225
Lloyd Pique4dccc412018-01-22 17:21:36 -08004226 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004227 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004228 }
4229
Peiyong Lin65248e02020-04-18 21:15:07 -07004230 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004231 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4232 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4233 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004234 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004235 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004236 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004237 mScheduler->onScreenAcquired(mAppConnectionHandle);
4238 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004239 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004240
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004241 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004242 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004243 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004244 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004245 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004246 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4247 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004248 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004249 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004250 mScheduler->disableHardwareVsync(true);
4251 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004252 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004253
Ady Abraham27c70212019-06-11 10:52:26 -07004254 // Make sure HWVsync is disabled before turning off the display
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004255 getHwComposer().setVsyncEnabled(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004256
Dominik Laskowski075d3172018-05-24 15:50:06 -07004257 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004258 mVisibleRegionsDirty = true;
4259 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004260 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004261 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004262 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004263 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004264 mScheduler->onScreenAcquired(mAppConnectionHandle);
4265 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004266 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004267 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004268 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004269 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004270 mScheduler->disableHardwareVsync(true);
4271 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004272 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004273 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004274 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004275 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004276 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004277 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004278
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004279 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004280 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004281 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004282 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004283 }
4284
Dominik Laskowski34157762018-10-31 13:07:19 -07004285 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004286}
4287
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004288void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004289 schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004290 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004291 if (!display) {
4292 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4293 displayToken.get());
4294 } else if (display->isVirtual()) {
4295 ALOGW("Attempt to set power mode %d for virtual display", mode);
4296 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004297 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004298 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004299 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004300}
4301
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004302status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004303 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004304
Mathias Agopianbd115332013-04-18 16:41:04 -07004305 IPCThreadState* ipc = IPCThreadState::self();
4306 const int pid = ipc->getCallingPid();
4307 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004308
Mathias Agopianbd115332013-04-18 16:41:04 -07004309 if ((uid != AID_SHELL) &&
4310 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004311 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4312 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004313 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004314 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004315 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004316 {"--dispsync"s,
4317 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004318 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004319 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4320 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4321 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4322 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4323 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4324 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004325 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004326 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4327 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004328
Dominik Laskowskic2867142019-01-21 11:33:38 -08004329 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004330
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004331 bool dumpLayers = true;
4332 {
4333 TimedLock lock(mStateLock, s2ns(1), __FUNCTION__);
4334 if (!lock.locked()) {
4335 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4336 strerror(-lock.status), lock.status);
4337 }
4338
4339 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4340 (it->second)(args, asProto, result);
4341 dumpLayers = false;
4342 } else if (!asProto) {
4343 dumpAllLocked(args, result);
4344 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004345 }
4346
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004347 if (dumpLayers) {
Dominik Laskowski46470112019-08-02 13:13:11 -07004348 const LayersProto layersProto = dumpProtoFromMainThread();
4349 if (asProto) {
4350 result.append(layersProto.SerializeAsString());
4351 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004352 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004353 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4354 result.append(LayerProtoParser::layerTreeToString(layerTree));
4355 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004356 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004357 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004358 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004359 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004360 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004361 return NO_ERROR;
4362}
4363
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004364status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4365 if (asProto && mTracing.isEnabled()) {
4366 mTracing.writeToFileAsync();
4367 }
4368
4369 return doDump(fd, DumpArgs(), asProto);
4370}
4371
Dominik Laskowskic2867142019-01-21 11:33:38 -08004372void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004373 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004374 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004375}
4376
Dominik Laskowskic2867142019-01-21 11:33:38 -08004377void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004378 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004379
Dominik Laskowskic2867142019-01-21 11:33:38 -08004380 if (args.size() > 1) {
4381 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004382 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004383 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004384 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004385 }
Robert Carr2047fae2016-11-28 14:09:09 -08004386 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004387 } else {
4388 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004389 }
4390}
4391
Dominik Laskowskic2867142019-01-21 11:33:38 -08004392void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004393 const bool clearAll = args.size() < 2;
4394 const auto name = clearAll ? String8() : String8(args[1]);
4395
Edgar Arriaga844fa672020-01-16 14:21:42 -08004396 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004397 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004398 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004399 }
Robert Carr2047fae2016-11-28 14:09:09 -08004400 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004401
Svetoslavd85084b2014-03-20 10:28:31 -07004402 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004403}
4404
Dominik Laskowskic2867142019-01-21 11:33:38 -08004405void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4406 mTimeStats->parseArgs(asProto, args, result);
4407}
4408
Jamie Gennis6547ff42013-07-16 20:12:42 -07004409// This should only be called from the main thread. Otherwise it would need
4410// the lock and should use mCurrentState rather than mDrawingState.
4411void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004412 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004413 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004414 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004415
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004416 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004417}
4418
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004420 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004421
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004422 if (isLayerTripleBufferingDisabled())
4423 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004424
Yiwei Zhang5434a782018-12-05 18:06:32 -08004425 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4426 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4427 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4428 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4429 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4430 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004431 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004432}
4433
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004434void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004435 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004436
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004437 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004438 result.append("\n");
4439
Ady Abraham9e16a482019-12-03 17:19:41 -08004440 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004441 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004442 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004443 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004444
Steven Thomasd4071902020-03-24 16:02:53 -07004445 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004446 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004447 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004448 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4449 policy.defaultConfig.value(), policy.primaryRange.min, policy.primaryRange.max,
4450 policy.appRequestRange.min, policy.appRequestRange.max);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004451 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4452 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004453 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4454 if (currentPolicy != policy) {
4455 StringAppendF(&result,
4456 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004457 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4458 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
4459 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
4460 currentPolicy.appRequestRange.max);
Ady Abraham07e54702020-04-16 15:05:37 -07004461 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004462
Ana Krulecc2870422019-01-29 19:00:58 -08004463 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004464 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004465}
4466
Yiwei Zhang5434a782018-12-05 18:06:32 -08004467void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4468 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004469 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4470 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004471 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004472 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004473 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004474 }
David Sodman4a36e932017-11-07 14:29:47 -08004475 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004476 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004477 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004478 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4479 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004480}
4481
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004482void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4483 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004484 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4485 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004486 for (const auto& segment : history) {
4487 if (!segment.usedThirdBuffer) {
4488 stats.twoBufferTime += segment.totalTime;
4489 }
4490 if (segment.occupancyAverage < 1.0f) {
4491 stats.doubleBufferedTime += segment.totalTime;
4492 } else if (segment.occupancyAverage < 2.0f) {
4493 stats.tripleBufferedTime += segment.totalTime;
4494 }
4495 ++stats.numSegments;
4496 stats.totalTime += segment.totalTime;
4497 }
4498}
4499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4501 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004502
4503 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4504 const size_t count = currentLayers.size();
4505 for (size_t i=0 ; i<count ; i++) {
4506 currentLayers[i]->dumpFrameEvents(result);
4507 }
4508}
4509
Yiwei Zhang5434a782018-12-05 18:06:32 -08004510void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004511 result.append("Buffering stats:\n");
4512 result.append(" [Layer name] <Active time> <Two buffer> "
4513 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004514 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004515 typedef std::tuple<std::string, float, float, float> BufferTuple;
4516 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004517 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004518 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004519 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004520 if (stats.numSegments == 0) {
4521 continue;
4522 }
4523 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4524 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4525 stats.totalTime;
4526 float doubleBufferRatio = static_cast<float>(
4527 stats.doubleBufferedTime) / stats.totalTime;
4528 float tripleBufferRatio = static_cast<float>(
4529 stats.tripleBufferedTime) / stats.totalTime;
4530 sorted.insert({activeTime, {name, twoBufferRatio,
4531 doubleBufferRatio, tripleBufferRatio}});
4532 }
4533 for (const auto& sortedPair : sorted) {
4534 float activeTime = sortedPair.first;
4535 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4537 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004538 }
4539 result.append("\n");
4540}
4541
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004543 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004544 const auto displayId = display->getId();
4545 if (!displayId) {
4546 continue;
4547 }
4548 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004549 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004550 continue;
4551 }
4552
Yiwei Zhang5434a782018-12-05 18:06:32 -08004553 StringAppendF(&result,
4554 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4555 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004556 uint8_t port;
4557 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004558 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004559 result.append("no identification data\n");
4560 continue;
4561 }
4562
4563 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004564 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004565 continue;
4566 }
4567
4568 const auto edid = parseEdid(data);
4569 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004570 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004571 continue;
4572 }
4573
Yiwei Zhang5434a782018-12-05 18:06:32 -08004574 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004575 result.append(edid->displayName.data(), edid->displayName.length());
4576 result.append("\"\n");
4577 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004578}
4579
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004580void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4581 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004582 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004583 uint8_t port;
4584 DisplayIdentificationData data;
4585
4586 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4587 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4588 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4589 }
4590}
4591
Yiwei Zhang5434a782018-12-05 18:06:32 -08004592void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004593 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004594 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4595 StringAppendF(&result, "DisplayColorSetting: %s\n",
4596 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004597
4598 // TODO: print out if wide-color mode is active or not
4599
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004600 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004601 const auto displayId = display->getId();
4602 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004603 continue;
4604 }
4605
Yiwei Zhang5434a782018-12-05 18:06:32 -08004606 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004607 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004608 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004610 }
4611
Lloyd Pique32cbe282018-10-19 13:09:22 -07004612 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004613 StringAppendF(&result, " Current color mode: %s (%d)\n",
4614 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004615 }
4616 result.append("\n");
4617}
4618
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004619LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4620 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004621 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004622
chaviw1d044282017-09-27 12:19:28 -07004623 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004624 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004625 layer->writeToProto(layersProto, traceFlags, display.get());
chaviw08f3cb22020-01-13 13:17:21 -08004626 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004627
chaviw1d044282017-09-27 12:19:28 -07004628 return layersProto;
4629}
4630
Alec Mouri6b9e9912020-01-21 10:50:24 -08004631void SurfaceFlinger::dumpHwc(std::string& result) const {
4632 getHwComposer().dump(result);
4633}
4634
Vishnu Nair0f085c62019-08-30 08:49:12 -07004635void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4636 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4637 // it.
4638 LayerProto* rootProto = layersProto.add_layers();
4639 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4640 rootProto->set_id(offscreenRootLayerId);
4641 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004642 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004643
4644 for (Layer* offscreenLayer : mOffscreenLayers) {
4645 // Add layer as child of the fake root
4646 rootProto->add_children(offscreenLayer->sequence);
4647
4648 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004649 LayerProto* layerProto =
4650 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004651 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004652 }
4653}
4654
Vishnu Nair8406fd72019-07-30 11:29:31 -07004655LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004656 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004657}
4658
Vishnu Nair0f085c62019-08-30 08:49:12 -07004659void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4660 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004661 result.append(schedule([this] {
4662 std::string result;
4663 for (Layer* offscreenLayer : mOffscreenLayers) {
4664 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4665 [&](Layer* layer) {
4666 layer->dumpCallingUidPid(result);
4667 });
4668 }
4669 return result;
4670 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004671}
4672
Dominik Laskowskic2867142019-01-21 11:33:38 -08004673void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4674 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004675 Colorizer colorizer(colorize);
4676
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004677 // figure out if we're stuck somewhere
4678 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004679 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004680 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4681
4682 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004683 * Dump library configuration.
4684 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004685
4686 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004687 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004688 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004689 appendSfConfigString(result);
4690 appendUiConfigString(result);
4691 appendGuiConfigString(result);
4692 result.append("\n");
4693
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004694 result.append("\nDisplay identification data:\n");
4695 dumpDisplayIdentificationData(result);
4696
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004697 result.append("\nWide-Color information:\n");
4698 dumpWideColorInfo(result);
4699
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004700 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004701 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004702 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004703 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004704 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004705
Andy McFadden41d67d72014-04-25 16:58:34 -07004706 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004707 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004708 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004709 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004710 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004711
Dan Stozab90cf072015-03-05 11:05:59 -08004712 dumpStaticScreenStats(result);
4713 result.append("\n");
4714
Alec Mouri40189b02019-03-05 15:07:54 -08004715 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4716 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4717 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004718
Dan Stozae77c7662016-05-13 11:37:28 -07004719 dumpBufferingStats(result);
4720
Andy McFadden4803b742012-09-24 19:07:20 -07004721 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004722 * Dump the visible layer list
4723 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004724 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004725 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004726 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4727 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004728 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004729
Chia-I Wu2f884132018-09-13 15:17:58 -07004730 {
Lloyd Pique207def92019-02-28 16:09:52 -08004731 StringAppendF(&result, "Composition layers\n");
4732 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004733 auto* compositionState = layer->getCompositionState();
4734 if (!compositionState) return;
4735
4736 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4737 layer->getDebugName() ? layer->getDebugName()
4738 : "<unknown>");
4739 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004740 });
4741 }
4742
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004743 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004744 * Dump Display state
4745 */
4746
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004747 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004748 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004749 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004750 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004751 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004752 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004753 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004754
4755 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004756 * Dump CompositionEngine state
4757 */
4758
4759 mCompositionEngine->dump(result);
4760
4761 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004762 * Dump SurfaceFlinger global state
4763 */
4764
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004765 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004766 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004767 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004768
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004769 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004770
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004771 DebugEGLImageTracker::getInstance()->dump(result);
4772
Dominik Laskowski075d3172018-05-24 15:50:06 -07004773 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004774 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4775 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004776 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4777 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004778 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004779 StringAppendF(&result,
4780 " transaction-flags : %08x\n"
4781 " gpu_to_cpu_unsupported : %d\n",
4782 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004783
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004784 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004785 displayId && getHwComposer().isConnected(*displayId)) {
4786 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004787 StringAppendF(&result,
4788 " refresh-rate : %f fps\n"
4789 " x-dpi : %f\n"
4790 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004791 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4792 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004793 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004794
Yiwei Zhang5434a782018-12-05 18:06:32 -08004795 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004796
Dan Stozae22aec72016-08-01 13:20:59 -07004797 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004798 * Tracing state
4799 */
4800 mTracing.dump(result);
4801 result.append("\n");
4802
4803 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004804 * HWC layer minidump
4805 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004806 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004807 const auto displayId = display->getId();
4808 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004809 continue;
4810 }
4811
Yiwei Zhang5434a782018-12-05 18:06:32 -08004812 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004813 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004814
4815 const DisplayDevice& ref = *display;
4816 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07004817 result.append("\n");
4818 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004819
4820 /*
4821 * Dump HWComposer state
4822 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004823 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004824 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004825 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004826 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004827 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004828 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004829
4830 /*
4831 * Dump gralloc state
4832 */
4833 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4834 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004835
4836 /*
4837 * Dump VrFlinger state if in use.
4838 */
4839 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4840 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004841 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004842 result.append("\n");
4843 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004844
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004845 result.append(mTimeStats->miniDump());
4846 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004847}
4848
Chia-I Wu28f320b2018-05-03 11:02:56 -07004849void SurfaceFlinger::updateColorMatrixLocked() {
4850 mat4 colorMatrix;
4851 if (mGlobalSaturationFactor != 1.0f) {
4852 // Rec.709 luma coefficients
4853 float3 luminance{0.213f, 0.715f, 0.072f};
4854 luminance *= 1.0f - mGlobalSaturationFactor;
4855 mat4 saturationMatrix = mat4(
4856 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4857 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4858 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4859 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4860 );
4861 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4862 } else {
4863 colorMatrix = mClientColorMatrix * mDaltonizer();
4864 }
4865
4866 if (mCurrentState.colorMatrix != colorMatrix) {
4867 mCurrentState.colorMatrix = colorMatrix;
4868 mCurrentState.colorMatrixChanged = true;
4869 setTransactionFlags(eTransactionNeeded);
4870 }
4871}
4872
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004873status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004874#pragma clang diagnostic push
4875#pragma clang diagnostic error "-Wswitch-enum"
4876 switch (static_cast<ISurfaceComposerTag>(code)) {
4877 // These methods should at minimum make sure that the client requested
4878 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004879 case BOOT_FINISHED:
4880 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004881 case CREATE_DISPLAY:
4882 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004883 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004884 case GET_ANIMATION_FRAME_STATS:
4885 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004886 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004887 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004888 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004889 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4890 case SET_AUTO_LOW_LATENCY_MODE:
4891 case GET_GAME_CONTENT_TYPE_SUPPORT:
4892 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004893 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004894 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004895 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004896 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004897 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004898 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004899 case SET_GLOBAL_SHADOW_SETTINGS:
4900 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4901 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4902 // necessary permission dynamically. Don't use the permission cache for this check.
4903 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4904 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004905 IPCThreadState* ipc = IPCThreadState::self();
4906 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4907 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004908 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004909 }
Robert Carr1db73f62016-12-21 12:58:51 -08004910 return OK;
4911 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004912 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004913 IPCThreadState* ipc = IPCThreadState::self();
4914 const int pid = ipc->getCallingPid();
4915 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004916 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4917 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004918 return PERMISSION_DENIED;
4919 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004920 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004921 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004922 // Used by apps to hook Choreographer to SurfaceFlinger.
4923 case CREATE_DISPLAY_EVENT_CONNECTION:
4924 // The following calls are currently used by clients that do not
4925 // request necessary permissions. However, they do not expose any secret
4926 // information, so it is OK to pass them.
4927 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004928 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004930 case GET_PHYSICAL_DISPLAY_IDS:
4931 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004932 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004933 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004934 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004935 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004936 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004937 case GET_DISPLAY_STATS:
4938 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4939 // Calling setTransactionState is safe, because you need to have been
4940 // granted a reference to Client* and Handle* to do anything with it.
4941 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004942 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004943 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004944 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004945 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004946 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004947 // setFrameRate() is deliberately available for apps to call without any
4948 // special permissions.
4949 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004950 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4951 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004952 return OK;
4953 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004954 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004955 case CAPTURE_SCREEN:
4956 case ADD_REGION_SAMPLING_LISTENER:
4957 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004958 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004959 IPCThreadState* ipc = IPCThreadState::self();
4960 const int pid = ipc->getCallingPid();
4961 const int uid = ipc->getCallingUid();
4962 if ((uid != AID_GRAPHICS) &&
4963 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4964 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4965 return PERMISSION_DENIED;
4966 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004967 return OK;
4968 }
chaviw93df2ea2019-04-30 16:45:12 -07004969 case CAPTURE_SCREEN_BY_ID: {
4970 IPCThreadState* ipc = IPCThreadState::self();
4971 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004972 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004973 return OK;
4974 }
4975 return PERMISSION_DENIED;
4976 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004977 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004978
4979 // These codes are used for the IBinder protocol to either interrogate the recipient
4980 // side of the transaction for its canonical interface descriptor or to dump its state.
4981 // We let them pass by default.
4982 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4983 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4984 code == IBinder::SYSPROPS_TRANSACTION) {
4985 return OK;
4986 }
Ady Abraham07e54702020-04-16 15:05:37 -07004987 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004988 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004989 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004990 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4991 return OK;
4992 }
4993 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4994 return PERMISSION_DENIED;
4995#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004996}
4997
Ana Krulec13be8ad2018-08-21 02:43:56 +00004998status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4999 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005000 status_t credentialCheck = CheckTransactCodeCredentials(code);
5001 if (credentialCheck != OK) {
5002 return credentialCheck;
5003 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005004
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005005 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5006 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005007 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005008 IPCThreadState* ipc = IPCThreadState::self();
5009 const int uid = ipc->getCallingUid();
5010 if (CC_UNLIKELY(uid != AID_SYSTEM
5011 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005012 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005013 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005014 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005015 return PERMISSION_DENIED;
5016 }
5017 int n;
5018 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005019 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005020 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005021 return NO_ERROR;
5022 case 1002: // SHOW_UPDATES
5023 n = data.readInt32();
5024 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005025 invalidateHwcGeometry();
5026 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005027 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005028 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005029 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005030 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005031 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005032 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005033 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005034 setTransactionFlags(
5035 eTransactionNeeded|
5036 eDisplayTransactionNeeded|
5037 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005038 return NO_ERROR;
5039 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005040 case 1006:{ // send empty update
5041 signalRefresh();
5042 return NO_ERROR;
5043 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005044 case 1008: // toggle use of hw composer
5045 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005046 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005047 invalidateHwcGeometry();
5048 repaintEverything();
5049 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005050 case 1009: // toggle use of transform hint
5051 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005052 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005053 invalidateHwcGeometry();
5054 repaintEverything();
5055 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005056 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005057 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005058 reply->writeInt32(0);
5059 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005060 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005061 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005062 return NO_ERROR;
5063 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005064 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005065 if (!display) {
5066 return NAME_NOT_FOUND;
5067 }
5068
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005069 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005070 return NO_ERROR;
5071 }
5072 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005073 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005074 // daltonize
5075 n = data.readInt32();
5076 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005077 case 1:
5078 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5079 break;
5080 case 2:
5081 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5082 break;
5083 case 3:
5084 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5085 break;
5086 default:
5087 mDaltonizer.setType(ColorBlindnessType::None);
5088 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005089 }
5090 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005091 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005092 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005093 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005094 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005095
5096 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005097 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005098 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005099 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005100 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005101 // apply a color matrix
5102 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005103 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005104 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005105 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005106 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005107 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005108 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005109 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005110 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005111 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005112 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005113
5114 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5115 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005116 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005117 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5118 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5119 }
5120
Chia-I Wu28f320b2018-05-03 11:02:56 -07005121 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005122 return NO_ERROR;
5123 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005124 case 1016: { // Unused.
5125 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005126 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005127 case 1017: {
5128 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005129 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005130 return NO_ERROR;
5131 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005132 case 1018: { // Modify Choreographer's phase offset
5133 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005134 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005135 return NO_ERROR;
5136 }
5137 case 1019: { // Modify SurfaceFlinger's phase offset
5138 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005139 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005140 return NO_ERROR;
5141 }
Irvel468051e2016-06-13 16:44:44 -07005142 case 1020: { // Layer updates interceptor
5143 n = data.readInt32();
5144 if (n) {
5145 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005146 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005147 }
5148 else{
5149 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005150 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005151 }
5152 return NO_ERROR;
5153 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005154 case 1021: { // Disable HWC virtual displays
5155 n = data.readInt32();
5156 mUseHwcVirtualDisplays = !n;
5157 return NO_ERROR;
5158 }
Romain Guy0147a172017-06-01 13:53:56 -07005159 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005160 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005161 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005162
Chia-I Wu28f320b2018-05-03 11:02:56 -07005163 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005164 return NO_ERROR;
5165 }
Romain Guy54f154a2017-10-24 21:40:32 +01005166 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005167 int32_t colorMode;
5168
Chia-I Wu0d711262018-05-21 15:19:35 -07005169 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005170 if (data.readInt32(&colorMode) == NO_ERROR) {
5171 mForceColorMode = static_cast<ColorMode>(colorMode);
5172 }
Romain Guy54f154a2017-10-24 21:40:32 +01005173 invalidateHwcGeometry();
5174 repaintEverything();
5175 return NO_ERROR;
5176 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005177 // Deprecate, use 1030 to check whether the device is color managed.
5178 case 1024: {
5179 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005180 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005181 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005182 n = data.readInt32();
5183 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005184 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005185 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005186 reply->writeInt32(NO_ERROR);
5187 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005188 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005189 mTracingEnabledChanged = mTracing.disable();
5190 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005191 reply->writeInt32(mTracing.writeToFile());
5192 } else {
5193 reply->writeInt32(NO_ERROR);
5194 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005195 }
5196 return NO_ERROR;
5197 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005198 case 1026: { // Get layer tracing status
5199 reply->writeBool(mTracing.isEnabled());
5200 return NO_ERROR;
5201 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005202 // Is a DisplayColorSetting supported?
5203 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005204 const auto display = getDefaultDisplayDevice();
5205 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005206 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005207 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005208
5209 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5210 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005211 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005212 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005213 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005214 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005215 reply->writeBool(true);
5216 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005217 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005218 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005219 break;
5220 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005221 reply->writeBool(
5222 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005223 break;
5224 }
5225 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005226 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005227 // Is VrFlinger active?
5228 case 1028: {
5229 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005230 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005231 return NO_ERROR;
5232 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005233 // Set buffer size for SF tracing (value in KB)
5234 case 1029: {
5235 n = data.readInt32();
5236 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5237 ALOGW("Invalid buffer size: %d KB", n);
5238 reply->writeInt32(BAD_VALUE);
5239 return BAD_VALUE;
5240 }
5241
5242 ALOGD("Updating trace buffer to %d KB", n);
5243 mTracing.setBufferSize(n * 1024);
5244 reply->writeInt32(NO_ERROR);
5245 return NO_ERROR;
5246 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005247 // Is device color managed?
5248 case 1030: {
5249 reply->writeBool(useColorManagement);
5250 return NO_ERROR;
5251 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005252 // Override default composition data space
5253 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5254 // && adb shell stop zygote && adb shell start zygote
5255 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5256 // adb shell stop zygote && adb shell start zygote
5257 case 1031: {
5258 Mutex::Autolock _l(mStateLock);
5259 n = data.readInt32();
5260 if (n) {
5261 n = data.readInt32();
5262 if (n) {
5263 Dataspace dataspace = static_cast<Dataspace>(n);
5264 if (!validateCompositionDataspace(dataspace)) {
5265 return BAD_VALUE;
5266 }
5267 mDefaultCompositionDataspace = dataspace;
5268 }
5269 n = data.readInt32();
5270 if (n) {
5271 Dataspace dataspace = static_cast<Dataspace>(n);
5272 if (!validateCompositionDataspace(dataspace)) {
5273 return BAD_VALUE;
5274 }
5275 mWideColorGamutCompositionDataspace = dataspace;
5276 }
5277 } else {
5278 // restore composition data space.
5279 mDefaultCompositionDataspace = defaultCompositionDataspace;
5280 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5281 }
5282 return NO_ERROR;
5283 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005284 // Set trace flags
5285 case 1033: {
5286 n = data.readUint32();
5287 ALOGD("Updating trace flags to 0x%x", n);
5288 mTracing.setTraceFlags(n);
5289 reply->writeInt32(NO_ERROR);
5290 return NO_ERROR;
5291 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005292 case 1034: {
Dominik Laskowski20134642020-04-20 22:36:44 -07005293 switch (n = data.readInt32()) {
5294 case 0:
5295 case 1:
5296 enableRefreshRateOverlay(static_cast<bool>(n));
5297 break;
5298 default: {
5299 Mutex::Autolock lock(mStateLock);
5300 reply->writeBool(mRefreshRateOverlay != nullptr);
5301 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005302 }
5303 return NO_ERROR;
5304 }
Ady Abraham34392f72019-04-10 11:29:27 -07005305 case 1035: {
5306 n = data.readInt32();
5307 mDebugDisplayConfigSetByBackdoor = false;
5308 if (n >= 0) {
5309 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005310 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005311 if (result != NO_ERROR) {
5312 return result;
5313 }
5314 mDebugDisplayConfigSetByBackdoor = true;
5315 }
5316 return NO_ERROR;
5317 }
Ady Abraham07e54702020-04-16 15:05:37 -07005318 case 1036: {
5319 if (data.readInt32() > 0) {
5320 status_t result =
5321 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5322 if (result != NO_ERROR) {
5323 return result;
5324 }
5325 } else {
5326 mDebugFrameRateFlexibilityToken = nullptr;
5327 }
5328 return NO_ERROR;
5329 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005330 }
5331 }
5332 return err;
5333}
5334
Steven Thomas6d8110b2017-08-31 18:24:21 -07005335void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005336 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005337 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005338}
5339
Ana Krulec7d1d6832018-12-27 11:10:09 -08005340void SurfaceFlinger::repaintEverythingForHWC() {
5341 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005342 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005343 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005344}
5345
Ady Abrahama09852a2020-02-20 14:23:42 -08005346void SurfaceFlinger::kernelTimerChanged(bool expired) {
5347 static bool updateOverlay =
5348 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005349 if (!updateOverlay) return;
5350 if (Mutex::Autolock lock(mStateLock); !mRefreshRateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005351
5352 // Update the overlay on the main thread to avoid race conditions with
5353 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowski20134642020-04-20 22:36:44 -07005354 static_cast<void>(schedule([=] {
5355 const auto desiredActiveConfig = getDesiredActiveConfig();
5356 const auto& current = desiredActiveConfig
5357 ? mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId)
5358 : mRefreshRateConfigs->getCurrentRefreshRate();
5359 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5360
5361 if (current != min) {
Ana Krulecb9afd792020-06-11 13:16:15 -07005362 const bool timerExpired = mKernelIdleTimerEnabled && expired;
Ady Abrahama09852a2020-02-20 14:23:42 -08005363
Dominik Laskowski20134642020-04-20 22:36:44 -07005364 if (Mutex::Autolock lock(mStateLock); mRefreshRateOverlay) {
Ady Abrahama09852a2020-02-20 14:23:42 -08005365 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
Ady Abrahama09852a2020-02-20 14:23:42 -08005366 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005367 mEventQueue->invalidate();
Ady Abrahama09852a2020-02-20 14:23:42 -08005368 }
5369 }));
5370}
5371
Ana Krulecb9afd792020-06-11 13:16:15 -07005372void SurfaceFlinger::toggleKernelIdleTimer() {
5373 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
5374
5375 // If the support for kernel idle timer is disabled in SF code, don't do anything.
5376 if (!mSupportKernelIdleTimer) {
5377 return;
5378 }
5379 const KernelIdleTimerAction action = mRefreshRateConfigs->getIdleTimerAction();
5380
5381 switch (action) {
5382 case KernelIdleTimerAction::TurnOff:
5383 if (mKernelIdleTimerEnabled) {
5384 ATRACE_INT("KernelIdleTimer", 0);
5385 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "false");
5386 mKernelIdleTimerEnabled = false;
5387 }
5388 break;
5389 case KernelIdleTimerAction::TurnOn:
5390 if (!mKernelIdleTimerEnabled) {
5391 ATRACE_INT("KernelIdleTimer", 1);
5392 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "true");
5393 mKernelIdleTimerEnabled = true;
5394 }
5395 break;
5396 case KernelIdleTimerAction::NoChange:
5397 break;
5398 }
5399}
5400
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005401// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5402class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005403public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005404 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5405 ~WindowDisconnector() {
5406 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005407 }
5408
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005409private:
5410 ANativeWindow* mWindow;
5411 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005412};
5413
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005414status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005415 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005416 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5417 const Rect& sourceCrop, uint32_t reqWidth,
5418 uint32_t reqHeight, bool useIdentityTransform,
5419 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005420 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005421
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005422 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005423
Dominik Laskowski718f9602019-11-09 20:01:35 -08005424 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5425 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5426 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5427 renderAreaRotation = ui::Transform::ROT_0;
5428 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005429
Chia-I Wu20261cb2018-08-23 12:55:44 -07005430 sp<DisplayDevice> display;
5431 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005432 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005433
Chia-I Wu20261cb2018-08-23 12:55:44 -07005434 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005435 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005436
Chia-I Wucb023152018-08-28 12:57:23 -07005437 // set the requested width/height to the logical display viewport size
5438 // by default
5439 if (reqWidth == 0 || reqHeight == 0) {
5440 reqWidth = uint32_t(display->getViewport().width());
5441 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005442 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005443 }
5444
Peiyong Lin0e003c92018-09-17 11:09:51 -07005445 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005446 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005447 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5448 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005449 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005450 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005451}
5452
chaviw93df2ea2019-04-30 16:45:12 -07005453static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5454 switch (colorMode) {
5455 case ColorMode::DISPLAY_P3:
5456 case ColorMode::BT2100_PQ:
5457 case ColorMode::BT2100_HLG:
5458 case ColorMode::DISPLAY_BT2020:
5459 return Dataspace::DISPLAY_P3;
5460 default:
5461 return Dataspace::V0_SRGB;
5462 }
5463}
5464
Martin Liu4a322352020-03-24 21:30:38 +08005465status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5466 static constexpr int kFifoPriority = 2;
5467 static constexpr int kOtherPriority = 0;
5468
5469 struct sched_param param = {0};
5470 int sched_policy;
5471 if (enabled) {
5472 sched_policy = SCHED_FIFO;
5473 param.sched_priority = kFifoPriority;
5474 } else {
5475 sched_policy = SCHED_OTHER;
5476 param.sched_priority = kOtherPriority;
5477 }
5478
5479 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5480 return -errno;
5481 }
5482 return NO_ERROR;
5483}
5484
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005485sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005486 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5487 if (displayToken) {
5488 return getDisplayDeviceLocked(displayToken);
5489 }
5490 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5491 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005492 return getDisplayByLayerStack(displayOrLayerStack);
5493}
5494
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005495sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005496 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005497 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005498 return display;
5499 }
5500 }
5501 return nullptr;
5502}
5503
5504status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5505 sp<GraphicBuffer>* outBuffer) {
5506 sp<DisplayDevice> display;
5507 uint32_t width;
5508 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005509 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005510 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005511 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005512 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5513 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005514 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005515 }
5516
5517 width = uint32_t(display->getViewport().width());
5518 height = uint32_t(display->getViewport().height());
5519
Dominik Laskowski718f9602019-11-09 20:01:35 -08005520 const auto orientation = display->getOrientation();
5521 captureOrientation = ui::Transform::toRotationFlags(orientation);
5522
5523 switch (captureOrientation) {
5524 case ui::Transform::ROT_90:
5525 captureOrientation = ui::Transform::ROT_270;
5526 break;
5527
5528 case ui::Transform::ROT_270:
5529 captureOrientation = ui::Transform::ROT_90;
5530 break;
5531
5532 case ui::Transform::ROT_INVALID:
5533 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5534 captureOrientation = ui::Transform::ROT_0;
5535 break;
5536
5537 default:
5538 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005539 }
chaviw93df2ea2019-04-30 16:45:12 -07005540 *outDataspace =
5541 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5542 }
5543
5544 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5545 false /* captureSecureLayers */);
5546
5547 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5548 std::placeholders::_1);
5549 bool ignored = false;
5550 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5551 false /* useIdentityTransform */,
5552 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,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005565 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005566 bool childrenOnly, const Rect& displayViewport)
5567 : RenderArea(reqWidth, reqHeight, 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
Robert Carrc0df3122019-04-11 13:18:21 -07005642 int reqWidth = 0;
5643 int reqHeight = 0;
5644 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005645 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005646 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005647 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005648 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005649 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005650
Alec Mouri9a02eda2020-04-21 17:39:34 -07005651 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005652 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5653 ALOGE("captureLayers called with an invalid or removed parent");
5654 return NAME_NOT_FOUND;
5655 }
5656
5657 const int uid = IPCThreadState::self()->getCallingUid();
5658 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5659 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5660 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5661 return PERMISSION_DENIED;
5662 }
5663
Vishnu Nairefc42e22019-12-03 17:36:12 -08005664 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005665 if (sourceCrop.width() <= 0) {
5666 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005667 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005668 }
5669
5670 if (sourceCrop.height() <= 0) {
5671 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005672 crop.bottom = parentSourceBounds.getHeight();
5673 }
5674
5675 if (crop.isEmpty() || frameScale <= 0.0f) {
5676 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5677 // crop was not specified, or an invalid frame scale was provided.
5678 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005679 }
5680 reqWidth = crop.width() * frameScale;
5681 reqHeight = crop.height() * frameScale;
5682
5683 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005684 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005685 if (excludeLayer != nullptr) {
5686 excludeLayers.emplace(excludeLayer);
5687 } else {
5688 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5689 return NAME_NOT_FOUND;
5690 }
5691 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005692
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005693 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005694 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005695 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005696 }
5697
5698 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005699 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005700
Chia-I Wu20261cb2018-08-23 12:55:44 -07005701 // really small crop or frameScale
5702 if (reqWidth <= 0) {
5703 reqWidth = 1;
5704 }
5705 if (reqHeight <= 0) {
5706 reqHeight = 1;
5707 }
5708
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005709 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5710 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005711 auto traverseLayers = [parent, childrenOnly,
5712 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005713 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5714 if (!layer->isVisible()) {
5715 return;
Robert Carr578038f2018-03-09 12:25:24 -08005716 } else if (childrenOnly && layer == parent.get()) {
5717 return;
chaviwa76b2712017-09-20 12:02:26 -07005718 }
Robert Carr866455f2019-04-02 16:28:26 -07005719
5720 sp<Layer> p = layer;
5721 while (p != nullptr) {
5722 if (excludeLayers.count(p) != 0) {
5723 return;
5724 }
5725 p = p->getParent();
5726 }
5727
chaviwa76b2712017-09-20 12:02:26 -07005728 visitor(layer);
5729 });
5730 };
Robert Carr108b2c72019-04-02 16:32:58 -07005731
5732 bool outCapturedSecureLayers = false;
5733 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5734 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005735}
5736
5737status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5738 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005739 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005740 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005741 bool useIdentityTransform,
5742 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005743 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005744
Peiyong Lin0e003c92018-09-17 11:09:51 -07005745 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005746 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5747 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005748 *outBuffer =
5749 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5750 static_cast<android_pixel_format>(reqPixelFormat), 1,
5751 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005752
Robert Carr108b2c72019-04-02 16:32:58 -07005753 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005754 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005755}
5756
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005757status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5758 TraverseLayersFunction traverseLayers,
5759 const sp<GraphicBuffer>& buffer,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005760 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005761 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005762 const int uid = IPCThreadState::self()->getCallingUid();
5763 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5764
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005765 status_t result;
5766 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005767
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005768 do {
5769 std::tie(result, syncFd) =
5770 schedule([&] {
5771 if (mRefreshPending) {
5772 ATRACE_NAME("Skipping screenshot for now");
5773 return std::make_pair(EAGAIN, -1);
5774 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005775
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005776 status_t result = NO_ERROR;
5777 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005778
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005779 Mutex::Autolock lock(mStateLock);
5780 renderArea.render([&] {
5781 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5782 useIdentityTransform, forSystem, &fd,
5783 regionSampling, outCapturedSecureLayers);
5784 });
5785
5786 return std::make_pair(result, fd);
5787 }).get();
5788 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005789
5790 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005791 sync_wait(syncFd, -1);
5792 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005793 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005794
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005795 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005796}
5797
chaviwa76b2712017-09-20 12:02:26 -07005798void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005799 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005800 ANativeWindowBuffer* buffer, bool useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005801 bool regionSampling, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005802 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005803
chaviwa76b2712017-09-20 12:02:26 -07005804 const auto reqWidth = renderArea.getReqWidth();
5805 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005806 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005807 const auto transform = renderArea.getTransform();
5808 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005809 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005810
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005811 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005812 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005813
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005814 // assume that bounds are never offset, and that they are the same as the
5815 // buffer bounds.
5816 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005817 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005818 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005819
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005820 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5821 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005822
chaviw50da5042018-04-09 13:49:37 -07005823 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005824
Vishnu Nair9b079a22020-01-21 14:36:08 -08005825 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005826 fillLayer.source.buffer.buffer = nullptr;
5827 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005828 fillLayer.geometry.boundaries =
5829 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005830 fillLayer.alpha = half(alpha);
5831 clientCompositionLayers.push_back(fillLayer);
5832
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005833 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08005834 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005835 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005836 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005837 const bool supportProtectedContent = false;
5838 Region clip(renderArea.getBounds());
5839 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5840 clip,
5841 useIdentityTransform,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005842 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07005843 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005844 renderArea.isSecure(),
5845 supportProtectedContent,
5846 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005847 displayViewport,
5848 clientCompositionDisplay.outputDataspace,
5849 true, /* realContentIsVisible */
5850 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005851 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005852 std::vector<compositionengine::LayerFE::LayerSettings> results =
5853 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005854 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005855 for (auto& settings : results) {
5856 settings.geometry.positionTransform =
5857 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupinf11eba52020-04-20 18:42:31 -07005858 // There's no need to process blurs when we're executing region sampling,
5859 // we're just trying to understand what we're drawing, and doing so without
5860 // blurs is already a pretty good approximation.
5861 if (regionSampling) {
5862 settings.backgroundBlurRadius = 0;
5863 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005864 }
Yichi Chen40773d92020-04-01 10:10:18 +08005865 clientCompositionLayers.insert(clientCompositionLayers.end(),
5866 std::make_move_iterator(results.begin()),
5867 std::make_move_iterator(results.end()));
5868 renderedLayers.push_back(layer);
5869 }
chaviwa76b2712017-09-20 12:02:26 -07005870 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005871
Yichi Chen40773d92020-04-01 10:10:18 +08005872 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5873 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005874 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005875 clientCompositionLayerPointers.begin(),
5876 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005877
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005878 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005879 // Use an empty fence for the buffer fence, since we just created the buffer so
5880 // there is no need for synchronization with the GPU.
5881 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005882 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005883 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005884 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005885 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005886
5887 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005888
5889 if (*outSyncFd >= 0) {
5890 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5891 for (auto* layer : renderedLayers) {
5892 layer->onLayerDisplayed(releaseFence);
5893 }
5894 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005895}
5896
chaviwa76b2712017-09-20 12:02:26 -07005897status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5898 TraverseLayersFunction traverseLayers,
5899 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005900 bool useIdentityTransform, bool forSystem,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005901 int* outSyncFd, bool regionSampling,
5902 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005903 ATRACE_CALL();
5904
chaviwa76b2712017-09-20 12:02:26 -07005905 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005906 outCapturedSecureLayers =
5907 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005908 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005909
Robert Carr03480e22018-01-04 16:02:06 -08005910 // We allow the system server to take screenshots of secure layers for
5911 // use in situations like the Screen-rotation animation and place
5912 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005913 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005914 ALOGW("FB is protected: PERMISSION_DENIED");
5915 return PERMISSION_DENIED;
5916 }
Lucas Dupinf11eba52020-04-20 18:42:31 -07005917 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5918 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005919 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005920}
5921
chaviw95ef3c42019-02-14 10:55:09 -08005922void SurfaceFlinger::setInputWindowsFinished() {
5923 Mutex::Autolock _l(mStateLock);
5924
5925 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005926
chaviw95ef3c42019-02-14 10:55:09 -08005927 mTransactionCV.broadcast();
5928}
chaviw5f21a5e2019-02-14 10:00:34 -08005929
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005930// ---------------------------------------------------------------------------
5931
Edgar Arriaga844fa672020-01-16 14:21:42 -08005932void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5933 layersSortedByZ.traverse(visitor);
5934}
5935
Dan Stoza412903f2017-04-27 13:42:17 -07005936void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5937 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005938}
5939
Dan Stoza412903f2017-04-27 13:42:17 -07005940void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5941 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005942}
5943
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005944void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005945 const LayerVector::Visitor& visitor) {
5946 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005947 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005948 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005949 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005950 continue;
5951 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005952 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005953 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005954 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005955 return;
5956 }
chaviwa76b2712017-09-20 12:02:26 -07005957 if (!layer->isVisible()) {
5958 return;
5959 }
5960 visitor(layer);
5961 });
5962 }
5963}
5964
Steven Thomasd4071902020-03-24 16:02:53 -07005965status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5966 const sp<DisplayDevice>& display,
5967 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005968 Mutex::Autolock lock(mStateLock);
5969
Steven Thomasd4071902020-03-24 16:02:53 -07005970 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5971 "Can only set override policy on the primary display");
5972 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5973
Dominik Laskowski22488f62019-03-28 09:53:04 -07005974 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005975 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5976 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5977 // it should go thru setDesiredActiveConfig, similar to primary display.
5978 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5979 const auto displayId = display->getId();
5980 LOG_ALWAYS_FATAL_IF(!displayId);
5981
Peiyong Line9d809e2020-04-14 13:10:48 -07005982 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005983 constraints.desiredTimeNanos = systemTime();
5984 constraints.seamlessRequired = false;
5985
Peiyong Line9d809e2020-04-14 13:10:48 -07005986 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005987 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5988 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005989 constraints, &timeline) < 0) {
5990 return BAD_VALUE;
5991 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005992 if (timeline.refreshRequired) {
5993 repaintEverythingForHWC();
5994 }
5995
Steven Thomasd4071902020-03-24 16:02:53 -07005996 display->setActiveConfig(policy->defaultConfig);
5997 const nsecs_t vsyncPeriod = getHwComposer()
5998 .getConfigs(*displayId)[policy->defaultConfig.value()]
5999 ->getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006000 mScheduler->onNonPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6001 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006002 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08006003 }
6004
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006005 if (mDebugDisplayConfigSetByBackdoor) {
6006 // ignore this request as config is overridden by backdoor
6007 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006008 }
6009
Steven Thomasd4071902020-03-24 16:02:53 -07006010 status_t setPolicyResult = overridePolicy
6011 ? mRefreshRateConfigs->setOverridePolicy(policy)
6012 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
6013 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006014 return BAD_VALUE;
6015 }
Steven Thomasd4071902020-03-24 16:02:53 -07006016 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006017 return NO_ERROR;
6018 }
Steven Thomasd4071902020-03-24 16:02:53 -07006019 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006020
Steven Thomasf734df42020-04-13 21:09:28 -07006021 ALOGV("Setting desired display config specs: defaultConfig: %d primaryRange: [%.0f %.0f]"
6022 " expandedRange: [%.0f %.0f]",
6023 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
6024 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
6025 currentPolicy.appRequestRange.max);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006026
Ana Krulecb9afd792020-06-11 13:16:15 -07006027 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6028 // be depending in this callback.
Alec Mouri60aee1c2019-10-28 16:18:59 -07006029 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07006030 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
6031 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006032 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6033 display->getActiveConfig(), vsyncPeriod);
Ana Krulecb9afd792020-06-11 13:16:15 -07006034 toggleKernelIdleTimer();
Ady Abraham838de062019-02-04 10:24:03 -08006035
Ana Krulec3f6a2062020-01-23 15:48:01 -08006036 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08006037 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08006038 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
6039 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07006040 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08006041 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07006042 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006043
Ady Abrahamabc27602020-04-08 17:20:29 -07006044 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
6045 ALOGV("switching to Scheduler preferred config %d",
6046 preferredRefreshRate.getConfigId().value());
6047 setDesiredActiveConfig(
6048 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006049 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07006050 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
6051 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006052 }
6053
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006054 return NO_ERROR;
6055}
6056
Ana Krulec0782b882019-10-15 17:34:54 -07006057status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Steven Thomasf734df42020-04-13 21:09:28 -07006058 int32_t defaultConfig,
6059 float primaryRefreshRateMin,
6060 float primaryRefreshRateMax,
6061 float appRequestRefreshRateMin,
6062 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006063 ATRACE_CALL();
6064
6065 if (!displayToken) {
6066 return BAD_VALUE;
6067 }
6068
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006069 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006070 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006071 if (!display) {
6072 ALOGE("Attempt to set desired display configs for invalid display token %p",
6073 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006074 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006075 } else if (display->isVirtual()) {
6076 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006077 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006078 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006079 using Policy = scheduler::RefreshRateConfigs::Policy;
Steven Thomasf734df42020-04-13 21:09:28 -07006080 const Policy policy{HwcConfigIndexType(defaultConfig),
6081 {primaryRefreshRateMin, primaryRefreshRateMax},
6082 {appRequestRefreshRateMin, appRequestRefreshRateMax}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006083 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006084
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006085 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
6086 }
6087 });
6088
6089 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006090}
6091
6092status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006093 int32_t* outDefaultConfig,
Steven Thomasf734df42020-04-13 21:09:28 -07006094 float* outPrimaryRefreshRateMin,
6095 float* outPrimaryRefreshRateMax,
6096 float* outAppRequestRefreshRateMin,
6097 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006098 ATRACE_CALL();
6099
Steven Thomasf734df42020-04-13 21:09:28 -07006100 if (!displayToken || !outDefaultConfig || !outPrimaryRefreshRateMin ||
6101 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006102 return BAD_VALUE;
6103 }
6104
6105 Mutex::Autolock lock(mStateLock);
6106 const auto display = getDisplayDeviceLocked(displayToken);
6107 if (!display) {
6108 return NAME_NOT_FOUND;
6109 }
6110
6111 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006112 scheduler::RefreshRateConfigs::Policy policy =
6113 mRefreshRateConfigs->getDisplayManagerPolicy();
6114 *outDefaultConfig = policy.defaultConfig.value();
Steven Thomasf734df42020-04-13 21:09:28 -07006115 *outPrimaryRefreshRateMin = policy.primaryRange.min;
6116 *outPrimaryRefreshRateMax = policy.primaryRange.max;
6117 *outAppRequestRefreshRateMin = policy.appRequestRange.min;
6118 *outAppRequestRefreshRateMax = policy.appRequestRange.max;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006119 return NO_ERROR;
6120 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006121 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006122 } else {
6123 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006124 LOG_FATAL_IF(!displayId);
6125
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006126 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6127 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
Steven Thomasf734df42020-04-13 21:09:28 -07006128 *outPrimaryRefreshRateMin = 1e9f / vsyncPeriod;
6129 *outPrimaryRefreshRateMax = 1e9f / vsyncPeriod;
6130 *outAppRequestRefreshRateMin = 1e9f / vsyncPeriod;
6131 *outAppRequestRefreshRateMax = 1e9f / vsyncPeriod;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006132 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006133 }
Ana Krulec0782b882019-10-15 17:34:54 -07006134}
6135
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006136void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006137 mFlinger->setInputWindowsFinished();
6138}
6139
Alec Mouri9a02eda2020-04-21 17:39:34 -07006140wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6141 Mutex::Autolock _l(mStateLock);
6142 return fromHandleLocked(handle);
6143}
6144
6145wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006146 BBinder* b = nullptr;
6147 if (handle) {
6148 b = handle->localBinder();
6149 }
Robert Carrc0df3122019-04-11 13:18:21 -07006150 if (b == nullptr) {
6151 return nullptr;
6152 }
6153 auto it = mLayersByLocalBinderToken.find(b);
6154 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006155 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006156 }
6157 return nullptr;
6158}
6159
Dominik Laskowski75848362019-11-11 17:57:20 -08006160void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006161 mNumLayers++;
6162 mScheduler->registerLayer(layer);
6163}
6164
6165void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6166 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006167 removeFromOffscreenLayers(layer);
6168}
6169
6170// WARNING: ONLY CALL THIS FROM LAYER DTOR
6171// Here we add children in the current state to offscreen layers and remove the
6172// layer itself from the offscreen layer list. Since
6173// this is the dtor, it is safe to access the current state. This keeps us
6174// from dangling children layers such that they are not reachable from the
6175// Drawing state nor the offscreen layer list
6176// See b/141111965
6177void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6178 for (auto& child : layer->getCurrentChildren()) {
6179 mOffscreenLayers.emplace(child.get());
6180 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006181 mOffscreenLayers.erase(layer);
6182}
6183
Alec Mouri4545a8a2019-08-08 20:05:32 -07006184void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6185 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6186}
6187
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006188status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6189 float lightPosY, float lightPosZ,
6190 float lightRadius) {
6191 Mutex::Autolock _l(mStateLock);
6192 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6193 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6194 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6195 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6196 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6197
6198 // these values are overridden when calculating the shadow settings for a layer.
6199 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6200 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006201 return NO_ERROR;
6202}
6203
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006204const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6205 const {
6206 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6207 // on the work to remove the table in that bug rather than adding more to
6208 // it.
6209 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6210 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6211 // supported, and exposed via the
6212 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6213 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6214 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6215 };
6216 return genericLayerMetadataKeyMap;
6217}
6218
Steven Thomas62a4cf82020-01-31 12:04:03 -08006219status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6220 int8_t compatibility) {
6221 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6222 return BAD_VALUE;
6223 }
6224
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006225 static_cast<void>(schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006226 Mutex::Autolock lock(mStateLock);
6227 if (authenticateSurfaceTextureLocked(surface)) {
6228 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6229 if (layer->setFrameRate(
6230 Layer::FrameRate(frameRate,
6231 Layer::FrameRate::convertCompatibility(compatibility)))) {
6232 setTransactionFlags(eTraversalNeeded);
6233 }
6234 } else {
6235 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6236 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006237 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006238 return NO_ERROR;
6239 }));
6240
Steven Thomas62a4cf82020-01-31 12:04:03 -08006241 return NO_ERROR;
6242}
6243
Steven Thomasd4071902020-03-24 16:02:53 -07006244status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6245 if (!outToken) {
6246 return BAD_VALUE;
6247 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006248
6249 auto future = schedule([this] {
6250 status_t result = NO_ERROR;
6251 sp<IBinder> token;
6252
Steven Thomasd4071902020-03-24 16:02:53 -07006253 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006254 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Steven Thomasd4071902020-03-24 16:02:53 -07006255
6256 // This is a little racy, but not in a way that hurts anything. As we grab the
6257 // defaultConfig from the display manager policy, we could be setting a new display
6258 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6259 // matter for the override policy though, since we set allowGroupSwitching to true, so
6260 // it's not a problem.
6261 scheduler::RefreshRateConfigs::Policy overridePolicy;
6262 overridePolicy.defaultConfig =
6263 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6264 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006265 constexpr bool kOverridePolicy = true;
6266 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006267 }
6268
6269 if (result == NO_ERROR) {
6270 mFrameRateFlexibilityTokenCount++;
6271 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6272 // below, is something to consider carefully. The lifetime of the
6273 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6274 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6275 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6276 // in this case, for two reasons:
6277 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6278 // the program exits is via a crash. So we won't have a situation where the
6279 // SurfaceFlinger object is dead but the process is still up.
6280 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6281 // if condition 1 were changed, the problem would only show up when running CTS tests,
6282 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006283 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006284 [this]() { onFrameRateFlexibilityTokenReleased(); });
6285 ALOGD("Frame rate flexibility token acquired. count=%d",
6286 mFrameRateFlexibilityTokenCount);
6287 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006288
6289 return std::make_pair(result, token);
6290 });
6291
6292 status_t result;
6293 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006294 return result;
6295}
6296
6297void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006298 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006299 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6300 "Failed tracking frame rate flexibility tokens");
6301 mFrameRateFlexibilityTokenCount--;
6302 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6303 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006304 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006305 constexpr bool kOverridePolicy = true;
6306 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006307 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6308 }
6309 }));
6310}
6311
Dominik Laskowski20134642020-04-20 22:36:44 -07006312void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
6313 static_cast<void>(schedule([=] {
6314 std::unique_ptr<RefreshRateOverlay> overlay;
6315 if (enable) {
6316 overlay = std::make_unique<RefreshRateOverlay>(*this);
6317 }
6318
6319 {
6320 Mutex::Autolock lock(mStateLock);
6321
6322 // Destroy the layer of the current overlay, if any, outside the lock.
6323 mRefreshRateOverlay.swap(overlay);
6324 if (!mRefreshRateOverlay) return;
6325
6326 if (const auto display = getDefaultDisplayDeviceLocked()) {
6327 mRefreshRateOverlay->setViewport(display->getSize());
6328 }
6329
6330 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
6331 }
6332 }));
6333}
6334
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006335} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006336
Mathias Agopian3f844832013-08-07 21:24:32 -07006337#if defined(__gl_h_)
6338#error "don't include gl/gl.h in this file"
6339#endif
6340
6341#if defined(__gl2_h_)
6342#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006343#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006344
6345// TODO(b/129481165): remove the #pragma below and fix conversion issues
6346#pragma clang diagnostic pop // ignored "-Wconversion"