blob: 0ac3d329e993f23b97629e1916a71e5c2391b3d4 [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)) ||
Robert Carr6417d2e2020-06-24 15:26:32 -07002026 flushedATransaction ||
2027 mForceTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002028
2029 if (runHandleTransaction) {
2030 handleTransaction(eTransactionMask);
2031 } else {
2032 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002033 }
2034
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002035 if (transactionFlushNeeded()) {
2036 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002037 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002038
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002039 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002040}
2041
Dan Stoza28d46a52020-04-28 09:54:54 -07002042void SurfaceFlinger::onMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002043 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002044
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002045 mRefreshPending = false;
2046
Lloyd Piqueab039b52019-02-13 14:22:42 -08002047 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002048 const auto& displays = ON_MAIN_THREAD(mDisplays);
2049 refreshArgs.outputs.reserve(displays.size());
2050 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002051 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2052 }
2053 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002054 if (auto layerFE = layer->getCompositionEngineLayerFE())
2055 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002056 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002057 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2058 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002059 if (auto layerFE = layer->getCompositionEngineLayerFE())
2060 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002061 }
2062
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002063 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002064 refreshArgs.outputColorSetting = useColorManagement
2065 ? mDisplayColorSetting
2066 : compositionengine::OutputColorSetting::kUnmanaged;
2067 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2068 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002069
2070 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2071 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002072 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002073 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002074
2075 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2076 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2077 mDrawingState.colorMatrixChanged = false;
2078 }
2079
2080 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2081
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002082 if (mDebugRegion != 0) {
2083 refreshArgs.devOptFlashDirtyRegionsDelay =
2084 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2085 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002086
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002087 mGeometryInvalid = false;
2088
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002089 // Store the present time just before calling to the composition engine so we could notify
2090 // the scheduler.
2091 const auto presentTime = systemTime();
2092
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002093 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002094 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2095 // Reset the frame start time now that we've recorded this frame.
2096 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002097
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002098 mScheduler->onDisplayRefreshed(presentTime);
2099
David Sodmanfa9b2af2017-12-24 13:28:59 -08002100 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002101 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002102
Alec Mouri8f7a0102020-04-15 12:11:10 -07002103 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2104
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002105 mHadClientComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2106 const auto& state = pair.second->getCompositionDisplay()->getState();
2107 return state.usesClientComposition && !state.reusedClientComposition;
2108 });
2109 mHadDeviceComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2110 const auto& state = pair.second->getCompositionDisplay()->getState();
2111 return state.usesDeviceComposition;
2112 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002113 mReusedClientComposition =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002114 std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2115 const auto& state = pair.second->getCompositionDisplay()->getState();
2116 return state.reusedClientComposition;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002117 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002118
Alec Mouri8f7a0102020-04-15 12:11:10 -07002119 // Only report a strategy change if we move in and out of composition with hw overlays
2120 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2121 mTimeStats->incrementCompositionStrategyChanges();
2122 }
2123
Yichi Chen28dee2c2020-07-06 21:24:14 +08002124 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
2125 mVSyncModulator->onRefreshed(mHadClientComposition || mReusedClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002126
David Sodman7e4ae112018-02-09 15:02:28 -08002127 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002128 if (mVisibleRegionsDirty) {
2129 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002130 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002131 mTracing.notify("visibleRegionsDirty");
2132 }
2133 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002134
2135 if (mCompositionEngine->needsAnotherUpdate()) {
2136 signalLayerUpdate();
2137 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002138}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002139
David Sodmanfa9b2af2017-12-24 13:28:59 -08002140bool SurfaceFlinger::handleMessageInvalidate() {
2141 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002142 bool refreshNeeded = handlePageFlip();
2143
Vishnu Nair4351ad52019-02-11 14:13:02 -08002144 if (mVisibleRegionsDirty) {
2145 computeLayerBounds();
2146 }
2147
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002148 for (auto& layer : mLayersPendingRefresh) {
2149 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002150 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002151 invalidateLayerStack(layer, visibleReg);
2152 }
2153 mLayersPendingRefresh.clear();
2154 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002155}
2156
Ana Krulece588e312018-09-18 12:32:24 -07002157void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2158 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002159 // Update queue of past composite+present times and determine the
2160 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002161 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002162 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002163 while (!getBE().mCompositePresentTimes.empty()) {
2164 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002165 // Cached values should have been updated before calling this method,
2166 // which helps avoid duplicate syscalls.
2167 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2168 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2169 break;
2170 }
2171 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002172 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002173 }
2174
2175 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002176 while (getBE().mCompositePresentTimes.size() > 16) {
2177 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002178 }
2179
Ana Krulece588e312018-09-18 12:32:24 -07002180 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002181}
2182
Ana Krulece588e312018-09-18 12:32:24 -07002183void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2184 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002185 // Integer division and modulo round toward 0 not -inf, so we need to
2186 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002187 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2188 ? (stats.vsyncPeriod -
2189 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2190 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002191
Ady Abraham9e16a482019-12-03 17:19:41 -08002192 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002193 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002194 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002195 }
2196
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002197 // Snap the latency to a value that removes scheduling jitter from the
2198 // composition and present times, which often have >1ms of jitter.
2199 // Reducing jitter is important if an app attempts to extrapolate
2200 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002201 // Snapping also allows an app to precisely calculate
2202 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002203 nsecs_t bias = stats.vsyncPeriod / 2;
2204 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2205 nsecs_t snappedCompositeToPresentLatency =
2206 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002207
David Sodman99974d22017-11-28 12:04:33 -08002208 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002209 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2210 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002211 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002212}
2213
David Sodman2b406362017-12-15 13:33:47 -08002214void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002215{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002216 ATRACE_CALL();
2217 ALOGV("postComposition");
2218
Brian Andersonf6386862016-10-31 16:34:13 -07002219 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002220 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002221 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002222 }
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002223
2224 const auto* display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002225
David Sodman73beded2017-11-15 11:56:06 -08002226 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002227 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002228 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002229 glCompositionDoneFenceTime =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002230 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002231 ->getRenderSurface()
2232 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002233 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002234 } else {
2235 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2236 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002237
David Sodman73beded2017-11-15 11:56:06 -08002238 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002239 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002240 mPreviousPresentFences[0] =
2241 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Ady Abrahambe0f9482019-04-24 15:41:53 -07002242 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002243 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002244
Ana Krulece588e312018-09-18 12:32:24 -07002245 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002246 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002247
Lloyd Piqueab039b52019-02-13 14:22:42 -08002248 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2249 // be sampled a little later than when we started doing work for this frame,
2250 // but that should be okay since updateCompositorTiming has snapping logic.
2251 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2252 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002253 CompositorTiming compositorTiming;
2254 {
David Sodman99974d22017-11-28 12:04:33 -08002255 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2256 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002257 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002258
Edgar Arriaga844fa672020-01-16 14:21:42 -08002259 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002260 const bool frameLatched = layer->onPostComposition(display, glCompositionDoneFenceTime,
2261 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002262 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002263 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002264 }
Robert Carr2047fae2016-11-28 14:09:09 -08002265 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002266
Valerie Hau4b678442020-04-14 10:50:42 -07002267 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2268 mTransactionCompletedThread.sendCallbacks();
2269
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002270 if (display && display->isPrimary() && display->getPowerMode() == hal::PowerMode::ON &&
2271 presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002272 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002273 }
2274
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002275 const bool isDisplayConnected = display && getHwComposer().isConnected(*display->getId());
2276
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002277 if (!hasSyncFramework) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002278 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002279 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002280 }
2281 }
2282
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002283 if (mAnimCompositionPending) {
2284 mAnimCompositionPending = false;
2285
Brian Anderson4e606e32017-03-16 15:34:57 -07002286 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002287 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002288 std::move(presentFenceTime));
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002289 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002290 // The HWC doesn't support present fences, so use the refresh
2291 // timestamp instead.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002292 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002293 mAnimFrameTracker.setActualPresentTime(presentTime);
2294 }
2295 mAnimFrameTracker.advanceFrame();
2296 }
Dan Stozab90cf072015-03-05 11:05:59 -08002297
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002298 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002299 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002300 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002301 }
2302
Vishnu Nair9b079a22020-01-21 14:36:08 -08002303 if (mReusedClientComposition) {
2304 mTimeStats->incrementClientCompositionReusedFrames();
2305 }
2306
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002307 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002308
Alec Mouri717bcb62020-02-10 17:07:19 -08002309 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2310 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2311 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2312
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002313 if (mLastJankDuration > 0) {
2314 ATRACE_NAME("Jank detected");
2315 const int32_t jankyDurationMillis = mLastJankDuration / (1000 * 1000);
2316 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED, jankyDurationMillis,
2317 mMissedFrameJankCount);
2318 mLastJankDuration = -1;
2319 }
2320
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002321 if (isDisplayConnected && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002322 return;
2323 }
2324
2325 nsecs_t currentTime = systemTime();
2326 if (mHasPoweredOff) {
2327 mHasPoweredOff = false;
2328 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002329 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002330 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002331 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2332 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002333 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002334 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002335 }
David Sodman4a36e932017-11-07 14:29:47 -08002336 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002337 }
David Sodman4a36e932017-11-07 14:29:47 -08002338 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002339
Alec Mouri4dde1782019-09-30 17:27:13 -07002340 // Cleanup any outstanding resources due to rendering a prior frame.
2341 getRenderEngine().cleanupPostRender();
2342
Dan Stoza436ccf32018-06-21 12:10:12 -07002343 {
2344 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002345 if (mTexturePool.size() < mTexturePoolSize) {
2346 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002347 const size_t offset = mTexturePool.size();
2348 mTexturePool.resize(mTexturePoolSize);
2349 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2350 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002351 } else if (mTexturePool.size() > mTexturePoolSize) {
2352 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2353 const size_t offset = mTexturePoolSize;
2354 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2355 mTexturePool.resize(mTexturePoolSize);
2356 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002357 }
2358 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002359
Kevin DuBois413287f2019-02-25 08:46:47 -08002360 if (mLumaSampling && mRegionSamplingThread) {
2361 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002362 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002363
2364 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2365 // side-effect of getTotalSize(), so we check that again here
2366 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002367 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002368 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2369 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002370}
2371
Lloyd Pique7eebe692020-04-22 22:40:06 -07002372FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2373 return displayDevice.getViewport().toFloatRect();
2374}
2375
Vishnu Nair4351ad52019-02-11 14:13:02 -08002376void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002377 for (const auto& pair : ON_MAIN_THREAD(mDisplays)) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08002378 const auto& displayDevice = pair.second;
2379 const auto display = displayDevice->getCompositionDisplay();
2380 for (const auto& layer : mDrawingState.layersSortedByZ) {
2381 // only consider the layers on the given layer stack
2382 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002383 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002384 }
2385
Lloyd Pique7eebe692020-04-22 22:40:06 -07002386 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002387 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002388 }
2389 }
2390}
2391
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002392void SurfaceFlinger::postFrame() {
2393 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002394 if (display && getHwComposer().isConnected(*display->getId())) {
2395 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002396 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2397 logFrameStats();
2398 }
2399 }
2400}
2401
Mathias Agopian87baae12012-07-31 12:38:26 -07002402void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002403{
Mathias Agopian841cde52012-03-01 15:44:37 -08002404 ATRACE_CALL();
2405
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002406 // here we keep a copy of the drawing state (that is the state that's
2407 // going to be overwritten by handleTransactionLocked()) outside of
2408 // mStateLock so that the side-effects of the State assignment
2409 // don't happen with mStateLock held (which can cause deadlocks).
2410 State drawingState(mDrawingState);
2411
Mathias Agopianca4d3602011-05-19 15:38:14 -07002412 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002413 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002414
Mathias Agopianca4d3602011-05-19 15:38:14 -07002415 // Here we're guaranteed that some transaction flags are set
2416 // so we can call handleTransactionLocked() unconditionally.
2417 // We call getTransactionFlags(), which will also clear the flags,
2418 // with mStateLock held to guarantee that mCurrentState won't change
2419 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002420
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002421 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002422 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002423 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002424
Mathias Agopianca4d3602011-05-19 15:38:14 -07002425 mDebugInTransaction = 0;
2426 invalidateHwcGeometry();
2427 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002428}
2429
Lloyd Piqueba04e622017-12-14 17:11:26 -08002430void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2431 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002432 const std::optional<DisplayIdentificationInfo> info =
2433 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002434
Dominik Laskowski075d3172018-05-24 15:50:06 -07002435 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002436 continue;
2437 }
2438
Dominik Laskowski55c85402020-01-21 16:25:47 -08002439 const DisplayId displayId = info->id;
2440 const auto it = mPhysicalDisplayTokens.find(displayId);
2441
Peiyong Line9d809e2020-04-14 13:10:48 -07002442 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002443 if (it == mPhysicalDisplayTokens.end()) {
2444 ALOGV("Creating display %s", to_string(displayId).c_str());
2445
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002446 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002447 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002448 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002449
Dominik Laskowski075d3172018-05-24 15:50:06 -07002450 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002451 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2452 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002453 state.isSecure = true; // All physical displays are currently considered secure.
2454 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002455
2456 sp<IBinder> token = new BBinder();
2457 mCurrentState.displays.add(token, state);
2458 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2459
Dominik Laskowski075d3172018-05-24 15:50:06 -07002460 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002461 } else {
2462 ALOGV("Recreating display %s", to_string(displayId).c_str());
2463
2464 const auto token = it->second;
2465 auto& state = mCurrentState.displays.editValueFor(token);
2466 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002467 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002468 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002469 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002470
Dominik Laskowski55c85402020-01-21 16:25:47 -08002471 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002472 if (index >= 0) {
2473 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2474 mInterceptor->saveDisplayDeletion(state.sequenceId);
2475 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002476 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002477 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002478 }
2479
2480 processDisplayChangesLocked();
2481 }
2482
2483 mPendingHotplugEvents.clear();
2484}
2485
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002486void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002487 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2488 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002489}
2490
Lloyd Pique99d3da52018-01-22 17:48:03 -08002491sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002492 const wp<IBinder>& displayToken,
2493 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002494 const DisplayDeviceState& state,
2495 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002497 auto displayId = compositionDisplay->getDisplayId();
2498 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002499 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002500 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002501 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002502 creationArgs.hasWideColorGamut = false;
2503 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002504
Dominik Laskowski55c85402020-01-21 16:25:47 -08002505 if (const auto& physical = state.physical) {
2506 creationArgs.connectionType = physical->type;
2507 }
2508
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002509 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002510 creationArgs.isPrimary = isInternalDisplay;
2511
2512 if (useColorManagement && displayId) {
2513 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002514 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002515 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002516 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002517 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002518
Dominik Laskowski7e045462018-05-30 13:02:02 -07002519 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002520 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002521 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522 }
tangrobin6753a022018-08-10 10:58:54 +08002523 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002524
Dominik Laskowski075d3172018-05-24 15:50:06 -07002525 if (displayId) {
2526 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002527 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002528 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002529 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002530
Lloyd Pique90c115d2018-09-18 21:39:42 -07002531 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002532 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002533 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002534
Lloyd Pique99d3da52018-01-22 17:48:03 -08002535 // Make sure that composition can never be stalled by a virtual display
2536 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002537 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002538 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002539 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2540 }
2541
Dominik Laskowski718f9602019-11-09 20:01:35 -08002542 creationArgs.physicalOrientation =
2543 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002544
Lloyd Pique99d3da52018-01-22 17:48:03 -08002545 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002546 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002548 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002549
2550 if (maxFrameBufferAcquiredBuffers >= 3) {
2551 nativeWindowSurface->preallocateBuffers();
2552 }
2553
2554 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002555 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002556 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002558 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002560 display->getCompositionDisplay()->setColorProfile(
2561 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2562 RenderIntent::COLORIMETRIC,
2563 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002564 if (!state.isVirtual()) {
2565 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002566 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2567 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002568 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002570 display->setLayerStack(state.layerStack);
2571 display->setProjection(state.orientation, state.viewport, state.frame);
2572 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002573
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002574 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002575}
2576
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002577void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2578 const DisplayDeviceState& state) {
2579 int width = 0;
2580 int height = 0;
2581 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2582 if (state.physical) {
2583 const auto& activeConfig =
2584 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2585 width = activeConfig->getWidth();
2586 height = activeConfig->getHeight();
2587 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2588 } else if (state.surface != nullptr) {
2589 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2590 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2591 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2592 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2593 int intPixelFormat;
2594 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2595 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2596 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2597 } else {
2598 // Virtual displays without a surface are dormant:
2599 // they have external state (layer stack, projection,
2600 // etc.) but no internal state (i.e. a DisplayDevice).
2601 return;
2602 }
2603
2604 compositionengine::DisplayCreationArgsBuilder builder;
2605 if (const auto& physical = state.physical) {
2606 builder.setPhysical({physical->id, physical->type});
2607 }
2608 builder.setPixels(ui::Size(width, height));
2609 builder.setPixelFormat(pixelFormat);
2610 builder.setIsSecure(state.isSecure);
2611 builder.setLayerStackId(state.layerStack);
2612 builder.setPowerAdvisor(&mPowerAdvisor);
2613 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2614 builder.setName(state.displayName);
2615 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2616
2617 sp<compositionengine::DisplaySurface> displaySurface;
2618 sp<IGraphicBufferProducer> producer;
2619 sp<IGraphicBufferProducer> bqProducer;
2620 sp<IGraphicBufferConsumer> bqConsumer;
2621 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2622
2623 std::optional<DisplayId> displayId = compositionDisplay->getId();
2624
2625 if (state.isVirtual()) {
2626 sp<VirtualDisplaySurface> vds =
2627 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2628 bqConsumer, state.displayName);
2629
2630 displaySurface = vds;
2631 producer = vds;
2632 } else {
2633 ALOGE_IF(state.surface != nullptr,
2634 "adding a supported display, but rendering "
2635 "surface is provided (%p), ignoring it",
2636 state.surface.get());
2637
2638 LOG_ALWAYS_FATAL_IF(!displayId);
2639 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2640 maxGraphicsWidth, maxGraphicsHeight);
2641 producer = bqProducer;
2642 }
2643
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002644 LOG_FATAL_IF(!displaySurface);
2645 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2646 displaySurface, producer);
2647 mDisplays.emplace(displayToken, display);
2648 if (!state.isVirtual()) {
2649 LOG_FATAL_IF(!displayId);
2650 dispatchDisplayHotplugEvent(displayId->value, true);
2651 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002652
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002653 if (display->isPrimary()) {
2654 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002655 }
2656}
2657
2658void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2659 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2660 // Save display ID before disconnecting.
2661 const auto displayId = display->getId();
2662 display->disconnect();
2663
2664 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002665 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002666 dispatchDisplayHotplugEvent(displayId->value, false);
2667 }
2668 }
2669
2670 mDisplays.erase(displayToken);
2671}
2672
2673void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2674 const DisplayDeviceState& currentState,
2675 const DisplayDeviceState& drawingState) {
2676 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2677 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002678 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002679 // changing the surface is like destroying and recreating the DisplayDevice
2680 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2681 display->disconnect();
2682 }
2683 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002684 if (const auto& physical = currentState.physical) {
2685 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2686 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002687 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002688 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002689 const auto display = getDisplayDeviceLocked(displayToken);
2690 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002691 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002692 return;
2693 }
2694
2695 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2696 if (currentState.layerStack != drawingState.layerStack) {
2697 display->setLayerStack(currentState.layerStack);
2698 }
2699 if ((currentState.orientation != drawingState.orientation) ||
2700 (currentState.viewport != drawingState.viewport) ||
2701 (currentState.frame != drawingState.frame)) {
2702 display->setProjection(currentState.orientation, currentState.viewport,
2703 currentState.frame);
2704 }
2705 if (currentState.width != drawingState.width ||
2706 currentState.height != drawingState.height) {
2707 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07002708
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002709 if (display->isPrimary()) {
2710 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2711 }
Dominik Laskowski20134642020-04-20 22:36:44 -07002712
2713 if (mRefreshRateOverlay) {
2714 mRefreshRateOverlay->setViewport(display->getSize());
2715 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002716 }
2717 }
2718}
2719
Lloyd Pique347200f2017-12-14 17:00:15 -08002720void SurfaceFlinger::processDisplayChangesLocked() {
2721 // here we take advantage of Vector's copy-on-write semantics to
2722 // improve performance by skipping the transaction entirely when
2723 // know that the lists are identical
2724 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2725 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2726 if (!curr.isIdenticalTo(draw)) {
2727 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002728
2729 // find the displays that were removed
2730 // (ie: in drawing state but not in current state)
2731 // also handle displays that changed
2732 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002733 for (size_t i = 0; i < draw.size(); i++) {
2734 const wp<IBinder>& displayToken = draw.keyAt(i);
2735 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 if (j < 0) {
2737 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002738 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002739 } else {
2740 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002741 const DisplayDeviceState& currentState = curr[j];
2742 const DisplayDeviceState& drawingState = draw[i];
2743 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002744 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 }
2746
2747 // find displays that were added
2748 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002749 for (size_t i = 0; i < curr.size(); i++) {
2750 const wp<IBinder>& displayToken = curr.keyAt(i);
2751 if (draw.indexOfKey(displayToken) < 0) {
2752 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002753 }
2754 }
2755 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002756
2757 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002758}
2759
Mathias Agopian87baae12012-07-31 12:38:26 -07002760void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002761{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002762 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2763
Dan Stoza7dde5992015-05-22 09:51:44 -07002764 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002765 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002766 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002767 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002768
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 /*
2770 * Traversal of the children
2771 * (perform the transaction for each of them if needed)
2772 */
2773
Valerie Haud50e7412020-06-16 17:58:14 -07002774 if ((transactionFlags & eTraversalNeeded) || mForceTraversal) {
2775 mForceTraversal = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002776 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002778 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779
2780 const uint32_t flags = layer->doTransaction(0);
2781 if (flags & Layer::eVisibleRegion)
2782 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002783
2784 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002785 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002786 }
Robert Carr2047fae2016-11-28 14:09:09 -08002787 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788 }
2789
2790 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002791 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792 */
2793
Mathias Agopiane57f2922012-08-09 16:29:12 -07002794 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002795 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002796 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002797 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798
Vishnu Nair6213bd92020-05-08 17:42:25 -07002799 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002800 // The transform hint might have changed for some layers
2801 // (either because a display has changed, or because a layer
2802 // as changed).
2803 //
2804 // Walk through all the layers in currentLayers,
2805 // and update their transform hint.
2806 //
2807 // If a layer is visible only on a single display, then that
2808 // display is used to calculate the hint, otherwise we use the
2809 // default display.
2810 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002811 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002812 // the hint is set before we acquire a buffer from the surface texture.
2813 //
2814 // NOTE: layer transactions have taken place already, so we use their
2815 // drawing state. However, SurfaceFlinger's own transaction has not
2816 // happened yet, so we must use the current state layer list
2817 // (soon to become the drawing state list).
2818 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002819 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002820 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002821 bool first = true;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002822 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08002823 // NOTE: we rely on the fact that layers are sorted by
2824 // layerStack first (so we don't have to traverse the list
2825 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002826 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002827 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002828 currentlayerStack = layerStack;
2829 // figure out if this layerstack is mirrored
2830 // (more than one display) if so, pick the default display,
2831 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002832 hintDisplay = nullptr;
2833 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002834 if (display->getCompositionDisplay()
2835 ->belongsInOutput(layer->getLayerStack(),
2836 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002837 if (hintDisplay) {
2838 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002839 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002840 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002841 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002842 }
2843 }
2844 }
2845 }
Chet Haase91d25932013-04-11 15:24:55 -07002846
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002847 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002848 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2849 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002850
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002851 // could be null when this layer is using a layerStack
2852 // that is not visible on any display. Also can occur at
2853 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002854 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002855 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002856
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002857 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002858 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002859 if (hintDisplay) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002860 layer->updateTransformHint(hintDisplay->getTransformHint());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002861 }
Robert Carr2047fae2016-11-28 14:09:09 -08002862
2863 first = false;
2864 });
Mathias Agopian84300952012-11-21 16:02:13 -08002865 }
2866
Mathias Agopian3559b072012-08-15 13:46:03 -07002867 /*
2868 * Perform our own transaction if needed
2869 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002870
2871 if (mLayersAdded) {
2872 mLayersAdded = false;
2873 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002874 mVisibleRegionsDirty = true;
2875 }
2876
2877 // some layers might have been removed, so
2878 // we need to update the regions they're exposing.
2879 if (mLayersRemoved) {
2880 mLayersRemoved = false;
2881 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002882 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002884 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002885 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002886 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002887 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002888 }
Robert Carr2047fae2016-11-28 14:09:09 -08002889 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890 }
2891
Vishnu Nairec0ab382019-02-13 15:32:56 -08002892 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002894}
2895
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002896void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002897 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002898 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002899 return;
2900 }
2901
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002902 if (mVisibleRegionsDirty || mInputInfoChanged) {
2903 mInputInfoChanged = false;
2904 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002905 } else if (mInputWindowCommands.syncInputWindows) {
2906 // If the caller requested to sync input windows, but there are no
2907 // changes to input windows, notify immediately.
2908 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002909 }
2910
Arthur Hung6cbb9752019-09-05 16:38:18 +08002911 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002912}
2913
2914void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002915 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002916
2917 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Robert Carredd13602020-04-13 17:24:34 -07002918 if (layer->needsInputInfo()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002919 // When calculating the screen bounds we ignore the transparent region since it may
2920 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002921 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002922 }
2923 });
chaviw291d88a2019-02-14 10:33:58 -08002924
2925 mInputFlinger->setInputWindows(inputHandles,
2926 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2927 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002928}
2929
Vishnu Nairec0ab382019-02-13 15:32:56 -08002930void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002931 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002932 mPendingInputWindowCommands.clear();
2933}
2934
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002935void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002936 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002937 for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002938 if (display->getId()) {
2939 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002940 }
2941 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002942
2943 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002944}
2945
Ady Abraham2139f732019-11-13 18:56:40 -08002946void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002947 Scheduler::ConfigEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08002948 // If this is called from the main thread mStateLock must be locked before
2949 // Currently the only way to call this function from the main thread is from
2950 // Sheduler::chooseRefreshRateForContent
2951
2952 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002953 changeRefreshRateLocked(refreshRate, event);
2954}
2955
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002956void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2957 if (mScheduler) {
2958 // In practice it's not allowed to hotplug in/out the primary display once it's been
2959 // connected during startup, but some tests do it, so just warn and return.
2960 ALOGW("Can't re-init scheduler");
2961 return;
2962 }
2963
Ady Abraham2139f732019-11-13 18:56:40 -08002964 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002965 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002966 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002967 primaryDisplayId),
2968 currentConfig);
2969 mRefreshRateStats =
2970 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002971 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002972 mRefreshRateStats->setConfigMode(currentConfig);
2973
Ady Abraham9e16a482019-12-03 17:19:41 -08002974 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2975
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002976 // start the EventThread
2977 mScheduler =
2978 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002979 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002980 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002981 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002982 impl::EventThread::InterceptVSyncsCallback());
2983 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002984 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002985 [this](nsecs_t timestamp) {
2986 mInterceptor->saveVSyncEvent(timestamp);
2987 });
2988
2989 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2990 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002991 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002992
2993 mRegionSamplingThread =
2994 new RegionSamplingThread(*this, *mScheduler,
2995 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002996 // Dispatch a config change request for the primary display on scheduler
2997 // initialization, so that the EventThreads always contain a reference to a
2998 // prior configuration.
2999 //
3000 // This is a bit hacky, but this avoids a back-pointer into the main SF
3001 // classes from EventThread, and there should be no run-time binder cost
3002 // anyway since there are no connected apps at this point.
3003 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07003004 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07003005 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, primaryDisplayId.value,
3006 currentConfig, vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003007}
3008
Mathias Agopian4fec8732012-06-29 14:12:52 -07003009void SurfaceFlinger::commitTransaction()
3010{
Vishnu Nair60db8c02020-04-02 11:55:16 -07003011 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003012 mTransactionPending = false;
3013 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003014 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003015}
3016
Lloyd Pique58e24a32019-08-01 15:50:14 -07003017void SurfaceFlinger::commitTransactionLocked() {
3018 if (!mLayersPendingRemoval.isEmpty()) {
3019 // Notify removed layers now that they can't be drawn from
3020 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003021 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003022
3023 // Ensure any buffers set to display on any children are released.
3024 if (l->isRemovedFromCurrentState()) {
3025 l->latchAndReleaseBuffer();
3026 }
3027
3028 // If the layer has been removed and has no parent, then it will not be reachable
3029 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3030 // ensure we can copy its current to drawing state.
3031 if (!l->getParent()) {
3032 mOffscreenLayers.emplace(l.get());
3033 }
3034 }
3035 mLayersPendingRemoval.clear();
3036 }
3037
3038 // If this transaction is part of a window animation then the next frame
3039 // we composite should be considered an animation as well.
3040 mAnimCompositionPending = mAnimTransactionPending;
3041
3042 mDrawingState = mCurrentState;
3043 // clear the "changed" flags in current state
3044 mCurrentState.colorMatrixChanged = false;
3045
Edgar Arriaga844fa672020-01-16 14:21:42 -08003046 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003047 layer->commitChildList();
3048
3049 // If the layer can be reached when traversing mDrawingState, then the layer is no
3050 // longer offscreen. Remove the layer from the offscreenLayer set.
3051 if (mOffscreenLayers.count(layer)) {
3052 mOffscreenLayers.erase(layer);
3053 }
3054 });
3055
3056 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003057 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003058}
3059
chaviw74d90ad2019-04-26 14:45:26 -07003060void SurfaceFlinger::commitOffscreenLayers() {
3061 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003062 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003063 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3064 if (!trFlags) return;
3065
3066 layer->doTransaction(0);
3067 layer->commitChildList();
3068 });
3069 }
3070}
3071
Chia-I Wuab0c3192017-08-01 11:29:00 -07003072void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07003073 for (const auto& [token, displayDevice] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003074 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003075 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003076 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003077 }
3078 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003079}
3080
Dan Stoza6b9454d2014-11-07 16:00:59 -08003081bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082{
Ady Abraham09bd3922019-04-08 10:44:56 -07003083 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003084 ALOGV("handlePageFlip");
3085
Brian Andersond6927fb2016-07-23 23:37:30 -07003086 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087
Mathias Agopian4fec8732012-06-29 14:12:52 -07003088 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003089 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003090 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003091
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003092 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3093
Eric Penner51c59cd2014-07-28 19:51:58 -07003094 // Store the set of layers that need updates. This set must not change as
3095 // buffers are being latched, as this could result in a deadlock.
3096 // Example: Two producers share the same command stream and:
3097 // 1.) Layer 0 is latched
3098 // 2.) Layer 0 gets a new frame
3099 // 2.) Layer 1 gets a new frame
3100 // 3.) Layer 1 is latched.
3101 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3102 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003103 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003104 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003105 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003106 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003107 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003108 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003109 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003110 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003111 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003112 } else {
3113 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003114 }
Robert Carr2047fae2016-11-28 14:09:09 -08003115 });
3116
chaviw49a108c2019-08-12 11:23:06 -07003117 // The client can continue submitting buffers for offscreen layers, but they will not
3118 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3119 // layers to ensure dequeueBuffer doesn't block indefinitely.
3120 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003121 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003122 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3123 }
3124
Lloyd Piquef2c79392018-12-20 16:23:33 -08003125 if (!mLayersWithQueuedFrames.empty()) {
3126 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3127 // writes to Layer current state. See also b/119481871
3128 Mutex::Autolock lock(mStateLock);
3129
3130 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003131 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003132 mLayersPendingRefresh.push_back(layer);
3133 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003134 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003135 if (layer->isBufferLatched()) {
3136 newDataLatched = true;
3137 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003138 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003139 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003140
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003141 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003142
3143 // If we will need to wake up at some time in the future to deal with a
3144 // queued frame that shouldn't be displayed during this vsync period, wake
3145 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003146 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003147 signalLayerUpdate();
3148 }
3149
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003150 // enter boot animation on first buffer latch
3151 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3152 ALOGI("Enter boot animation");
3153 mBootStage = BootStage::BOOTANIMATION;
3154 }
3155
Edgar Arriaga844fa672020-01-16 14:21:42 -08003156 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003157
Dan Stoza6b9454d2014-11-07 16:00:59 -08003158 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003159 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160}
3161
Mathias Agopianad456f92011-01-13 17:53:01 -08003162void SurfaceFlinger::invalidateHwcGeometry()
3163{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003164 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003165}
3166
Robert Carrc0df3122019-04-11 13:18:21 -07003167status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3168 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3169 const sp<IBinder>& parentHandle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003170 const sp<Layer>& parentLayer, bool addToCurrentState,
3171 uint32_t* outTransformHint) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003172 // add this layer to the current state list
3173 {
3174 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003175 sp<Layer> parent;
3176 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003177 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003178 if (parent == nullptr) {
3179 return NAME_NOT_FOUND;
3180 }
3181 } else {
3182 parent = parentLayer;
3183 }
3184
Ady Abraham0a525092020-03-03 12:51:24 -08003185 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003186 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003187 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003188 return NO_MEMORY;
3189 }
Robert Carrc0df3122019-04-11 13:18:21 -07003190
3191 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3192
Robert Carrb89ea9d2018-12-10 13:01:14 -08003193 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003194 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003195 } else if (parent == nullptr) {
3196 lbc->onRemovedFromCurrentState();
3197 } else if (parent->isRemovedFromCurrentState()) {
3198 parent->addChild(lbc);
3199 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003200 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003201 parent->addChild(lbc);
3202 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003203
Yiwei Zhang243b3782018-05-15 17:40:04 -07003204 if (gbc != nullptr) {
3205 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3206 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3207 mMaxGraphicBufferProducerListSize,
3208 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3209 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003210 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003211 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003212
3213 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07003214 lbc->updateTransformHint(display->getTransformHint());
Vishnu Nair6213bd92020-05-08 17:42:25 -07003215 }
3216 if (outTransformHint) {
3217 *outTransformHint = lbc->getTransformHint();
3218 }
3219
Robert Carr1f0a16a2016-10-24 16:27:39 -07003220 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003221 }
3222
Mathias Agopian96f08192010-06-02 23:28:45 -07003223 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003224 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003225
Dan Stoza7d89d062015-04-30 13:29:25 -07003226 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003227}
3228
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003229void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3230 static_cast<void>(schedule([=] {
3231 Mutex::Autolock lock(mStateLock);
3232 mGraphicBufferProducerList.erase(binder);
3233 }));
3234}
3235
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003236uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003237 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003238}
3239
Mathias Agopian3f844832013-08-07 21:24:32 -07003240uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003241 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242}
3243
Mathias Agopian3f844832013-08-07 21:24:32 -07003244uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ady Abrahambf1349c2020-06-12 14:26:18 -07003245 return setTransactionFlags(flags, Scheduler::TransactionStart::Normal);
Dan Stoza84d619e2018-03-28 17:07:36 -07003246}
3247
3248uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003249 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003250 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003251 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003253 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003254 }
3255 return old;
3256}
3257
Valerie Haud50e7412020-06-16 17:58:14 -07003258void SurfaceFlinger::setTraversalNeeded() {
3259 mForceTraversal = true;
Robert Carr7ec777d2020-05-29 12:02:51 -07003260}
3261
Marissa Wall713b63f2018-10-17 15:42:43 -07003262bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003263 // to prevent onHandleDestroyed from being called while the lock is held,
3264 // we must keep a copy of the transactions (specifically the composer
3265 // states) around outside the scope of the lock
3266 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003267 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003268 {
3269 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003270
Valerie Haufce31b82019-04-30 16:41:14 -07003271 auto it = mTransactionQueues.begin();
3272 while (it != mTransactionQueues.end()) {
3273 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003274
Valerie Haufce31b82019-04-30 16:41:14 -07003275 while (!transactionQueue.empty()) {
3276 const auto& transaction = transactionQueue.front();
3277 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3278 transaction.states)) {
3279 setTransactionFlags(eTransactionFlushNeeded);
3280 break;
3281 }
3282 transactions.push_back(transaction);
3283 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3284 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003285 transaction.buffer, transaction.postTime,
3286 transaction.privileged, transaction.hasListenerCallbacks,
3287 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003288 transactionQueue.pop();
3289 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003290 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003291
Valerie Haufce31b82019-04-30 16:41:14 -07003292 if (transactionQueue.empty()) {
3293 it = mTransactionQueues.erase(it);
3294 mTransactionCV.broadcast();
3295 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003296 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003297 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003298 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003299 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003300 return flushedATransaction;
3301}
3302
3303bool SurfaceFlinger::transactionFlushNeeded() {
3304 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003305}
3306
chaviwca27f252018-02-06 16:46:39 -08003307
Marissa Wall17b4e452018-12-26 16:32:34 -08003308bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3309 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003310
3311 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003312 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3313 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3314 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3315 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3316 return false;
3317 }
3318
Marissa Wall713b63f2018-10-17 15:42:43 -07003319 for (const ComposerState& state : states) {
3320 const layer_state_t& s = state.state;
3321 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3322 continue;
3323 }
3324 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003325 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003326 }
3327 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003328 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003329}
3330
Valerie Hau9dab9732019-08-20 09:29:25 -07003331void SurfaceFlinger::setTransactionState(
3332 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3333 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3334 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3335 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003336 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003337
Valerie Haubc6ddb12019-03-08 11:10:15 -08003338 const int64_t postTime = systemTime();
3339
Robert Carr14167e02019-02-13 13:50:55 -08003340 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3341
Mathias Agopian698c0872011-06-28 19:09:31 -07003342 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003343
Marissa Wall713b63f2018-10-17 15:42:43 -07003344 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003345 auto itr = mTransactionQueues.find(applyToken);
3346 // if this is an animation frame, wait until prior animation frame has
3347 // been applied by SF
3348 if (flags & eAnimation) {
3349 while (itr != mTransactionQueues.end()) {
3350 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3351 if (CC_UNLIKELY(err != NO_ERROR)) {
3352 ALOGW_IF(err == TIMED_OUT,
3353 "setTransactionState timed out "
3354 "waiting for animation frame to apply");
3355 break;
3356 }
3357 itr = mTransactionQueues.find(applyToken);
3358 }
3359 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003360
Ady Abraham5facfb12020-04-22 15:18:31 -07003361 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003362 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003363 if (!pendingTransactions) {
3364 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3365 }
3366
3367 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003368 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003369 uncacheBuffer, postTime, privileged,
3370 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003371 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003372 return;
3373 }
3374
Valerie Haubc6ddb12019-03-08 11:10:15 -08003375 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003376 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3377 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003378}
3379
Valerie Hau9dab9732019-08-20 09:29:25 -07003380void SurfaceFlinger::applyTransactionState(
3381 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3382 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3383 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3384 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3385 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003386 uint32_t transactionFlags = 0;
3387
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003388 if (flags & eAnimation) {
3389 // For window updates that are part of an animation we must wait for
3390 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003391 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003392 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003393 if (CC_UNLIKELY(err != NO_ERROR)) {
3394 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003395 // caller after a few seconds.
3396 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3397 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003398 mAnimTransactionPending = false;
3399 break;
3400 }
3401 }
3402 }
3403
chaviwca27f252018-02-06 16:46:39 -08003404 for (const DisplayState& display : displays) {
3405 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003406 }
3407
Valerie Hau9dab9732019-08-20 09:29:25 -07003408 // start and end registration for listeners w/ no surface so they can get their callback. Note
3409 // that listeners with SurfaceControls will start registration during setClientStateLocked
3410 // below.
3411 for (const auto& listener : listenerCallbacks) {
3412 mTransactionCompletedThread.startRegistration(listener);
3413 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003414 }
3415
Valerie Hau9dab9732019-08-20 09:29:25 -07003416 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003417 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003418 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003419 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3420 listenerCallbacksWithSurfaces);
Ady Abraham5def7332020-05-29 16:13:47 -07003421 if ((flags & eAnimation) && state.state.surface) {
3422 if (const auto layer = fromHandleLocked(state.state.surface).promote(); layer) {
3423 mScheduler->recordLayerHistory(layer.get(), desiredPresentTime,
3424 LayerHistory::LayerUpdateType::AnimationTX);
3425 }
3426 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07003427 }
3428
Valerie Hau9dab9732019-08-20 09:29:25 -07003429 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003430 mTransactionCompletedThread.endRegistration(listenerCallback);
3431 }
3432
Marissa Walle2ffb422018-10-12 11:33:52 -07003433 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003434 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003435 mTransactionCompletedThread.sendCallbacks();
3436 }
3437 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003438
chaviw273171b2018-12-26 11:46:30 -08003439 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3440
Marissa Wall947d34e2019-03-29 14:03:53 -07003441 if (uncacheBuffer.isValid()) {
3442 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003443 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003444 }
3445
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003446 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3447 // anyway. This can be used as a flush mechanism for previous async transactions.
3448 // Empty animation transaction can be used to simulate back-pressure, so also force a
3449 // transaction for empty animation transactions.
3450 if (transactionFlags == 0 &&
3451 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003452 transactionFlags = eTransactionNeeded;
3453 }
3454
Marissa Wall06255332019-03-27 13:48:27 -07003455 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3456 // so we don't have to wake up again next frame to preform an uneeded traversal.
3457 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3458 transactionFlags = transactionFlags & (~eTraversalNeeded);
Valerie Haud50e7412020-06-16 17:58:14 -07003459 mForceTraversal = true;
Marissa Wall06255332019-03-27 13:48:27 -07003460 }
3461
Ady Abrahambf1349c2020-06-12 14:26:18 -07003462 const auto transactionStart = [](uint32_t flags) {
3463 if (flags & eEarlyWakeup) {
3464 return Scheduler::TransactionStart::Early;
3465 }
3466 if (flags & eExplicitEarlyWakeupEnd) {
3467 return Scheduler::TransactionStart::EarlyEnd;
3468 }
3469 if (flags & eExplicitEarlyWakeupStart) {
3470 return Scheduler::TransactionStart::EarlyStart;
3471 }
3472 return Scheduler::TransactionStart::Normal;
3473 }(flags);
3474
Mathias Agopian386aa982011-11-07 21:58:03 -08003475 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003476 if (mInterceptor->isEnabled()) {
3477 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003478 }
Irvel468051e2016-06-13 16:44:44 -07003479
Ady Abrahambf1349c2020-06-12 14:26:18 -07003480 // TODO(b/159125966): Remove eEarlyWakeup completly as no client should use this flag
3481 if (flags & eEarlyWakeup) {
3482 ALOGW("eEarlyWakeup is deprecated. Use eExplicitEarlyWakeup[Start|End]");
3483 }
3484
3485 if (!privileged && (flags & (eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd))) {
3486 ALOGE("Only WindowManager is allowed to use eExplicitEarlyWakeup[Start|End] flags");
3487 flags &= ~(eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd);
3488 }
3489
Mathias Agopian386aa982011-11-07 21:58:03 -08003490 // this triggers the transaction
Ady Abrahambf1349c2020-06-12 14:26:18 -07003491 setTransactionFlags(transactionFlags, transactionStart);
Mathias Agopian386aa982011-11-07 21:58:03 -08003492
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003493 if (flags & eAnimation) {
3494 mAnimTransactionPending = true;
3495 }
Robert Carr238f4a22020-04-29 13:04:02 -07003496
3497 // if this is a synchronous transaction, wait for it to take effect
3498 // before returning.
3499 const bool synchronous = flags & eSynchronous;
3500 const bool syncInput = inputWindowCommands.syncInputWindows;
3501 if (!synchronous && !syncInput) {
3502 return;
3503 }
3504
3505 if (synchronous) {
3506 mTransactionPending = true;
3507 }
3508 if (syncInput) {
chaviw4fe36852019-04-15 16:25:49 -07003509 mPendingSyncInputWindows = true;
3510 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003511
Robert Carr238f4a22020-04-29 13:04:02 -07003512
Valerie Hau0779ded2019-03-19 12:43:04 -07003513 // applyTransactionState can be called by either the main SF thread or by
3514 // another process through setTransactionState. While a given process may wish
3515 // to wait on synchronous transactions, the main SF thread should never
3516 // be blocked. Therefore, we only wait if isMainThread is false.
3517 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003518 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3519 if (CC_UNLIKELY(err != NO_ERROR)) {
3520 // just in case something goes wrong in SF, return to the
3521 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003522 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3523 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003524 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003525 break;
3526 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003527 }
Ady Abrahambf1349c2020-06-12 14:26:18 -07003528 } else {
3529 // even if a transaction is not needed, we need to update VsyncModulator
3530 // about explicit early indications
3531 if (transactionStart == Scheduler::TransactionStart::EarlyStart ||
3532 transactionStart == Scheduler::TransactionStart::EarlyEnd) {
3533 mVSyncModulator->setTransactionStart(transactionStart);
3534 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003535 }
3536}
3537
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003538uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3539 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3540 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003541
Mathias Agopiane57f2922012-08-09 16:29:12 -07003542 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003543 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3544
3545 const uint32_t what = s.what;
3546 if (what & DisplayState::eSurfaceChanged) {
3547 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3548 state.surface = s.surface;
3549 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003550 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003551 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003552 if (what & DisplayState::eLayerStackChanged) {
3553 if (state.layerStack != s.layerStack) {
3554 state.layerStack = s.layerStack;
3555 flags |= eDisplayTransactionNeeded;
3556 }
3557 }
3558 if (what & DisplayState::eDisplayProjectionChanged) {
3559 if (state.orientation != s.orientation) {
3560 state.orientation = s.orientation;
3561 flags |= eDisplayTransactionNeeded;
3562 }
3563 if (state.frame != s.frame) {
3564 state.frame = s.frame;
3565 flags |= eDisplayTransactionNeeded;
3566 }
3567 if (state.viewport != s.viewport) {
3568 state.viewport = s.viewport;
3569 flags |= eDisplayTransactionNeeded;
3570 }
3571 }
3572 if (what & DisplayState::eDisplaySizeChanged) {
3573 if (state.width != s.width) {
3574 state.width = s.width;
3575 flags |= eDisplayTransactionNeeded;
3576 }
3577 if (state.height != s.height) {
3578 state.height = s.height;
3579 flags |= eDisplayTransactionNeeded;
3580 }
3581 }
3582
Mathias Agopiane57f2922012-08-09 16:29:12 -07003583 return flags;
3584}
3585
Steven Thomasd4071902020-03-24 16:02:53 -07003586bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003587 IPCThreadState* ipc = IPCThreadState::self();
3588 const int pid = ipc->getCallingPid();
3589 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003590 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003591 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3592 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003593 return false;
3594 }
3595 return true;
3596}
3597
Marissa Wall3dad52d2019-03-22 14:03:19 -07003598uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003599 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3600 bool privileged,
3601 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003602 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003603
Valerie Hau9dab9732019-08-20 09:29:25 -07003604 for (auto& listener : s.listeners) {
3605 // note that startRegistration will not re-register if the listener has
3606 // already be registered for a prior surface control
3607 mTransactionCompletedThread.startRegistration(listener);
3608 listenerCallbacks.insert(listener);
3609 }
3610
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003611 sp<Layer> layer = nullptr;
3612 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003613 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003614 } else {
3615 // The client may provide us a null handle. Treat it as if the layer was removed.
3616 ALOGW("Attempt to set client state with a null layer handle");
3617 }
chaviw8b3871a2017-11-01 17:41:01 -07003618 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003619 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003620 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003621 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003622 }
chaviw8b3871a2017-11-01 17:41:01 -07003623 return 0;
3624 }
3625
chaviw8b3871a2017-11-01 17:41:01 -07003626 uint32_t flags = 0;
3627
Garfield Tan8a3083e2018-12-03 13:21:07 -08003628 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003629
3630 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3631 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003632 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003633 layer->pushPendingState();
3634 }
3635
Valerie Hau871d6352020-01-29 08:44:02 -08003636 // Only set by BLAST adapter layers
3637 if (what & layer_state_t::eProducerDisconnect) {
3638 layer->onDisconnect();
3639 }
3640
chaviw8b3871a2017-11-01 17:41:01 -07003641 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003642 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003643 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003644 }
chaviw8b3871a2017-11-01 17:41:01 -07003645 }
3646 if (what & layer_state_t::eLayerChanged) {
3647 // NOTE: index needs to be calculated before we update the state
3648 const auto& p = layer->getParent();
3649 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003650 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003651 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003652 mCurrentState.layersSortedByZ.removeAt(idx);
3653 mCurrentState.layersSortedByZ.add(layer);
3654 // we need traversal (state changed)
3655 // AND transaction (list changed)
3656 flags |= eTransactionNeeded|eTraversalNeeded;
3657 }
chaviw8b3871a2017-11-01 17:41:01 -07003658 } else {
3659 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003660 flags |= eTransactionNeeded|eTraversalNeeded;
3661 }
3662 }
chaviw8b3871a2017-11-01 17:41:01 -07003663 }
3664 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003665 // NOTE: index needs to be calculated before we update the state
3666 const auto& p = layer->getParent();
3667 if (p == nullptr) {
3668 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3669 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3670 mCurrentState.layersSortedByZ.removeAt(idx);
3671 mCurrentState.layersSortedByZ.add(layer);
3672 // we need traversal (state changed)
3673 // AND transaction (list changed)
3674 flags |= eTransactionNeeded|eTraversalNeeded;
3675 }
3676 } else {
3677 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3678 flags |= eTransactionNeeded|eTraversalNeeded;
3679 }
chaviw8b3871a2017-11-01 17:41:01 -07003680 }
3681 }
3682 if (what & layer_state_t::eSizeChanged) {
3683 if (layer->setSize(s.w, s.h)) {
3684 flags |= eTraversalNeeded;
3685 }
3686 }
3687 if (what & layer_state_t::eAlphaChanged) {
3688 if (layer->setAlpha(s.alpha))
3689 flags |= eTraversalNeeded;
3690 }
3691 if (what & layer_state_t::eColorChanged) {
3692 if (layer->setColor(s.color))
3693 flags |= eTraversalNeeded;
3694 }
Peiyong Lind3788632018-09-18 16:01:31 -07003695 if (what & layer_state_t::eColorTransformChanged) {
3696 if (layer->setColorTransform(s.colorTransform)) {
3697 flags |= eTraversalNeeded;
3698 }
3699 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003700 if (what & layer_state_t::eBackgroundColorChanged) {
3701 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3702 flags |= eTraversalNeeded;
3703 }
3704 }
chaviw8b3871a2017-11-01 17:41:01 -07003705 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003706 // TODO: b/109894387
3707 //
3708 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3709 // rotation. To see the problem observe that if we have a square parent, and a child
3710 // of the same size, then we rotate the child 45 degrees around it's center, the child
3711 // must now be cropped to a non rectangular 8 sided region.
3712 //
3713 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3714 // private API, and the WindowManager only uses rotation in one case, which is on a top
3715 // level layer in which cropping is not an issue.
3716 //
3717 // However given that abuse of rotation matrices could lead to surfaces extending outside
3718 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3719 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3720 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003721 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003722 flags |= eTraversalNeeded;
3723 }
3724 if (what & layer_state_t::eTransparentRegionChanged) {
3725 if (layer->setTransparentRegionHint(s.transparentRegion))
3726 flags |= eTraversalNeeded;
3727 }
3728 if (what & layer_state_t::eFlagsChanged) {
3729 if (layer->setFlags(s.flags, s.mask))
3730 flags |= eTraversalNeeded;
3731 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003732 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003733 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003734 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003735 if (what & layer_state_t::eCornerRadiusChanged) {
3736 if (layer->setCornerRadius(s.cornerRadius))
3737 flags |= eTraversalNeeded;
3738 }
Lucas Dupin130e55c2020-05-26 16:11:18 -07003739 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003740 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3741 }
chaviw8b3871a2017-11-01 17:41:01 -07003742 if (what & layer_state_t::eLayerStackChanged) {
3743 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3744 // We only allow setting layer stacks for top level layers,
3745 // everything else inherits layer stack from its parent.
3746 if (layer->hasParent()) {
3747 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003748 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003749 } else if (idx < 0) {
3750 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003751 "that also does not appear in the top level layer list. Something"
3752 " has gone wrong.",
3753 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003754 } else if (layer->setLayerStack(s.layerStack)) {
3755 mCurrentState.layersSortedByZ.removeAt(idx);
3756 mCurrentState.layersSortedByZ.add(layer);
3757 // we need traversal (state changed)
3758 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07003759 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003760 }
3761 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003762 if (what & layer_state_t::eDeferTransaction_legacy) {
3763 if (s.barrierHandle_legacy != nullptr) {
3764 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3765 } else if (s.barrierGbp_legacy != nullptr) {
3766 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003767 if (authenticateSurfaceTextureLocked(gbp)) {
3768 const auto& otherLayer =
3769 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003770 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003771 } else {
3772 ALOGE("Attempt to defer transaction to to an"
3773 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003774 }
3775 }
chaviw8b3871a2017-11-01 17:41:01 -07003776 // We don't trigger a traversal here because if no other state is
3777 // changed, we don't want this to cause any more work
3778 }
chaviw8b3871a2017-11-01 17:41:01 -07003779 if (what & layer_state_t::eReparentChildren) {
3780 if (layer->reparentChildren(s.reparentHandle)) {
3781 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003782 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003783 }
chaviw8b3871a2017-11-01 17:41:01 -07003784 if (what & layer_state_t::eDetachChildren) {
3785 layer->detachChildren();
3786 }
3787 if (what & layer_state_t::eOverrideScalingModeChanged) {
3788 layer->setOverrideScalingMode(s.overrideScalingMode);
3789 // We don't trigger a traversal here because if no other state is
3790 // changed, we don't want this to cause any more work
3791 }
Marissa Wall61c58622018-07-18 10:12:20 -07003792 if (what & layer_state_t::eTransformChanged) {
3793 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3794 }
3795 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3796 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3797 flags |= eTraversalNeeded;
3798 }
3799 if (what & layer_state_t::eCropChanged) {
3800 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3801 }
Marissa Wall861616d2018-10-22 12:52:23 -07003802 if (what & layer_state_t::eFrameChanged) {
3803 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3804 }
Marissa Wall61c58622018-07-18 10:12:20 -07003805 if (what & layer_state_t::eAcquireFenceChanged) {
3806 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3807 }
3808 if (what & layer_state_t::eDataspaceChanged) {
3809 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3810 }
3811 if (what & layer_state_t::eHdrMetadataChanged) {
3812 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3813 }
3814 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3815 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3816 }
3817 if (what & layer_state_t::eApiChanged) {
3818 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3819 }
3820 if (what & layer_state_t::eSidebandStreamChanged) {
3821 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3822 }
Robert Carr720e5062018-07-30 17:45:14 -07003823 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003824 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003825 layer->setInputInfo(s.inputInfo);
3826 flags |= eTraversalNeeded;
3827 } else {
3828 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3829 }
Robert Carr720e5062018-07-30 17:45:14 -07003830 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003831 if (what & layer_state_t::eMetadataChanged) {
3832 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3833 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003834 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3835 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3836 flags |= eTraversalNeeded;
3837 }
3838 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003839 if (what & layer_state_t::eShadowRadiusChanged) {
3840 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3841 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003842 if (what & layer_state_t::eFrameRateSelectionPriority) {
3843 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3844 flags |= eTraversalNeeded;
3845 }
3846 }
Steven Thomas3172e202020-01-06 19:25:30 -08003847 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003848 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3849 "SurfaceFlinger::setClientStateLocked") &&
3850 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3851 Layer::FrameRate::convertCompatibility(
3852 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003853 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003854 }
Steven Thomas3172e202020-01-06 19:25:30 -08003855 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003856 if (what & layer_state_t::eFixedTransformHintChanged) {
3857 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
3858 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
3859 }
3860 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003861 // This has to happen after we reparent children because when we reparent to null we remove
3862 // child layers from current state and remove its relative z. If the children are reparented in
3863 // the same transaction, then we have to make sure we reparent the children first so we do not
3864 // lose its relative z order.
3865 if (what & layer_state_t::eReparent) {
3866 bool hadParent = layer->hasParent();
3867 if (layer->reparent(s.parentHandleForChild)) {
3868 if (!hadParent) {
3869 mCurrentState.layersSortedByZ.remove(layer);
3870 }
3871 flags |= eTransactionNeeded | eTraversalNeeded;
3872 }
3873 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003874 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003875 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3876 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003877 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3878 }
3879 }
Marissa Wall78b72202019-03-15 14:58:34 -07003880 bool bufferChanged = what & layer_state_t::eBufferChanged;
3881 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3882 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003883 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003884 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003885 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3886 if (success) {
3887 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3888 success = ClientCache::getInstance()
3889 .registerErasedRecipient(s.cachedBuffer,
3890 wp<ClientCache::ErasedRecipient>(this));
3891 if (!success) {
3892 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3893 }
3894 }
Marissa Wall78b72202019-03-15 14:58:34 -07003895 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003896 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003897 } else if (bufferChanged) {
3898 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003899 }
Marissa Wall78b72202019-03-15 14:58:34 -07003900 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003901 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3902 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003903 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003904 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003905 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003906 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3907 // Do not put anything that updates layer state or modifies flags after
3908 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003909 return flags;
3910}
3911
chaviw273171b2018-12-26 11:46:30 -08003912uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3913 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003914 if (inputWindowCommands.syncInputWindows) {
3915 flags |= eTraversalNeeded;
3916 }
3917
Vishnu Nairec0ab382019-02-13 15:32:56 -08003918 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003919 return flags;
3920}
3921
chaviwfe94a222019-08-21 13:52:59 -07003922status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3923 sp<IBinder>* outHandle) {
3924 if (!mirrorFromHandle) {
3925 return NAME_NOT_FOUND;
3926 }
3927
3928 sp<Layer> mirrorLayer;
3929 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003930 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003931
3932 {
3933 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003934 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003935 if (!mirrorFrom) {
3936 return NAME_NOT_FOUND;
3937 }
3938
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003939 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3940 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003941 if (result != NO_ERROR) {
3942 return result;
3943 }
3944
3945 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3946 }
3947
Vishnu Nair6213bd92020-05-08 17:42:25 -07003948 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false,
3949 nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07003950}
3951
Marissa Wall2d814fb2019-04-09 18:52:57 +00003952status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3953 uint32_t h, PixelFormat format, uint32_t flags,
3954 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003955 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003956 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3957 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003958 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003959 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003960 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003961 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003962 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003963
Robert Carrc0df3122019-04-11 13:18:21 -07003964 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3965 "Expected only one of parentLayer or parentHandle to be non-null. "
3966 "Programmer error?");
3967
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003968 status_t result = NO_ERROR;
3969
3970 sp<Layer> layer;
3971
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003972 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003973
Evan Roskya1f1e152019-01-24 16:17:46 -08003974 bool primaryDisplayOnly = false;
3975
3976 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3977 // TODO b/64227542
3978 if (metadata.has(METADATA_WINDOW_TYPE)) {
3979 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3980 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003981 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003982 primaryDisplayOnly = true;
3983 }
3984 }
3985
Mathias Agopian3165cc22012-08-08 19:42:09 -07003986 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003987 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003988 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3989 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003990
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003991 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003992 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003993 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003994 std::move(metadata), handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003995 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003996 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003997 // check if buffer size is set for color layer.
3998 if (w > 0 || h > 0) {
3999 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4000 int(w), int(h));
4001 return BAD_VALUE;
4002 }
4003
Vishnu Nairfa247b12020-02-11 08:58:26 -08004004 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
4005 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004006 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004007 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004008 // check if buffer size is set for container layer.
4009 if (w > 0 || h > 0) {
4010 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4011 int(w), int(h));
4012 return BAD_VALUE;
4013 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004014 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
4015 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004016 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004017 default:
4018 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004019 break;
4020 }
4021
Dan Stoza7d89d062015-04-30 13:29:25 -07004022 if (result != NO_ERROR) {
4023 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004024 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004025
Evan Roskya1f1e152019-01-24 16:17:46 -08004026 if (primaryDisplayOnly) {
4027 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004028 }
4029
Robert Carrb89ea9d2018-12-10 13:01:14 -08004030 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004031 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004032 addToCurrentState, outTransformHint);
Dan Stoza7d89d062015-04-30 13:29:25 -07004033 if (result != NO_ERROR) {
4034 return result;
4035 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004036 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004037
4038 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004039 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004040}
4041
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004042std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
4043 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06004044
4045 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004046 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004047
Dan Stoza436ccf32018-06-21 12:10:12 -07004048 // Grab the state lock since we're accessing mCurrentState
4049 Mutex::Autolock lock(mStateLock);
4050
Cody Northropbc755282017-03-31 12:00:08 -06004051 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004052 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06004053 while (matchFound) {
4054 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08004055 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004056 if (layer->getName() == uniqueName) {
4057 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004058 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004059 }
4060 });
4061 }
4062
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004063 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004064 return uniqueName;
4065}
4066
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004067status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07004068 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004069 LayerMetadata metadata, PixelFormat& format,
4070 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004071 sp<IGraphicBufferProducer>* gbp,
4072 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004074 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004075 case PIXEL_FORMAT_TRANSPARENT:
4076 case PIXEL_FORMAT_TRANSLUCENT:
4077 format = PIXEL_FORMAT_RGBA_8888;
4078 break;
4079 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004080 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004081 break;
4082 }
4083
chaviwb4c6e582019-08-16 14:35:07 -07004084 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004085 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004086 args.textureName = getNewTexture();
4087 {
4088 // Grab the SF state lock during this since it's the only safe way to access
4089 // RenderEngine when creating a BufferLayerConsumer
4090 // TODO: Check if this lock is still needed here
4091 Mutex::Autolock lock(mStateLock);
4092 layer = getFactory().createBufferQueueLayer(args);
4093 }
4094
Marissa Wallfd668622018-05-10 10:21:13 -07004095 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004096 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004097 *handle = layer->getHandle();
4098 *gbp = layer->getProducer();
4099 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004100 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004101
Marissa Wallfd668622018-05-10 10:21:13 -07004102 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004103 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004104}
4105
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004106status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004107 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004108 LayerMetadata metadata, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004109 sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004110 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004111 args.textureName = getNewTexture();
4112 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07004113 *handle = layer->getHandle();
4114 *outLayer = layer;
4115
4116 return NO_ERROR;
4117}
4118
Vishnu Nairfa247b12020-02-11 08:58:26 -08004119status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4120 uint32_t h, uint32_t flags, LayerMetadata metadata,
4121 sp<IBinder>* handle, sp<Layer>* outLayer) {
4122 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004123 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004124 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004125 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004126}
4127
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004128status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004129 uint32_t w, uint32_t h, uint32_t flags,
4130 LayerMetadata metadata, sp<IBinder>* handle,
4131 sp<Layer>* outLayer) {
4132 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004133 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004134 *handle = (*outLayer)->getHandle();
4135 return NO_ERROR;
4136}
4137
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004138void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004139 mLayersPendingRemoval.add(layer);
4140 mLayersRemoved = true;
4141 setTransactionFlags(eTransactionNeeded);
4142}
4143
Robert Carr695d5282018-12-18 15:27:58 -08004144void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004145{
Robert Carr2e102c92018-10-23 12:11:15 -07004146 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004147 // If a layer has a parent, we allow it to out-live it's handle
4148 // with the idea that the parent holds a reference and will eventually
4149 // be cleaned up. However no one cleans up the top-level so we do so
4150 // here.
4151 if (layer->getParent() == nullptr) {
4152 mCurrentState.layersSortedByZ.remove(layer);
4153 }
4154 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004155
4156 auto it = mLayersByLocalBinderToken.begin();
4157 while (it != mLayersByLocalBinderToken.end()) {
4158 if (it->second == layer) {
4159 it = mLayersByLocalBinderToken.erase(it);
4160 } else {
4161 it++;
4162 }
4163 }
4164
Robert Carr695d5282018-12-18 15:27:58 -08004165 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004166}
4167
Mathias Agopianb60314a2012-04-10 22:09:54 -07004168// ---------------------------------------------------------------------------
4169
Andy McFadden13a082e2012-08-24 10:16:42 -07004170void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004171 const auto display = getDefaultDisplayDeviceLocked();
4172 if (!display) return;
4173
4174 const sp<IBinder> token = display->getDisplayToken().promote();
4175 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004176
Jesse Hall01e29052013-02-19 16:13:35 -08004177 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004178 Vector<ComposerState> state;
4179 Vector<DisplayState> displays;
4180 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004181 d.what = DisplayState::eDisplayProjectionChanged |
4182 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004183 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004184 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004185 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004186 d.frame.makeInvalid();
4187 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004188 d.width = 0;
4189 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004190 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004191 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4192 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004193
Peiyong Lin65248e02020-04-18 21:15:07 -07004194 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004195
Dominik Laskowski83b88212018-12-11 13:34:06 -08004196 const nsecs_t vsyncPeriod = getVsyncPeriod();
4197 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004198
Brian Andersond0010582017-03-07 13:20:31 -08004199 // Use phase of 0 since phase is not known.
4200 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004201 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004202 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004203}
4204
4205void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004206 // Async since we may be called from the main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004207 static_cast<void>(schedule([this]() MAIN_THREAD { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004208}
4209
Peiyong Lin65248e02020-04-18 21:15:07 -07004210void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004211 if (display->isVirtual()) {
4212 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004213 return;
4214 }
4215
Dominik Laskowski075d3172018-05-24 15:50:06 -07004216 const auto displayId = display->getId();
4217 LOG_ALWAYS_FATAL_IF(!displayId);
4218
Dominik Laskowski34157762018-10-31 13:07:19 -07004219 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004220
Peiyong Lin65248e02020-04-18 21:15:07 -07004221 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004222 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004223 return;
4224 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004225
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004226 display->setPowerMode(mode);
4227
Lloyd Pique4dccc412018-01-22 17:21:36 -08004228 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004229 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004230 }
4231
Peiyong Lin65248e02020-04-18 21:15:07 -07004232 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004233 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4234 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4235 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004236 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004237 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004238 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004239 mScheduler->onScreenAcquired(mAppConnectionHandle);
4240 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004241 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004242
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004243 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004244 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004245 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004246 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004247 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004248 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4249 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004250 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004251 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004252 mScheduler->disableHardwareVsync(true);
4253 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004254 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004255
Ady Abraham27c70212019-06-11 10:52:26 -07004256 // Make sure HWVsync is disabled before turning off the display
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004257 getHwComposer().setVsyncEnabled(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004258
Dominik Laskowski075d3172018-05-24 15:50:06 -07004259 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004260 mVisibleRegionsDirty = true;
4261 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004262 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004263 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004264 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004265 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004266 mScheduler->onScreenAcquired(mAppConnectionHandle);
4267 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004268 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004269 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004270 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004271 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004272 mScheduler->disableHardwareVsync(true);
4273 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004274 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004275 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004276 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004277 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004278 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004279 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004280
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004281 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004282 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004283 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004284 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004285 }
4286
Dominik Laskowski34157762018-10-31 13:07:19 -07004287 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004288}
4289
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004290void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004291 schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004292 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004293 if (!display) {
4294 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4295 displayToken.get());
4296 } else if (display->isVirtual()) {
4297 ALOGW("Attempt to set power mode %d for virtual display", mode);
4298 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004299 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004300 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004301 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004302}
4303
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004304status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004305 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004306
Mathias Agopianbd115332013-04-18 16:41:04 -07004307 IPCThreadState* ipc = IPCThreadState::self();
4308 const int pid = ipc->getCallingPid();
4309 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004310
Mathias Agopianbd115332013-04-18 16:41:04 -07004311 if ((uid != AID_SHELL) &&
4312 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004313 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4314 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004315 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004316 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004317 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004318 {"--dispsync"s,
4319 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004320 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004321 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4322 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4323 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4324 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4325 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4326 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004327 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004328 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4329 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004330
Dominik Laskowskic2867142019-01-21 11:33:38 -08004331 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004332
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004333 bool dumpLayers = true;
4334 {
4335 TimedLock lock(mStateLock, s2ns(1), __FUNCTION__);
4336 if (!lock.locked()) {
4337 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4338 strerror(-lock.status), lock.status);
4339 }
4340
4341 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4342 (it->second)(args, asProto, result);
4343 dumpLayers = false;
4344 } else if (!asProto) {
4345 dumpAllLocked(args, result);
4346 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004347 }
4348
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004349 if (dumpLayers) {
Dominik Laskowski46470112019-08-02 13:13:11 -07004350 const LayersProto layersProto = dumpProtoFromMainThread();
4351 if (asProto) {
4352 result.append(layersProto.SerializeAsString());
4353 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004354 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004355 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4356 result.append(LayerProtoParser::layerTreeToString(layerTree));
4357 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004358 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004359 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004360 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004361 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004362 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004363 return NO_ERROR;
4364}
4365
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004366status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4367 if (asProto && mTracing.isEnabled()) {
4368 mTracing.writeToFileAsync();
4369 }
4370
4371 return doDump(fd, DumpArgs(), asProto);
4372}
4373
Dominik Laskowskic2867142019-01-21 11:33:38 -08004374void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004375 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004376 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004377}
4378
Dominik Laskowskic2867142019-01-21 11:33:38 -08004379void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004380 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004381
Dominik Laskowskic2867142019-01-21 11:33:38 -08004382 if (args.size() > 1) {
4383 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004384 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004385 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004386 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004387 }
Robert Carr2047fae2016-11-28 14:09:09 -08004388 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004389 } else {
4390 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004391 }
4392}
4393
Dominik Laskowskic2867142019-01-21 11:33:38 -08004394void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004395 const bool clearAll = args.size() < 2;
4396 const auto name = clearAll ? String8() : String8(args[1]);
4397
Edgar Arriaga844fa672020-01-16 14:21:42 -08004398 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004399 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004400 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004401 }
Robert Carr2047fae2016-11-28 14:09:09 -08004402 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004403
Svetoslavd85084b2014-03-20 10:28:31 -07004404 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004405}
4406
Dominik Laskowskic2867142019-01-21 11:33:38 -08004407void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4408 mTimeStats->parseArgs(asProto, args, result);
4409}
4410
Jamie Gennis6547ff42013-07-16 20:12:42 -07004411// This should only be called from the main thread. Otherwise it would need
4412// the lock and should use mCurrentState rather than mDrawingState.
4413void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004414 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004415 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004416 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004417
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004418 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004419}
4420
Yiwei Zhang5434a782018-12-05 18:06:32 -08004421void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004422 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004423
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004424 if (isLayerTripleBufferingDisabled())
4425 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004426
Yiwei Zhang5434a782018-12-05 18:06:32 -08004427 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4428 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4429 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4430 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4431 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4432 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004433 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004434}
4435
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004436void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004437 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004438
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004439 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004440 result.append("\n");
4441
Ady Abraham9e16a482019-12-03 17:19:41 -08004442 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004443 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004444 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004445 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004446
Steven Thomasd4071902020-03-24 16:02:53 -07004447 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004448 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004449 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004450 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4451 policy.defaultConfig.value(), policy.primaryRange.min, policy.primaryRange.max,
4452 policy.appRequestRange.min, policy.appRequestRange.max);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004453 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4454 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004455 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4456 if (currentPolicy != policy) {
4457 StringAppendF(&result,
4458 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004459 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4460 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
4461 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
4462 currentPolicy.appRequestRange.max);
Ady Abraham07e54702020-04-16 15:05:37 -07004463 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004464
Ana Krulecc2870422019-01-29 19:00:58 -08004465 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004466 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004467}
4468
Yiwei Zhang5434a782018-12-05 18:06:32 -08004469void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4470 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004471 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4472 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004473 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004474 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004476 }
David Sodman4a36e932017-11-07 14:29:47 -08004477 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004478 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004479 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004480 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4481 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004482}
4483
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004484void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4485 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004486 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4487 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004488 for (const auto& segment : history) {
4489 if (!segment.usedThirdBuffer) {
4490 stats.twoBufferTime += segment.totalTime;
4491 }
4492 if (segment.occupancyAverage < 1.0f) {
4493 stats.doubleBufferedTime += segment.totalTime;
4494 } else if (segment.occupancyAverage < 2.0f) {
4495 stats.tripleBufferedTime += segment.totalTime;
4496 }
4497 ++stats.numSegments;
4498 stats.totalTime += segment.totalTime;
4499 }
4500}
4501
Yiwei Zhang5434a782018-12-05 18:06:32 -08004502void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4503 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004504
4505 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4506 const size_t count = currentLayers.size();
4507 for (size_t i=0 ; i<count ; i++) {
4508 currentLayers[i]->dumpFrameEvents(result);
4509 }
4510}
4511
Yiwei Zhang5434a782018-12-05 18:06:32 -08004512void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004513 result.append("Buffering stats:\n");
4514 result.append(" [Layer name] <Active time> <Two buffer> "
4515 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004516 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004517 typedef std::tuple<std::string, float, float, float> BufferTuple;
4518 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004519 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004520 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004521 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004522 if (stats.numSegments == 0) {
4523 continue;
4524 }
4525 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4526 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4527 stats.totalTime;
4528 float doubleBufferRatio = static_cast<float>(
4529 stats.doubleBufferedTime) / stats.totalTime;
4530 float tripleBufferRatio = static_cast<float>(
4531 stats.tripleBufferedTime) / stats.totalTime;
4532 sorted.insert({activeTime, {name, twoBufferRatio,
4533 doubleBufferRatio, tripleBufferRatio}});
4534 }
4535 for (const auto& sortedPair : sorted) {
4536 float activeTime = sortedPair.first;
4537 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004538 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4539 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004540 }
4541 result.append("\n");
4542}
4543
Yiwei Zhang5434a782018-12-05 18:06:32 -08004544void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004545 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004546 const auto displayId = display->getId();
4547 if (!displayId) {
4548 continue;
4549 }
4550 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004551 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004552 continue;
4553 }
4554
Yiwei Zhang5434a782018-12-05 18:06:32 -08004555 StringAppendF(&result,
4556 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4557 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004558 uint8_t port;
4559 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004560 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004561 result.append("no identification data\n");
4562 continue;
4563 }
4564
4565 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004566 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004567 continue;
4568 }
4569
4570 const auto edid = parseEdid(data);
4571 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004572 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004573 continue;
4574 }
4575
Yiwei Zhang5434a782018-12-05 18:06:32 -08004576 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004577 result.append(edid->displayName.data(), edid->displayName.length());
4578 result.append("\"\n");
4579 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004580}
4581
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004582void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4583 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004584 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004585 uint8_t port;
4586 DisplayIdentificationData data;
4587
4588 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4589 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4590 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4591 }
4592}
4593
Yiwei Zhang5434a782018-12-05 18:06:32 -08004594void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004595 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004596 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4597 StringAppendF(&result, "DisplayColorSetting: %s\n",
4598 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004599
4600 // TODO: print out if wide-color mode is active or not
4601
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004602 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004603 const auto displayId = display->getId();
4604 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004605 continue;
4606 }
4607
Yiwei Zhang5434a782018-12-05 18:06:32 -08004608 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004609 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004610 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004611 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004612 }
4613
Lloyd Pique32cbe282018-10-19 13:09:22 -07004614 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004615 StringAppendF(&result, " Current color mode: %s (%d)\n",
4616 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004617 }
4618 result.append("\n");
4619}
4620
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004621LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4622 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004623 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004624
chaviw1d044282017-09-27 12:19:28 -07004625 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004626 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004627 layer->writeToProto(layersProto, traceFlags, display.get());
chaviw08f3cb22020-01-13 13:17:21 -08004628 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004629
chaviw1d044282017-09-27 12:19:28 -07004630 return layersProto;
4631}
4632
Alec Mouri6b9e9912020-01-21 10:50:24 -08004633void SurfaceFlinger::dumpHwc(std::string& result) const {
4634 getHwComposer().dump(result);
4635}
4636
Vishnu Nair0f085c62019-08-30 08:49:12 -07004637void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4638 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4639 // it.
4640 LayerProto* rootProto = layersProto.add_layers();
4641 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4642 rootProto->set_id(offscreenRootLayerId);
4643 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004644 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004645
4646 for (Layer* offscreenLayer : mOffscreenLayers) {
4647 // Add layer as child of the fake root
4648 rootProto->add_children(offscreenLayer->sequence);
4649
4650 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004651 LayerProto* layerProto =
4652 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004653 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004654 }
4655}
4656
Vishnu Nair8406fd72019-07-30 11:29:31 -07004657LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004658 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004659}
4660
Vishnu Nair0f085c62019-08-30 08:49:12 -07004661void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4662 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004663 result.append(schedule([this] {
4664 std::string result;
4665 for (Layer* offscreenLayer : mOffscreenLayers) {
4666 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4667 [&](Layer* layer) {
4668 layer->dumpCallingUidPid(result);
4669 });
4670 }
4671 return result;
4672 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004673}
4674
Dominik Laskowskic2867142019-01-21 11:33:38 -08004675void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4676 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004677 Colorizer colorizer(colorize);
4678
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004679 // figure out if we're stuck somewhere
4680 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004681 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004682 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4683
4684 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004685 * Dump library configuration.
4686 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004687
4688 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004689 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004690 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004691 appendSfConfigString(result);
4692 appendUiConfigString(result);
4693 appendGuiConfigString(result);
4694 result.append("\n");
4695
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004696 result.append("\nDisplay identification data:\n");
4697 dumpDisplayIdentificationData(result);
4698
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004699 result.append("\nWide-Color information:\n");
4700 dumpWideColorInfo(result);
4701
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004702 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004703 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004704 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004705 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004706 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004707
Andy McFadden41d67d72014-04-25 16:58:34 -07004708 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004709 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004710 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004711 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004712 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004713
Dan Stozab90cf072015-03-05 11:05:59 -08004714 dumpStaticScreenStats(result);
4715 result.append("\n");
4716
Alec Mouri40189b02019-03-05 15:07:54 -08004717 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4718 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4719 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004720
Dan Stozae77c7662016-05-13 11:37:28 -07004721 dumpBufferingStats(result);
4722
Andy McFadden4803b742012-09-24 19:07:20 -07004723 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004724 * Dump the visible layer list
4725 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004726 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004727 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004728 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4729 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004730 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004731
Chia-I Wu2f884132018-09-13 15:17:58 -07004732 {
Lloyd Pique207def92019-02-28 16:09:52 -08004733 StringAppendF(&result, "Composition layers\n");
4734 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004735 auto* compositionState = layer->getCompositionState();
4736 if (!compositionState) return;
4737
4738 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4739 layer->getDebugName() ? layer->getDebugName()
4740 : "<unknown>");
4741 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004742 });
4743 }
4744
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004745 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004746 * Dump Display state
4747 */
4748
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004749 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004750 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004751 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004752 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004753 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004754 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004755 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004756
4757 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004758 * Dump CompositionEngine state
4759 */
4760
4761 mCompositionEngine->dump(result);
4762
4763 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004764 * Dump SurfaceFlinger global state
4765 */
4766
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004767 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004768 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004769 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004770
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004771 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004772
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004773 DebugEGLImageTracker::getInstance()->dump(result);
4774
Dominik Laskowski075d3172018-05-24 15:50:06 -07004775 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004776 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4777 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004778 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4779 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004780 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004781 StringAppendF(&result,
4782 " transaction-flags : %08x\n"
4783 " gpu_to_cpu_unsupported : %d\n",
4784 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004785
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004786 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004787 displayId && getHwComposer().isConnected(*displayId)) {
4788 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004789 StringAppendF(&result,
4790 " refresh-rate : %f fps\n"
4791 " x-dpi : %f\n"
4792 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004793 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4794 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004795 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004796
Yiwei Zhang5434a782018-12-05 18:06:32 -08004797 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004798
Dan Stozae22aec72016-08-01 13:20:59 -07004799 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004800 * Tracing state
4801 */
4802 mTracing.dump(result);
4803 result.append("\n");
4804
4805 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004806 * HWC layer minidump
4807 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004808 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004809 const auto displayId = display->getId();
4810 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004811 continue;
4812 }
4813
Yiwei Zhang5434a782018-12-05 18:06:32 -08004814 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004815 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004816
4817 const DisplayDevice& ref = *display;
4818 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07004819 result.append("\n");
4820 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004821
4822 /*
4823 * Dump HWComposer state
4824 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004825 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004826 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004827 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004828 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004829 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004830 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004831
4832 /*
4833 * Dump gralloc state
4834 */
4835 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4836 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004837
4838 /*
4839 * Dump VrFlinger state if in use.
4840 */
4841 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4842 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004843 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004844 result.append("\n");
4845 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004846
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004847 result.append(mTimeStats->miniDump());
4848 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004849}
4850
Chia-I Wu28f320b2018-05-03 11:02:56 -07004851void SurfaceFlinger::updateColorMatrixLocked() {
4852 mat4 colorMatrix;
4853 if (mGlobalSaturationFactor != 1.0f) {
4854 // Rec.709 luma coefficients
4855 float3 luminance{0.213f, 0.715f, 0.072f};
4856 luminance *= 1.0f - mGlobalSaturationFactor;
4857 mat4 saturationMatrix = mat4(
4858 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4859 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4860 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4861 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4862 );
4863 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4864 } else {
4865 colorMatrix = mClientColorMatrix * mDaltonizer();
4866 }
4867
4868 if (mCurrentState.colorMatrix != colorMatrix) {
4869 mCurrentState.colorMatrix = colorMatrix;
4870 mCurrentState.colorMatrixChanged = true;
4871 setTransactionFlags(eTransactionNeeded);
4872 }
4873}
4874
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004875status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004876#pragma clang diagnostic push
4877#pragma clang diagnostic error "-Wswitch-enum"
4878 switch (static_cast<ISurfaceComposerTag>(code)) {
4879 // These methods should at minimum make sure that the client requested
4880 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004881 case BOOT_FINISHED:
4882 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004883 case CREATE_DISPLAY:
4884 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004885 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004886 case GET_ANIMATION_FRAME_STATS:
4887 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004888 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004889 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004890 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004891 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4892 case SET_AUTO_LOW_LATENCY_MODE:
4893 case GET_GAME_CONTENT_TYPE_SUPPORT:
4894 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004895 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004896 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004897 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004898 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004899 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004900 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004901 case SET_GLOBAL_SHADOW_SETTINGS:
4902 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4903 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4904 // necessary permission dynamically. Don't use the permission cache for this check.
4905 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4906 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004907 IPCThreadState* ipc = IPCThreadState::self();
4908 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4909 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004910 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004911 }
Robert Carr1db73f62016-12-21 12:58:51 -08004912 return OK;
4913 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004914 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004915 IPCThreadState* ipc = IPCThreadState::self();
4916 const int pid = ipc->getCallingPid();
4917 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004918 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4919 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004920 return PERMISSION_DENIED;
4921 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004922 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004923 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004924 // Used by apps to hook Choreographer to SurfaceFlinger.
4925 case CREATE_DISPLAY_EVENT_CONNECTION:
4926 // The following calls are currently used by clients that do not
4927 // request necessary permissions. However, they do not expose any secret
4928 // information, so it is OK to pass them.
4929 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004930 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004931 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004932 case GET_PHYSICAL_DISPLAY_IDS:
4933 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004934 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004935 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004936 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004937 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004938 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004939 case GET_DISPLAY_STATS:
4940 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4941 // Calling setTransactionState is safe, because you need to have been
4942 // granted a reference to Client* and Handle* to do anything with it.
4943 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004944 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004945 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004946 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004947 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004948 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004949 // setFrameRate() is deliberately available for apps to call without any
4950 // special permissions.
4951 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004952 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4953 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004954 return OK;
4955 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004956 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004957 case CAPTURE_SCREEN:
4958 case ADD_REGION_SAMPLING_LISTENER:
4959 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004960 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004961 IPCThreadState* ipc = IPCThreadState::self();
4962 const int pid = ipc->getCallingPid();
4963 const int uid = ipc->getCallingUid();
4964 if ((uid != AID_GRAPHICS) &&
4965 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4966 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4967 return PERMISSION_DENIED;
4968 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004969 return OK;
4970 }
chaviw93df2ea2019-04-30 16:45:12 -07004971 case CAPTURE_SCREEN_BY_ID: {
4972 IPCThreadState* ipc = IPCThreadState::self();
4973 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004974 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004975 return OK;
4976 }
4977 return PERMISSION_DENIED;
4978 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004979 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004980
4981 // These codes are used for the IBinder protocol to either interrogate the recipient
4982 // side of the transaction for its canonical interface descriptor or to dump its state.
4983 // We let them pass by default.
4984 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4985 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4986 code == IBinder::SYSPROPS_TRANSACTION) {
4987 return OK;
4988 }
Ady Abraham07e54702020-04-16 15:05:37 -07004989 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004990 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004991 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004992 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4993 return OK;
4994 }
4995 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4996 return PERMISSION_DENIED;
4997#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004998}
4999
Ana Krulec13be8ad2018-08-21 02:43:56 +00005000status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5001 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005002 status_t credentialCheck = CheckTransactCodeCredentials(code);
5003 if (credentialCheck != OK) {
5004 return credentialCheck;
5005 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005006
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005007 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5008 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005009 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005010 IPCThreadState* ipc = IPCThreadState::self();
5011 const int uid = ipc->getCallingUid();
5012 if (CC_UNLIKELY(uid != AID_SYSTEM
5013 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005014 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005015 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005016 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005017 return PERMISSION_DENIED;
5018 }
5019 int n;
5020 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005021 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005022 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005023 return NO_ERROR;
5024 case 1002: // SHOW_UPDATES
5025 n = data.readInt32();
5026 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005027 invalidateHwcGeometry();
5028 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005029 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005030 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005031 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005032 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005033 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005034 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005035 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005036 setTransactionFlags(
5037 eTransactionNeeded|
5038 eDisplayTransactionNeeded|
5039 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005040 return NO_ERROR;
5041 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005042 case 1006:{ // send empty update
5043 signalRefresh();
5044 return NO_ERROR;
5045 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005046 case 1008: // toggle use of hw composer
5047 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005048 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005049 invalidateHwcGeometry();
5050 repaintEverything();
5051 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005052 case 1009: // toggle use of transform hint
5053 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005054 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005055 invalidateHwcGeometry();
5056 repaintEverything();
5057 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005058 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005059 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005060 reply->writeInt32(0);
5061 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005062 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005063 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005064 return NO_ERROR;
5065 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005066 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005067 if (!display) {
5068 return NAME_NOT_FOUND;
5069 }
5070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005071 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005072 return NO_ERROR;
5073 }
5074 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005075 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005076 // daltonize
5077 n = data.readInt32();
5078 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005079 case 1:
5080 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5081 break;
5082 case 2:
5083 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5084 break;
5085 case 3:
5086 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5087 break;
5088 default:
5089 mDaltonizer.setType(ColorBlindnessType::None);
5090 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005091 }
5092 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005093 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005094 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005095 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005096 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005097
5098 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005099 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005100 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005101 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005102 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005103 // apply a color matrix
5104 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005105 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005106 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005107 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005108 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005109 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005110 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005111 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005112 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005113 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005114 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005115
5116 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5117 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005118 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005119 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5120 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5121 }
5122
Chia-I Wu28f320b2018-05-03 11:02:56 -07005123 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005124 return NO_ERROR;
5125 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005126 case 1016: { // Unused.
5127 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005128 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005129 case 1017: {
5130 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005131 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005132 return NO_ERROR;
5133 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005134 case 1018: { // Modify Choreographer's phase offset
5135 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005136 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005137 return NO_ERROR;
5138 }
5139 case 1019: { // Modify SurfaceFlinger's phase offset
5140 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005141 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005142 return NO_ERROR;
5143 }
Irvel468051e2016-06-13 16:44:44 -07005144 case 1020: { // Layer updates interceptor
5145 n = data.readInt32();
5146 if (n) {
5147 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005148 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005149 }
5150 else{
5151 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005152 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005153 }
5154 return NO_ERROR;
5155 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005156 case 1021: { // Disable HWC virtual displays
5157 n = data.readInt32();
5158 mUseHwcVirtualDisplays = !n;
5159 return NO_ERROR;
5160 }
Romain Guy0147a172017-06-01 13:53:56 -07005161 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005162 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005163 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005164
Chia-I Wu28f320b2018-05-03 11:02:56 -07005165 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005166 return NO_ERROR;
5167 }
Romain Guy54f154a2017-10-24 21:40:32 +01005168 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005169 int32_t colorMode;
5170
Chia-I Wu0d711262018-05-21 15:19:35 -07005171 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005172 if (data.readInt32(&colorMode) == NO_ERROR) {
5173 mForceColorMode = static_cast<ColorMode>(colorMode);
5174 }
Romain Guy54f154a2017-10-24 21:40:32 +01005175 invalidateHwcGeometry();
5176 repaintEverything();
5177 return NO_ERROR;
5178 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005179 // Deprecate, use 1030 to check whether the device is color managed.
5180 case 1024: {
5181 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005182 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005183 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005184 n = data.readInt32();
5185 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005186 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005187 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005188 reply->writeInt32(NO_ERROR);
5189 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005190 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005191 mTracingEnabledChanged = mTracing.disable();
5192 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005193 reply->writeInt32(mTracing.writeToFile());
5194 } else {
5195 reply->writeInt32(NO_ERROR);
5196 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005197 }
5198 return NO_ERROR;
5199 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005200 case 1026: { // Get layer tracing status
5201 reply->writeBool(mTracing.isEnabled());
5202 return NO_ERROR;
5203 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005204 // Is a DisplayColorSetting supported?
5205 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005206 const auto display = getDefaultDisplayDevice();
5207 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005208 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005209 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005210
5211 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5212 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005213 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005214 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005215 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005216 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005217 reply->writeBool(true);
5218 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005219 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005220 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005221 break;
5222 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005223 reply->writeBool(
5224 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005225 break;
5226 }
5227 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005228 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005229 // Is VrFlinger active?
5230 case 1028: {
5231 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005232 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005233 return NO_ERROR;
5234 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005235 // Set buffer size for SF tracing (value in KB)
5236 case 1029: {
5237 n = data.readInt32();
5238 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5239 ALOGW("Invalid buffer size: %d KB", n);
5240 reply->writeInt32(BAD_VALUE);
5241 return BAD_VALUE;
5242 }
5243
5244 ALOGD("Updating trace buffer to %d KB", n);
5245 mTracing.setBufferSize(n * 1024);
5246 reply->writeInt32(NO_ERROR);
5247 return NO_ERROR;
5248 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005249 // Is device color managed?
5250 case 1030: {
5251 reply->writeBool(useColorManagement);
5252 return NO_ERROR;
5253 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005254 // Override default composition data space
5255 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5256 // && adb shell stop zygote && adb shell start zygote
5257 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5258 // adb shell stop zygote && adb shell start zygote
5259 case 1031: {
5260 Mutex::Autolock _l(mStateLock);
5261 n = data.readInt32();
5262 if (n) {
5263 n = data.readInt32();
5264 if (n) {
5265 Dataspace dataspace = static_cast<Dataspace>(n);
5266 if (!validateCompositionDataspace(dataspace)) {
5267 return BAD_VALUE;
5268 }
5269 mDefaultCompositionDataspace = dataspace;
5270 }
5271 n = data.readInt32();
5272 if (n) {
5273 Dataspace dataspace = static_cast<Dataspace>(n);
5274 if (!validateCompositionDataspace(dataspace)) {
5275 return BAD_VALUE;
5276 }
5277 mWideColorGamutCompositionDataspace = dataspace;
5278 }
5279 } else {
5280 // restore composition data space.
5281 mDefaultCompositionDataspace = defaultCompositionDataspace;
5282 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5283 }
5284 return NO_ERROR;
5285 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005286 // Set trace flags
5287 case 1033: {
5288 n = data.readUint32();
5289 ALOGD("Updating trace flags to 0x%x", n);
5290 mTracing.setTraceFlags(n);
5291 reply->writeInt32(NO_ERROR);
5292 return NO_ERROR;
5293 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005294 case 1034: {
Dominik Laskowski20134642020-04-20 22:36:44 -07005295 switch (n = data.readInt32()) {
5296 case 0:
5297 case 1:
5298 enableRefreshRateOverlay(static_cast<bool>(n));
5299 break;
5300 default: {
5301 Mutex::Autolock lock(mStateLock);
5302 reply->writeBool(mRefreshRateOverlay != nullptr);
5303 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005304 }
5305 return NO_ERROR;
5306 }
Ady Abraham34392f72019-04-10 11:29:27 -07005307 case 1035: {
5308 n = data.readInt32();
5309 mDebugDisplayConfigSetByBackdoor = false;
5310 if (n >= 0) {
5311 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005312 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005313 if (result != NO_ERROR) {
5314 return result;
5315 }
5316 mDebugDisplayConfigSetByBackdoor = true;
5317 }
5318 return NO_ERROR;
5319 }
Ady Abraham07e54702020-04-16 15:05:37 -07005320 case 1036: {
5321 if (data.readInt32() > 0) {
5322 status_t result =
5323 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5324 if (result != NO_ERROR) {
5325 return result;
5326 }
5327 } else {
5328 mDebugFrameRateFlexibilityToken = nullptr;
5329 }
5330 return NO_ERROR;
5331 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005332 }
5333 }
5334 return err;
5335}
5336
Steven Thomas6d8110b2017-08-31 18:24:21 -07005337void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005338 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005339 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005340}
5341
Ana Krulec7d1d6832018-12-27 11:10:09 -08005342void SurfaceFlinger::repaintEverythingForHWC() {
5343 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005344 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005345 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005346}
5347
Ady Abrahama09852a2020-02-20 14:23:42 -08005348void SurfaceFlinger::kernelTimerChanged(bool expired) {
5349 static bool updateOverlay =
5350 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005351 if (!updateOverlay) return;
5352 if (Mutex::Autolock lock(mStateLock); !mRefreshRateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005353
5354 // Update the overlay on the main thread to avoid race conditions with
5355 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowski20134642020-04-20 22:36:44 -07005356 static_cast<void>(schedule([=] {
5357 const auto desiredActiveConfig = getDesiredActiveConfig();
5358 const auto& current = desiredActiveConfig
5359 ? mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId)
5360 : mRefreshRateConfigs->getCurrentRefreshRate();
5361 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5362
5363 if (current != min) {
Ana Krulecb9afd792020-06-11 13:16:15 -07005364 const bool timerExpired = mKernelIdleTimerEnabled && expired;
Ady Abrahama09852a2020-02-20 14:23:42 -08005365
Dominik Laskowski20134642020-04-20 22:36:44 -07005366 if (Mutex::Autolock lock(mStateLock); mRefreshRateOverlay) {
Ady Abrahama09852a2020-02-20 14:23:42 -08005367 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
Ady Abrahama09852a2020-02-20 14:23:42 -08005368 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005369 mEventQueue->invalidate();
Ady Abrahama09852a2020-02-20 14:23:42 -08005370 }
5371 }));
5372}
5373
Ana Krulecb9afd792020-06-11 13:16:15 -07005374void SurfaceFlinger::toggleKernelIdleTimer() {
5375 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
5376
5377 // If the support for kernel idle timer is disabled in SF code, don't do anything.
5378 if (!mSupportKernelIdleTimer) {
5379 return;
5380 }
5381 const KernelIdleTimerAction action = mRefreshRateConfigs->getIdleTimerAction();
5382
5383 switch (action) {
5384 case KernelIdleTimerAction::TurnOff:
5385 if (mKernelIdleTimerEnabled) {
5386 ATRACE_INT("KernelIdleTimer", 0);
5387 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "false");
5388 mKernelIdleTimerEnabled = false;
5389 }
5390 break;
5391 case KernelIdleTimerAction::TurnOn:
5392 if (!mKernelIdleTimerEnabled) {
5393 ATRACE_INT("KernelIdleTimer", 1);
5394 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "true");
5395 mKernelIdleTimerEnabled = true;
5396 }
5397 break;
5398 case KernelIdleTimerAction::NoChange:
5399 break;
5400 }
5401}
5402
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005403// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5404class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005405public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005406 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5407 ~WindowDisconnector() {
5408 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005409 }
5410
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005411private:
5412 ANativeWindow* mWindow;
5413 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005414};
5415
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005416status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005417 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005418 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5419 const Rect& sourceCrop, uint32_t reqWidth,
5420 uint32_t reqHeight, bool useIdentityTransform,
5421 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005422 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005423
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005424 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005425
Dominik Laskowski718f9602019-11-09 20:01:35 -08005426 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5427 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5428 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5429 renderAreaRotation = ui::Transform::ROT_0;
5430 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005431
Chia-I Wu20261cb2018-08-23 12:55:44 -07005432 sp<DisplayDevice> display;
5433 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005434 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005435
Chia-I Wu20261cb2018-08-23 12:55:44 -07005436 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005437 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005438
Chia-I Wucb023152018-08-28 12:57:23 -07005439 // set the requested width/height to the logical display viewport size
5440 // by default
5441 if (reqWidth == 0 || reqHeight == 0) {
5442 reqWidth = uint32_t(display->getViewport().width());
5443 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005444 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005445 }
5446
Peiyong Lin0e003c92018-09-17 11:09:51 -07005447 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005448 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005449 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5450 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005451 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005452 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005453}
5454
chaviw93df2ea2019-04-30 16:45:12 -07005455static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5456 switch (colorMode) {
5457 case ColorMode::DISPLAY_P3:
5458 case ColorMode::BT2100_PQ:
5459 case ColorMode::BT2100_HLG:
5460 case ColorMode::DISPLAY_BT2020:
5461 return Dataspace::DISPLAY_P3;
5462 default:
5463 return Dataspace::V0_SRGB;
5464 }
5465}
5466
Martin Liu4a322352020-03-24 21:30:38 +08005467status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5468 static constexpr int kFifoPriority = 2;
5469 static constexpr int kOtherPriority = 0;
5470
5471 struct sched_param param = {0};
5472 int sched_policy;
5473 if (enabled) {
5474 sched_policy = SCHED_FIFO;
5475 param.sched_priority = kFifoPriority;
5476 } else {
5477 sched_policy = SCHED_OTHER;
5478 param.sched_priority = kOtherPriority;
5479 }
5480
5481 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5482 return -errno;
5483 }
5484 return NO_ERROR;
5485}
5486
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005487sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005488 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5489 if (displayToken) {
5490 return getDisplayDeviceLocked(displayToken);
5491 }
5492 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5493 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005494 return getDisplayByLayerStack(displayOrLayerStack);
5495}
5496
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005497sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005498 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005499 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005500 return display;
5501 }
5502 }
5503 return nullptr;
5504}
5505
5506status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5507 sp<GraphicBuffer>* outBuffer) {
5508 sp<DisplayDevice> display;
5509 uint32_t width;
5510 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005511 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005512 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005513 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005514 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5515 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005516 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005517 }
5518
5519 width = uint32_t(display->getViewport().width());
5520 height = uint32_t(display->getViewport().height());
5521
Dominik Laskowski718f9602019-11-09 20:01:35 -08005522 const auto orientation = display->getOrientation();
5523 captureOrientation = ui::Transform::toRotationFlags(orientation);
5524
5525 switch (captureOrientation) {
5526 case ui::Transform::ROT_90:
5527 captureOrientation = ui::Transform::ROT_270;
5528 break;
5529
5530 case ui::Transform::ROT_270:
5531 captureOrientation = ui::Transform::ROT_90;
5532 break;
5533
5534 case ui::Transform::ROT_INVALID:
5535 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5536 captureOrientation = ui::Transform::ROT_0;
5537 break;
5538
5539 default:
5540 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005541 }
chaviw93df2ea2019-04-30 16:45:12 -07005542 *outDataspace =
5543 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5544 }
5545
5546 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5547 false /* captureSecureLayers */);
5548
5549 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5550 std::placeholders::_1);
5551 bool ignored = false;
5552 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5553 false /* useIdentityTransform */,
5554 ignored /* outCapturedSecureLayers */);
5555}
5556
Robert Carr866455f2019-04-02 16:28:26 -07005557status_t SurfaceFlinger::captureLayers(
5558 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5559 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5560 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5561 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005562 ATRACE_CALL();
5563
5564 class LayerRenderArea : public RenderArea {
5565 public:
Robert Carr578038f2018-03-09 12:25:24 -08005566 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005567 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005568 bool childrenOnly, const Rect& displayViewport)
5569 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005570 mLayer(layer),
5571 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005572 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005573 mFlinger(flinger),
5574 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005575 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005576 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005577 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005578 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005579 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005580 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005581 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005582 }
chaviwa76b2712017-09-20 12:02:26 -07005583 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005584 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005585 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005586 Rect getSourceCrop() const override {
5587 if (mCrop.isEmpty()) {
5588 return getBounds();
5589 } else {
5590 return mCrop;
5591 }
5592 }
Robert Carr578038f2018-03-09 12:25:24 -08005593 class ReparentForDrawing {
5594 public:
5595 const sp<Layer>& oldParent;
5596 const sp<Layer>& newParent;
5597
Vishnu Nair4351ad52019-02-11 14:13:02 -08005598 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5599 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005600 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005601 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005602 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5603 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005604 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005605 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005606 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005607 };
5608
5609 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005610 const Rect sourceCrop = getSourceCrop();
5611 // no need to check rotation because there is none
5612 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5613 sourceCrop.height() != getReqHeight();
5614
Robert Carr578038f2018-03-09 12:25:24 -08005615 if (!mChildrenOnly) {
5616 mTransform = mLayer->getTransform().inverse();
5617 drawLayers();
5618 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005619 uint32_t w = static_cast<uint32_t>(getWidth());
5620 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005621 // In the "childrenOnly" case we reparent the children to a screenshot
5622 // layer which has no properties set and which does not draw.
5623 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005624 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5625 "Screenshot Parent"s, w, h, 0,
5626 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005627
Vishnu Nair4351ad52019-02-11 14:13:02 -08005628 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005629 drawLayers();
5630 }
5631 }
chaviwa76b2712017-09-20 12:02:26 -07005632
chaviwa76b2712017-09-20 12:02:26 -07005633 private:
chaviw7206d492017-11-10 16:16:12 -08005634 const sp<Layer> mLayer;
5635 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005636
Peiyong Linefefaac2018-08-17 12:27:51 -07005637 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005638 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005639
5640 SurfaceFlinger* mFlinger;
5641 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005642 };
5643
Robert Carrc0df3122019-04-11 13:18:21 -07005644 int reqWidth = 0;
5645 int reqHeight = 0;
5646 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005647 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005648 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005649 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005650 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005651 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005652
Alec Mouri9a02eda2020-04-21 17:39:34 -07005653 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005654 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5655 ALOGE("captureLayers called with an invalid or removed parent");
5656 return NAME_NOT_FOUND;
5657 }
5658
5659 const int uid = IPCThreadState::self()->getCallingUid();
5660 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5661 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5662 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5663 return PERMISSION_DENIED;
5664 }
5665
Vishnu Nairefc42e22019-12-03 17:36:12 -08005666 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005667 if (sourceCrop.width() <= 0) {
5668 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005669 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005670 }
5671
5672 if (sourceCrop.height() <= 0) {
5673 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005674 crop.bottom = parentSourceBounds.getHeight();
5675 }
5676
5677 if (crop.isEmpty() || frameScale <= 0.0f) {
5678 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5679 // crop was not specified, or an invalid frame scale was provided.
5680 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005681 }
5682 reqWidth = crop.width() * frameScale;
5683 reqHeight = crop.height() * frameScale;
5684
5685 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005686 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005687 if (excludeLayer != nullptr) {
5688 excludeLayers.emplace(excludeLayer);
5689 } else {
5690 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5691 return NAME_NOT_FOUND;
5692 }
5693 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005694
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005695 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005696 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005697 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005698 }
5699
5700 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005701 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005702
Chia-I Wu20261cb2018-08-23 12:55:44 -07005703 // really small crop or frameScale
5704 if (reqWidth <= 0) {
5705 reqWidth = 1;
5706 }
5707 if (reqHeight <= 0) {
5708 reqHeight = 1;
5709 }
5710
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005711 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5712 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005713 auto traverseLayers = [parent, childrenOnly,
5714 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005715 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5716 if (!layer->isVisible()) {
5717 return;
Robert Carr578038f2018-03-09 12:25:24 -08005718 } else if (childrenOnly && layer == parent.get()) {
5719 return;
chaviwa76b2712017-09-20 12:02:26 -07005720 }
Robert Carr866455f2019-04-02 16:28:26 -07005721
5722 sp<Layer> p = layer;
5723 while (p != nullptr) {
5724 if (excludeLayers.count(p) != 0) {
5725 return;
5726 }
5727 p = p->getParent();
5728 }
5729
chaviwa76b2712017-09-20 12:02:26 -07005730 visitor(layer);
5731 });
5732 };
Robert Carr108b2c72019-04-02 16:32:58 -07005733
5734 bool outCapturedSecureLayers = false;
5735 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5736 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005737}
5738
5739status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5740 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005741 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005742 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005743 bool useIdentityTransform,
5744 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005745 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005746
Peiyong Lin0e003c92018-09-17 11:09:51 -07005747 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005748 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5749 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005750 *outBuffer =
5751 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5752 static_cast<android_pixel_format>(reqPixelFormat), 1,
5753 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005754
Robert Carr108b2c72019-04-02 16:32:58 -07005755 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005756 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005757}
5758
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005759status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5760 TraverseLayersFunction traverseLayers,
5761 const sp<GraphicBuffer>& buffer,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005762 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005763 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005764 const int uid = IPCThreadState::self()->getCallingUid();
5765 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5766
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005767 status_t result;
5768 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005769
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005770 do {
5771 std::tie(result, syncFd) =
5772 schedule([&] {
5773 if (mRefreshPending) {
5774 ATRACE_NAME("Skipping screenshot for now");
5775 return std::make_pair(EAGAIN, -1);
5776 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005777
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005778 status_t result = NO_ERROR;
5779 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005780
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005781 Mutex::Autolock lock(mStateLock);
5782 renderArea.render([&] {
5783 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5784 useIdentityTransform, forSystem, &fd,
5785 regionSampling, outCapturedSecureLayers);
5786 });
5787
5788 return std::make_pair(result, fd);
5789 }).get();
5790 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005791
5792 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005793 sync_wait(syncFd, -1);
5794 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005795 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005796
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005797 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005798}
5799
chaviwa76b2712017-09-20 12:02:26 -07005800void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005801 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005802 ANativeWindowBuffer* buffer, bool useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005803 bool regionSampling, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005804 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005805
chaviwa76b2712017-09-20 12:02:26 -07005806 const auto reqWidth = renderArea.getReqWidth();
5807 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005808 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005809 const auto transform = renderArea.getTransform();
5810 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005811 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005812
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005813 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005814 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005815
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005816 // assume that bounds are never offset, and that they are the same as the
5817 // buffer bounds.
5818 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005819 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005820 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005821
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005822 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5823 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005824
chaviw50da5042018-04-09 13:49:37 -07005825 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005826
Vishnu Nair9b079a22020-01-21 14:36:08 -08005827 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005828 fillLayer.source.buffer.buffer = nullptr;
5829 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005830 fillLayer.geometry.boundaries =
5831 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005832 fillLayer.alpha = half(alpha);
5833 clientCompositionLayers.push_back(fillLayer);
5834
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005835 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08005836 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005837 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005838 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005839 const bool supportProtectedContent = false;
5840 Region clip(renderArea.getBounds());
5841 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5842 clip,
5843 useIdentityTransform,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005844 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07005845 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005846 renderArea.isSecure(),
5847 supportProtectedContent,
5848 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005849 displayViewport,
5850 clientCompositionDisplay.outputDataspace,
5851 true, /* realContentIsVisible */
5852 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005853 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005854 std::vector<compositionengine::LayerFE::LayerSettings> results =
5855 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005856 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005857 for (auto& settings : results) {
5858 settings.geometry.positionTransform =
5859 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupinf11eba52020-04-20 18:42:31 -07005860 // There's no need to process blurs when we're executing region sampling,
5861 // we're just trying to understand what we're drawing, and doing so without
5862 // blurs is already a pretty good approximation.
5863 if (regionSampling) {
5864 settings.backgroundBlurRadius = 0;
5865 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005866 }
Yichi Chen40773d92020-04-01 10:10:18 +08005867 clientCompositionLayers.insert(clientCompositionLayers.end(),
5868 std::make_move_iterator(results.begin()),
5869 std::make_move_iterator(results.end()));
5870 renderedLayers.push_back(layer);
5871 }
chaviwa76b2712017-09-20 12:02:26 -07005872 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005873
Yichi Chen40773d92020-04-01 10:10:18 +08005874 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5875 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005876 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005877 clientCompositionLayerPointers.begin(),
5878 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005879
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005880 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005881 // Use an empty fence for the buffer fence, since we just created the buffer so
5882 // there is no need for synchronization with the GPU.
5883 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005884 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005885 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005886 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005887 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005888
5889 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005890
5891 if (*outSyncFd >= 0) {
5892 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5893 for (auto* layer : renderedLayers) {
5894 layer->onLayerDisplayed(releaseFence);
5895 }
5896 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005897}
5898
chaviwa76b2712017-09-20 12:02:26 -07005899status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5900 TraverseLayersFunction traverseLayers,
5901 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005902 bool useIdentityTransform, bool forSystem,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005903 int* outSyncFd, bool regionSampling,
5904 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005905 ATRACE_CALL();
5906
chaviwa76b2712017-09-20 12:02:26 -07005907 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005908 outCapturedSecureLayers =
5909 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005910 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005911
Robert Carr03480e22018-01-04 16:02:06 -08005912 // We allow the system server to take screenshots of secure layers for
5913 // use in situations like the Screen-rotation animation and place
5914 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005915 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005916 ALOGW("FB is protected: PERMISSION_DENIED");
5917 return PERMISSION_DENIED;
5918 }
Lucas Dupinf11eba52020-04-20 18:42:31 -07005919 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5920 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005921 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005922}
5923
chaviw95ef3c42019-02-14 10:55:09 -08005924void SurfaceFlinger::setInputWindowsFinished() {
5925 Mutex::Autolock _l(mStateLock);
5926
5927 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005928
chaviw95ef3c42019-02-14 10:55:09 -08005929 mTransactionCV.broadcast();
5930}
chaviw5f21a5e2019-02-14 10:00:34 -08005931
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005932// ---------------------------------------------------------------------------
5933
Edgar Arriaga844fa672020-01-16 14:21:42 -08005934void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5935 layersSortedByZ.traverse(visitor);
5936}
5937
Dan Stoza412903f2017-04-27 13:42:17 -07005938void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5939 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005940}
5941
Dan Stoza412903f2017-04-27 13:42:17 -07005942void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5943 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005944}
5945
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005946void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005947 const LayerVector::Visitor& visitor) {
5948 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005949 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005950 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005951 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005952 continue;
5953 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005954 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005955 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005956 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005957 return;
5958 }
chaviwa76b2712017-09-20 12:02:26 -07005959 if (!layer->isVisible()) {
5960 return;
5961 }
5962 visitor(layer);
5963 });
5964 }
5965}
5966
Steven Thomasd4071902020-03-24 16:02:53 -07005967status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5968 const sp<DisplayDevice>& display,
5969 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005970 Mutex::Autolock lock(mStateLock);
5971
Steven Thomasd4071902020-03-24 16:02:53 -07005972 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5973 "Can only set override policy on the primary display");
5974 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5975
Dominik Laskowski22488f62019-03-28 09:53:04 -07005976 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005977 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5978 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5979 // it should go thru setDesiredActiveConfig, similar to primary display.
5980 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5981 const auto displayId = display->getId();
5982 LOG_ALWAYS_FATAL_IF(!displayId);
5983
Peiyong Line9d809e2020-04-14 13:10:48 -07005984 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005985 constraints.desiredTimeNanos = systemTime();
5986 constraints.seamlessRequired = false;
5987
Peiyong Line9d809e2020-04-14 13:10:48 -07005988 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005989 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5990 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005991 constraints, &timeline) < 0) {
5992 return BAD_VALUE;
5993 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005994 if (timeline.refreshRequired) {
5995 repaintEverythingForHWC();
5996 }
5997
Steven Thomasd4071902020-03-24 16:02:53 -07005998 display->setActiveConfig(policy->defaultConfig);
5999 const nsecs_t vsyncPeriod = getHwComposer()
6000 .getConfigs(*displayId)[policy->defaultConfig.value()]
6001 ->getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006002 mScheduler->onNonPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6003 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006004 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08006005 }
6006
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006007 if (mDebugDisplayConfigSetByBackdoor) {
6008 // ignore this request as config is overridden by backdoor
6009 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006010 }
6011
Steven Thomasd4071902020-03-24 16:02:53 -07006012 status_t setPolicyResult = overridePolicy
6013 ? mRefreshRateConfigs->setOverridePolicy(policy)
6014 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
6015 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006016 return BAD_VALUE;
6017 }
Steven Thomasd4071902020-03-24 16:02:53 -07006018 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006019 return NO_ERROR;
6020 }
Steven Thomasd4071902020-03-24 16:02:53 -07006021 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006022
Steven Thomasf734df42020-04-13 21:09:28 -07006023 ALOGV("Setting desired display config specs: defaultConfig: %d primaryRange: [%.0f %.0f]"
6024 " expandedRange: [%.0f %.0f]",
6025 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
6026 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
6027 currentPolicy.appRequestRange.max);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006028
Ana Krulecb9afd792020-06-11 13:16:15 -07006029 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6030 // be depending in this callback.
Alec Mouri60aee1c2019-10-28 16:18:59 -07006031 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07006032 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
6033 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006034 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6035 display->getActiveConfig(), vsyncPeriod);
Ana Krulecb9afd792020-06-11 13:16:15 -07006036 toggleKernelIdleTimer();
Ady Abraham838de062019-02-04 10:24:03 -08006037
Ana Krulec3f6a2062020-01-23 15:48:01 -08006038 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08006039 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08006040 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
6041 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07006042 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08006043 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07006044 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006045
Ady Abrahamabc27602020-04-08 17:20:29 -07006046 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
6047 ALOGV("switching to Scheduler preferred config %d",
6048 preferredRefreshRate.getConfigId().value());
6049 setDesiredActiveConfig(
6050 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006051 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07006052 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
6053 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006054 }
6055
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006056 return NO_ERROR;
6057}
6058
Ana Krulec0782b882019-10-15 17:34:54 -07006059status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Steven Thomasf734df42020-04-13 21:09:28 -07006060 int32_t defaultConfig,
6061 float primaryRefreshRateMin,
6062 float primaryRefreshRateMax,
6063 float appRequestRefreshRateMin,
6064 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006065 ATRACE_CALL();
6066
6067 if (!displayToken) {
6068 return BAD_VALUE;
6069 }
6070
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006071 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006072 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006073 if (!display) {
6074 ALOGE("Attempt to set desired display configs for invalid display token %p",
6075 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006076 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006077 } else if (display->isVirtual()) {
6078 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006079 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006080 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006081 using Policy = scheduler::RefreshRateConfigs::Policy;
Steven Thomasf734df42020-04-13 21:09:28 -07006082 const Policy policy{HwcConfigIndexType(defaultConfig),
6083 {primaryRefreshRateMin, primaryRefreshRateMax},
6084 {appRequestRefreshRateMin, appRequestRefreshRateMax}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006085 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006086
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006087 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
6088 }
6089 });
6090
6091 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006092}
6093
6094status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006095 int32_t* outDefaultConfig,
Steven Thomasf734df42020-04-13 21:09:28 -07006096 float* outPrimaryRefreshRateMin,
6097 float* outPrimaryRefreshRateMax,
6098 float* outAppRequestRefreshRateMin,
6099 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006100 ATRACE_CALL();
6101
Steven Thomasf734df42020-04-13 21:09:28 -07006102 if (!displayToken || !outDefaultConfig || !outPrimaryRefreshRateMin ||
6103 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006104 return BAD_VALUE;
6105 }
6106
6107 Mutex::Autolock lock(mStateLock);
6108 const auto display = getDisplayDeviceLocked(displayToken);
6109 if (!display) {
6110 return NAME_NOT_FOUND;
6111 }
6112
6113 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006114 scheduler::RefreshRateConfigs::Policy policy =
6115 mRefreshRateConfigs->getDisplayManagerPolicy();
6116 *outDefaultConfig = policy.defaultConfig.value();
Steven Thomasf734df42020-04-13 21:09:28 -07006117 *outPrimaryRefreshRateMin = policy.primaryRange.min;
6118 *outPrimaryRefreshRateMax = policy.primaryRange.max;
6119 *outAppRequestRefreshRateMin = policy.appRequestRange.min;
6120 *outAppRequestRefreshRateMax = policy.appRequestRange.max;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006121 return NO_ERROR;
6122 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006123 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006124 } else {
6125 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006126 LOG_FATAL_IF(!displayId);
6127
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006128 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6129 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
Steven Thomasf734df42020-04-13 21:09:28 -07006130 *outPrimaryRefreshRateMin = 1e9f / vsyncPeriod;
6131 *outPrimaryRefreshRateMax = 1e9f / vsyncPeriod;
6132 *outAppRequestRefreshRateMin = 1e9f / vsyncPeriod;
6133 *outAppRequestRefreshRateMax = 1e9f / vsyncPeriod;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006134 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006135 }
Ana Krulec0782b882019-10-15 17:34:54 -07006136}
6137
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006138void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006139 mFlinger->setInputWindowsFinished();
6140}
6141
Alec Mouri9a02eda2020-04-21 17:39:34 -07006142wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6143 Mutex::Autolock _l(mStateLock);
6144 return fromHandleLocked(handle);
6145}
6146
6147wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006148 BBinder* b = nullptr;
6149 if (handle) {
6150 b = handle->localBinder();
6151 }
Robert Carrc0df3122019-04-11 13:18:21 -07006152 if (b == nullptr) {
6153 return nullptr;
6154 }
6155 auto it = mLayersByLocalBinderToken.find(b);
6156 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006157 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006158 }
6159 return nullptr;
6160}
6161
Dominik Laskowski75848362019-11-11 17:57:20 -08006162void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006163 mNumLayers++;
6164 mScheduler->registerLayer(layer);
6165}
6166
6167void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6168 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006169 removeFromOffscreenLayers(layer);
6170}
6171
6172// WARNING: ONLY CALL THIS FROM LAYER DTOR
6173// Here we add children in the current state to offscreen layers and remove the
6174// layer itself from the offscreen layer list. Since
6175// this is the dtor, it is safe to access the current state. This keeps us
6176// from dangling children layers such that they are not reachable from the
6177// Drawing state nor the offscreen layer list
6178// See b/141111965
6179void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6180 for (auto& child : layer->getCurrentChildren()) {
6181 mOffscreenLayers.emplace(child.get());
6182 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006183 mOffscreenLayers.erase(layer);
6184}
6185
Alec Mouri4545a8a2019-08-08 20:05:32 -07006186void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6187 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6188}
6189
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006190status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6191 float lightPosY, float lightPosZ,
6192 float lightRadius) {
6193 Mutex::Autolock _l(mStateLock);
6194 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6195 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6196 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6197 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6198 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6199
6200 // these values are overridden when calculating the shadow settings for a layer.
6201 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6202 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006203 return NO_ERROR;
6204}
6205
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006206const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6207 const {
6208 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6209 // on the work to remove the table in that bug rather than adding more to
6210 // it.
6211 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6212 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6213 // supported, and exposed via the
6214 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6215 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6216 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6217 };
6218 return genericLayerMetadataKeyMap;
6219}
6220
Steven Thomas62a4cf82020-01-31 12:04:03 -08006221status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6222 int8_t compatibility) {
6223 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6224 return BAD_VALUE;
6225 }
6226
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006227 static_cast<void>(schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006228 Mutex::Autolock lock(mStateLock);
6229 if (authenticateSurfaceTextureLocked(surface)) {
6230 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6231 if (layer->setFrameRate(
6232 Layer::FrameRate(frameRate,
6233 Layer::FrameRate::convertCompatibility(compatibility)))) {
6234 setTransactionFlags(eTraversalNeeded);
6235 }
6236 } else {
6237 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6238 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006239 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006240 return NO_ERROR;
6241 }));
6242
Steven Thomas62a4cf82020-01-31 12:04:03 -08006243 return NO_ERROR;
6244}
6245
Steven Thomasd4071902020-03-24 16:02:53 -07006246status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6247 if (!outToken) {
6248 return BAD_VALUE;
6249 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006250
6251 auto future = schedule([this] {
6252 status_t result = NO_ERROR;
6253 sp<IBinder> token;
6254
Steven Thomasd4071902020-03-24 16:02:53 -07006255 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006256 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Steven Thomasd4071902020-03-24 16:02:53 -07006257
6258 // This is a little racy, but not in a way that hurts anything. As we grab the
6259 // defaultConfig from the display manager policy, we could be setting a new display
6260 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6261 // matter for the override policy though, since we set allowGroupSwitching to true, so
6262 // it's not a problem.
6263 scheduler::RefreshRateConfigs::Policy overridePolicy;
6264 overridePolicy.defaultConfig =
6265 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6266 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006267 constexpr bool kOverridePolicy = true;
6268 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006269 }
6270
6271 if (result == NO_ERROR) {
6272 mFrameRateFlexibilityTokenCount++;
6273 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6274 // below, is something to consider carefully. The lifetime of the
6275 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6276 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6277 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6278 // in this case, for two reasons:
6279 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6280 // the program exits is via a crash. So we won't have a situation where the
6281 // SurfaceFlinger object is dead but the process is still up.
6282 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6283 // if condition 1 were changed, the problem would only show up when running CTS tests,
6284 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006285 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006286 [this]() { onFrameRateFlexibilityTokenReleased(); });
6287 ALOGD("Frame rate flexibility token acquired. count=%d",
6288 mFrameRateFlexibilityTokenCount);
6289 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006290
6291 return std::make_pair(result, token);
6292 });
6293
6294 status_t result;
6295 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006296 return result;
6297}
6298
6299void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006300 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006301 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6302 "Failed tracking frame rate flexibility tokens");
6303 mFrameRateFlexibilityTokenCount--;
6304 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6305 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006306 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006307 constexpr bool kOverridePolicy = true;
6308 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006309 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6310 }
6311 }));
6312}
6313
Dominik Laskowski20134642020-04-20 22:36:44 -07006314void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
6315 static_cast<void>(schedule([=] {
6316 std::unique_ptr<RefreshRateOverlay> overlay;
6317 if (enable) {
6318 overlay = std::make_unique<RefreshRateOverlay>(*this);
6319 }
6320
6321 {
6322 Mutex::Autolock lock(mStateLock);
6323
6324 // Destroy the layer of the current overlay, if any, outside the lock.
6325 mRefreshRateOverlay.swap(overlay);
6326 if (!mRefreshRateOverlay) return;
6327
6328 if (const auto display = getDefaultDisplayDeviceLocked()) {
6329 mRefreshRateOverlay->setViewport(display->getSize());
6330 }
6331
6332 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
6333 }
6334 }));
6335}
6336
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006337} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006338
Mathias Agopian3f844832013-08-07 21:24:32 -07006339#if defined(__gl_h_)
6340#error "don't include gl/gl.h in this file"
6341#endif
6342
6343#if defined(__gl2_h_)
6344#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006345#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006346
6347// TODO(b/129481165): remove the #pragma below and fix conversion issues
6348#pragma clang diagnostic pop // ignored "-Wconversion"