blob: 07690cbf325e2ed904eb59b03e6f51b208a15267 [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
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002124 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002125
David Sodman7e4ae112018-02-09 15:02:28 -08002126 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002127 if (mVisibleRegionsDirty) {
2128 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002129 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002130 mTracing.notify("visibleRegionsDirty");
2131 }
2132 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002133
2134 if (mCompositionEngine->needsAnotherUpdate()) {
2135 signalLayerUpdate();
2136 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002137}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002138
David Sodmanfa9b2af2017-12-24 13:28:59 -08002139bool SurfaceFlinger::handleMessageInvalidate() {
2140 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002141 bool refreshNeeded = handlePageFlip();
2142
Vishnu Nair4351ad52019-02-11 14:13:02 -08002143 if (mVisibleRegionsDirty) {
2144 computeLayerBounds();
2145 }
2146
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002147 for (auto& layer : mLayersPendingRefresh) {
2148 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002149 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002150 invalidateLayerStack(layer, visibleReg);
2151 }
2152 mLayersPendingRefresh.clear();
2153 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002154}
2155
Ana Krulece588e312018-09-18 12:32:24 -07002156void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2157 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002158 // Update queue of past composite+present times and determine the
2159 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002160 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002161 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002162 while (!getBE().mCompositePresentTimes.empty()) {
2163 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002164 // Cached values should have been updated before calling this method,
2165 // which helps avoid duplicate syscalls.
2166 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2167 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2168 break;
2169 }
2170 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002171 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002172 }
2173
2174 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002175 while (getBE().mCompositePresentTimes.size() > 16) {
2176 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002177 }
2178
Ana Krulece588e312018-09-18 12:32:24 -07002179 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002180}
2181
Ana Krulece588e312018-09-18 12:32:24 -07002182void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2183 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002184 // Integer division and modulo round toward 0 not -inf, so we need to
2185 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002186 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2187 ? (stats.vsyncPeriod -
2188 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2189 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002190
Ady Abraham9e16a482019-12-03 17:19:41 -08002191 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002192 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002193 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002194 }
2195
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002196 // Snap the latency to a value that removes scheduling jitter from the
2197 // composition and present times, which often have >1ms of jitter.
2198 // Reducing jitter is important if an app attempts to extrapolate
2199 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002200 // Snapping also allows an app to precisely calculate
2201 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002202 nsecs_t bias = stats.vsyncPeriod / 2;
2203 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2204 nsecs_t snappedCompositeToPresentLatency =
2205 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002206
David Sodman99974d22017-11-28 12:04:33 -08002207 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002208 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2209 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002210 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002211}
2212
David Sodman2b406362017-12-15 13:33:47 -08002213void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002214{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002215 ATRACE_CALL();
2216 ALOGV("postComposition");
2217
Brian Andersonf6386862016-10-31 16:34:13 -07002218 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002219 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002220 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002221 }
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002222
2223 const auto* display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002224
David Sodman73beded2017-11-15 11:56:06 -08002225 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002226 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002227 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002228 glCompositionDoneFenceTime =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002229 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002230 ->getRenderSurface()
2231 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002232 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002233 } else {
2234 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2235 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002236
David Sodman73beded2017-11-15 11:56:06 -08002237 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002238 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002239 mPreviousPresentFences[0] =
2240 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Ady Abrahambe0f9482019-04-24 15:41:53 -07002241 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002242 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002243
Ana Krulece588e312018-09-18 12:32:24 -07002244 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002245 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002246
Lloyd Piqueab039b52019-02-13 14:22:42 -08002247 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2248 // be sampled a little later than when we started doing work for this frame,
2249 // but that should be okay since updateCompositorTiming has snapping logic.
2250 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2251 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002252 CompositorTiming compositorTiming;
2253 {
David Sodman99974d22017-11-28 12:04:33 -08002254 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2255 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002256 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002257
Edgar Arriaga844fa672020-01-16 14:21:42 -08002258 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002259 const bool frameLatched = layer->onPostComposition(display, glCompositionDoneFenceTime,
2260 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002261 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002262 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002263 }
Robert Carr2047fae2016-11-28 14:09:09 -08002264 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002265
Valerie Hau4b678442020-04-14 10:50:42 -07002266 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2267 mTransactionCompletedThread.sendCallbacks();
2268
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002269 if (display && display->isPrimary() && display->getPowerMode() == hal::PowerMode::ON &&
2270 presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002271 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002272 }
2273
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002274 const bool isDisplayConnected = display && getHwComposer().isConnected(*display->getId());
2275
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002276 if (!hasSyncFramework) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002277 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002278 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002279 }
2280 }
2281
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002282 if (mAnimCompositionPending) {
2283 mAnimCompositionPending = false;
2284
Brian Anderson4e606e32017-03-16 15:34:57 -07002285 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002286 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002287 std::move(presentFenceTime));
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002288 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002289 // The HWC doesn't support present fences, so use the refresh
2290 // timestamp instead.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002291 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002292 mAnimFrameTracker.setActualPresentTime(presentTime);
2293 }
2294 mAnimFrameTracker.advanceFrame();
2295 }
Dan Stozab90cf072015-03-05 11:05:59 -08002296
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002297 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002298 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002299 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002300 }
2301
Vishnu Nair9b079a22020-01-21 14:36:08 -08002302 if (mReusedClientComposition) {
2303 mTimeStats->incrementClientCompositionReusedFrames();
2304 }
2305
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002306 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002307
Alec Mouri717bcb62020-02-10 17:07:19 -08002308 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2309 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2310 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2311
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002312 if (mLastJankDuration > 0) {
2313 ATRACE_NAME("Jank detected");
2314 const int32_t jankyDurationMillis = mLastJankDuration / (1000 * 1000);
2315 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED, jankyDurationMillis,
2316 mMissedFrameJankCount);
2317 mLastJankDuration = -1;
2318 }
2319
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002320 if (isDisplayConnected && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002321 return;
2322 }
2323
2324 nsecs_t currentTime = systemTime();
2325 if (mHasPoweredOff) {
2326 mHasPoweredOff = false;
2327 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002328 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002329 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002330 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2331 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002332 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002333 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002334 }
David Sodman4a36e932017-11-07 14:29:47 -08002335 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002336 }
David Sodman4a36e932017-11-07 14:29:47 -08002337 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002338
Alec Mouri4dde1782019-09-30 17:27:13 -07002339 // Cleanup any outstanding resources due to rendering a prior frame.
2340 getRenderEngine().cleanupPostRender();
2341
Dan Stoza436ccf32018-06-21 12:10:12 -07002342 {
2343 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002344 if (mTexturePool.size() < mTexturePoolSize) {
2345 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002346 const size_t offset = mTexturePool.size();
2347 mTexturePool.resize(mTexturePoolSize);
2348 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2349 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002350 } else if (mTexturePool.size() > mTexturePoolSize) {
2351 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2352 const size_t offset = mTexturePoolSize;
2353 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2354 mTexturePool.resize(mTexturePoolSize);
2355 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002356 }
2357 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002358
Kevin DuBois413287f2019-02-25 08:46:47 -08002359 if (mLumaSampling && mRegionSamplingThread) {
2360 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002361 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002362
2363 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2364 // side-effect of getTotalSize(), so we check that again here
2365 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002366 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002367 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2368 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002369}
2370
Lloyd Pique7eebe692020-04-22 22:40:06 -07002371FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2372 return displayDevice.getViewport().toFloatRect();
2373}
2374
Vishnu Nair4351ad52019-02-11 14:13:02 -08002375void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002376 for (const auto& pair : ON_MAIN_THREAD(mDisplays)) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08002377 const auto& displayDevice = pair.second;
2378 const auto display = displayDevice->getCompositionDisplay();
2379 for (const auto& layer : mDrawingState.layersSortedByZ) {
2380 // only consider the layers on the given layer stack
2381 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002382 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002383 }
2384
Lloyd Pique7eebe692020-04-22 22:40:06 -07002385 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002386 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002387 }
2388 }
2389}
2390
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002391void SurfaceFlinger::postFrame() {
2392 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002393 if (display && getHwComposer().isConnected(*display->getId())) {
2394 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002395 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2396 logFrameStats();
2397 }
2398 }
2399}
2400
Mathias Agopian87baae12012-07-31 12:38:26 -07002401void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002402{
Mathias Agopian841cde52012-03-01 15:44:37 -08002403 ATRACE_CALL();
2404
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002405 // here we keep a copy of the drawing state (that is the state that's
2406 // going to be overwritten by handleTransactionLocked()) outside of
2407 // mStateLock so that the side-effects of the State assignment
2408 // don't happen with mStateLock held (which can cause deadlocks).
2409 State drawingState(mDrawingState);
2410
Mathias Agopianca4d3602011-05-19 15:38:14 -07002411 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002412 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002413
Mathias Agopianca4d3602011-05-19 15:38:14 -07002414 // Here we're guaranteed that some transaction flags are set
2415 // so we can call handleTransactionLocked() unconditionally.
2416 // We call getTransactionFlags(), which will also clear the flags,
2417 // with mStateLock held to guarantee that mCurrentState won't change
2418 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002419
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002420 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002421 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002422 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002423
Mathias Agopianca4d3602011-05-19 15:38:14 -07002424 mDebugInTransaction = 0;
2425 invalidateHwcGeometry();
2426 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002427}
2428
Lloyd Piqueba04e622017-12-14 17:11:26 -08002429void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2430 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002431 const std::optional<DisplayIdentificationInfo> info =
2432 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002433
Dominik Laskowski075d3172018-05-24 15:50:06 -07002434 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002435 continue;
2436 }
2437
Dominik Laskowski55c85402020-01-21 16:25:47 -08002438 const DisplayId displayId = info->id;
2439 const auto it = mPhysicalDisplayTokens.find(displayId);
2440
Peiyong Line9d809e2020-04-14 13:10:48 -07002441 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002442 if (it == mPhysicalDisplayTokens.end()) {
2443 ALOGV("Creating display %s", to_string(displayId).c_str());
2444
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002445 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002446 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002447 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002448
Dominik Laskowski075d3172018-05-24 15:50:06 -07002449 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002450 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2451 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002452 state.isSecure = true; // All physical displays are currently considered secure.
2453 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002454
2455 sp<IBinder> token = new BBinder();
2456 mCurrentState.displays.add(token, state);
2457 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2458
Dominik Laskowski075d3172018-05-24 15:50:06 -07002459 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002460 } else {
2461 ALOGV("Recreating display %s", to_string(displayId).c_str());
2462
2463 const auto token = it->second;
2464 auto& state = mCurrentState.displays.editValueFor(token);
2465 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002466 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002467 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002468 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002469
Dominik Laskowski55c85402020-01-21 16:25:47 -08002470 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002471 if (index >= 0) {
2472 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2473 mInterceptor->saveDisplayDeletion(state.sequenceId);
2474 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002475 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002476 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002477 }
2478
2479 processDisplayChangesLocked();
2480 }
2481
2482 mPendingHotplugEvents.clear();
2483}
2484
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002485void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002486 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2487 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002488}
2489
Lloyd Pique99d3da52018-01-22 17:48:03 -08002490sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002491 const wp<IBinder>& displayToken,
2492 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002493 const DisplayDeviceState& state,
2494 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002495 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002496 auto displayId = compositionDisplay->getDisplayId();
2497 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002498 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002499 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002500 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002501 creationArgs.hasWideColorGamut = false;
2502 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002503
Dominik Laskowski55c85402020-01-21 16:25:47 -08002504 if (const auto& physical = state.physical) {
2505 creationArgs.connectionType = physical->type;
2506 }
2507
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002508 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002509 creationArgs.isPrimary = isInternalDisplay;
2510
2511 if (useColorManagement && displayId) {
2512 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002513 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002514 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002515 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002516 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002517
Dominik Laskowski7e045462018-05-30 13:02:02 -07002518 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002519 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002520 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002521 }
tangrobin6753a022018-08-10 10:58:54 +08002522 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002523
Dominik Laskowski075d3172018-05-24 15:50:06 -07002524 if (displayId) {
2525 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002526 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002527 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002528 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002529
Lloyd Pique90c115d2018-09-18 21:39:42 -07002530 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002531 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002532 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002533
Lloyd Pique99d3da52018-01-22 17:48:03 -08002534 // Make sure that composition can never be stalled by a virtual display
2535 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002536 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002537 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002538 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2539 }
2540
Dominik Laskowski718f9602019-11-09 20:01:35 -08002541 creationArgs.physicalOrientation =
2542 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002543
Lloyd Pique99d3da52018-01-22 17:48:03 -08002544 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002545 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002546
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002547 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002548
2549 if (maxFrameBufferAcquiredBuffers >= 3) {
2550 nativeWindowSurface->preallocateBuffers();
2551 }
2552
2553 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002554 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002555 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002556 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002557 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002558 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002559 display->getCompositionDisplay()->setColorProfile(
2560 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2561 RenderIntent::COLORIMETRIC,
2562 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002563 if (!state.isVirtual()) {
2564 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002565 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2566 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002567 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002569 display->setLayerStack(state.layerStack);
2570 display->setProjection(state.orientation, state.viewport, state.frame);
2571 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002572
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002573 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574}
2575
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002576void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2577 const DisplayDeviceState& state) {
2578 int width = 0;
2579 int height = 0;
2580 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2581 if (state.physical) {
2582 const auto& activeConfig =
2583 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2584 width = activeConfig->getWidth();
2585 height = activeConfig->getHeight();
2586 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2587 } else if (state.surface != nullptr) {
2588 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2589 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2590 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2591 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2592 int intPixelFormat;
2593 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2594 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2595 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2596 } else {
2597 // Virtual displays without a surface are dormant:
2598 // they have external state (layer stack, projection,
2599 // etc.) but no internal state (i.e. a DisplayDevice).
2600 return;
2601 }
2602
2603 compositionengine::DisplayCreationArgsBuilder builder;
2604 if (const auto& physical = state.physical) {
2605 builder.setPhysical({physical->id, physical->type});
2606 }
2607 builder.setPixels(ui::Size(width, height));
2608 builder.setPixelFormat(pixelFormat);
2609 builder.setIsSecure(state.isSecure);
2610 builder.setLayerStackId(state.layerStack);
2611 builder.setPowerAdvisor(&mPowerAdvisor);
2612 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2613 builder.setName(state.displayName);
2614 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2615
2616 sp<compositionengine::DisplaySurface> displaySurface;
2617 sp<IGraphicBufferProducer> producer;
2618 sp<IGraphicBufferProducer> bqProducer;
2619 sp<IGraphicBufferConsumer> bqConsumer;
2620 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2621
2622 std::optional<DisplayId> displayId = compositionDisplay->getId();
2623
2624 if (state.isVirtual()) {
2625 sp<VirtualDisplaySurface> vds =
2626 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2627 bqConsumer, state.displayName);
2628
2629 displaySurface = vds;
2630 producer = vds;
2631 } else {
2632 ALOGE_IF(state.surface != nullptr,
2633 "adding a supported display, but rendering "
2634 "surface is provided (%p), ignoring it",
2635 state.surface.get());
2636
2637 LOG_ALWAYS_FATAL_IF(!displayId);
2638 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2639 maxGraphicsWidth, maxGraphicsHeight);
2640 producer = bqProducer;
2641 }
2642
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002643 LOG_FATAL_IF(!displaySurface);
2644 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2645 displaySurface, producer);
2646 mDisplays.emplace(displayToken, display);
2647 if (!state.isVirtual()) {
2648 LOG_FATAL_IF(!displayId);
2649 dispatchDisplayHotplugEvent(displayId->value, true);
2650 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002651
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002652 if (display->isPrimary()) {
2653 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002654 }
2655}
2656
2657void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2658 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2659 // Save display ID before disconnecting.
2660 const auto displayId = display->getId();
2661 display->disconnect();
2662
2663 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002664 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002665 dispatchDisplayHotplugEvent(displayId->value, false);
2666 }
2667 }
2668
2669 mDisplays.erase(displayToken);
2670}
2671
2672void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2673 const DisplayDeviceState& currentState,
2674 const DisplayDeviceState& drawingState) {
2675 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2676 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002677 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002678 // changing the surface is like destroying and recreating the DisplayDevice
2679 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2680 display->disconnect();
2681 }
2682 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002683 if (const auto& physical = currentState.physical) {
2684 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2685 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002686 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002687 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002688 const auto display = getDisplayDeviceLocked(displayToken);
2689 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002690 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002691 return;
2692 }
2693
2694 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2695 if (currentState.layerStack != drawingState.layerStack) {
2696 display->setLayerStack(currentState.layerStack);
2697 }
2698 if ((currentState.orientation != drawingState.orientation) ||
2699 (currentState.viewport != drawingState.viewport) ||
2700 (currentState.frame != drawingState.frame)) {
2701 display->setProjection(currentState.orientation, currentState.viewport,
2702 currentState.frame);
2703 }
2704 if (currentState.width != drawingState.width ||
2705 currentState.height != drawingState.height) {
2706 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07002707
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002708 if (display->isPrimary()) {
2709 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2710 }
Dominik Laskowski20134642020-04-20 22:36:44 -07002711
2712 if (mRefreshRateOverlay) {
2713 mRefreshRateOverlay->setViewport(display->getSize());
2714 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002715 }
2716 }
2717}
2718
Lloyd Pique347200f2017-12-14 17:00:15 -08002719void SurfaceFlinger::processDisplayChangesLocked() {
2720 // here we take advantage of Vector's copy-on-write semantics to
2721 // improve performance by skipping the transaction entirely when
2722 // know that the lists are identical
2723 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2724 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2725 if (!curr.isIdenticalTo(draw)) {
2726 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002727
2728 // find the displays that were removed
2729 // (ie: in drawing state but not in current state)
2730 // also handle displays that changed
2731 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002732 for (size_t i = 0; i < draw.size(); i++) {
2733 const wp<IBinder>& displayToken = draw.keyAt(i);
2734 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 if (j < 0) {
2736 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002737 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 } else {
2739 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002740 const DisplayDeviceState& currentState = curr[j];
2741 const DisplayDeviceState& drawingState = draw[i];
2742 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002743 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002744 }
2745
2746 // find displays that were added
2747 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002748 for (size_t i = 0; i < curr.size(); i++) {
2749 const wp<IBinder>& displayToken = curr.keyAt(i);
2750 if (draw.indexOfKey(displayToken) < 0) {
2751 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002752 }
2753 }
2754 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002755
2756 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002757}
2758
Mathias Agopian87baae12012-07-31 12:38:26 -07002759void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002760{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002761 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2762
Dan Stoza7dde5992015-05-22 09:51:44 -07002763 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002764 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002765 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002766 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002767
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 /*
2769 * Traversal of the children
2770 * (perform the transaction for each of them if needed)
2771 */
2772
Valerie Haud50e7412020-06-16 17:58:14 -07002773 if ((transactionFlags & eTraversalNeeded) || mForceTraversal) {
2774 mForceTraversal = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002775 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002777 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778
2779 const uint32_t flags = layer->doTransaction(0);
2780 if (flags & Layer::eVisibleRegion)
2781 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002782
2783 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002784 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002785 }
Robert Carr2047fae2016-11-28 14:09:09 -08002786 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787 }
2788
2789 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002790 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 */
2792
Mathias Agopiane57f2922012-08-09 16:29:12 -07002793 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002794 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002795 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002796 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797
Vishnu Nair6213bd92020-05-08 17:42:25 -07002798 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002799 // The transform hint might have changed for some layers
2800 // (either because a display has changed, or because a layer
2801 // as changed).
2802 //
2803 // Walk through all the layers in currentLayers,
2804 // and update their transform hint.
2805 //
2806 // If a layer is visible only on a single display, then that
2807 // display is used to calculate the hint, otherwise we use the
2808 // default display.
2809 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002810 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002811 // the hint is set before we acquire a buffer from the surface texture.
2812 //
2813 // NOTE: layer transactions have taken place already, so we use their
2814 // drawing state. However, SurfaceFlinger's own transaction has not
2815 // happened yet, so we must use the current state layer list
2816 // (soon to become the drawing state list).
2817 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002818 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002819 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002820 bool first = true;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002821 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08002822 // NOTE: we rely on the fact that layers are sorted by
2823 // layerStack first (so we don't have to traverse the list
2824 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002825 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002826 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002827 currentlayerStack = layerStack;
2828 // figure out if this layerstack is mirrored
2829 // (more than one display) if so, pick the default display,
2830 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002831 hintDisplay = nullptr;
2832 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002833 if (display->getCompositionDisplay()
2834 ->belongsInOutput(layer->getLayerStack(),
2835 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002836 if (hintDisplay) {
2837 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002838 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002839 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002840 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002841 }
2842 }
2843 }
2844 }
Chet Haase91d25932013-04-11 15:24:55 -07002845
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002846 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002847 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2848 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002849
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002850 // could be null when this layer is using a layerStack
2851 // that is not visible on any display. Also can occur at
2852 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002853 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002854 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002855
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002856 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002857 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002858 if (hintDisplay) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002859 layer->updateTransformHint(hintDisplay->getTransformHint());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002860 }
Robert Carr2047fae2016-11-28 14:09:09 -08002861
2862 first = false;
2863 });
Mathias Agopian84300952012-11-21 16:02:13 -08002864 }
2865
Mathias Agopian3559b072012-08-15 13:46:03 -07002866 /*
2867 * Perform our own transaction if needed
2868 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002869
2870 if (mLayersAdded) {
2871 mLayersAdded = false;
2872 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002873 mVisibleRegionsDirty = true;
2874 }
2875
2876 // some layers might have been removed, so
2877 // we need to update the regions they're exposing.
2878 if (mLayersRemoved) {
2879 mLayersRemoved = false;
2880 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002881 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002882 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002883 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002884 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002885 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002886 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002887 }
Robert Carr2047fae2016-11-28 14:09:09 -08002888 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889 }
2890
Vishnu Nairec0ab382019-02-13 15:32:56 -08002891 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002893}
2894
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002895void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002896 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002897 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002898 return;
2899 }
2900
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002901 if (mVisibleRegionsDirty || mInputInfoChanged) {
2902 mInputInfoChanged = false;
2903 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002904 } else if (mInputWindowCommands.syncInputWindows) {
2905 // If the caller requested to sync input windows, but there are no
2906 // changes to input windows, notify immediately.
2907 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002908 }
2909
Arthur Hung6cbb9752019-09-05 16:38:18 +08002910 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002911}
2912
2913void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002914 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002915
2916 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Robert Carredd13602020-04-13 17:24:34 -07002917 if (layer->needsInputInfo()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002918 // When calculating the screen bounds we ignore the transparent region since it may
2919 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002920 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002921 }
2922 });
chaviw291d88a2019-02-14 10:33:58 -08002923
2924 mInputFlinger->setInputWindows(inputHandles,
2925 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2926 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002927}
2928
Vishnu Nairec0ab382019-02-13 15:32:56 -08002929void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002930 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002931 mPendingInputWindowCommands.clear();
2932}
2933
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002934void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002935 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002936 for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002937 if (display->getId()) {
2938 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002939 }
2940 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002941
2942 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002943}
2944
Ady Abraham2139f732019-11-13 18:56:40 -08002945void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002946 Scheduler::ConfigEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08002947 // If this is called from the main thread mStateLock must be locked before
2948 // Currently the only way to call this function from the main thread is from
2949 // Sheduler::chooseRefreshRateForContent
2950
2951 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002952 changeRefreshRateLocked(refreshRate, event);
2953}
2954
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002955void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2956 if (mScheduler) {
2957 // In practice it's not allowed to hotplug in/out the primary display once it's been
2958 // connected during startup, but some tests do it, so just warn and return.
2959 ALOGW("Can't re-init scheduler");
2960 return;
2961 }
2962
Ady Abraham2139f732019-11-13 18:56:40 -08002963 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002964 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002965 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002966 primaryDisplayId),
2967 currentConfig);
2968 mRefreshRateStats =
2969 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002970 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002971 mRefreshRateStats->setConfigMode(currentConfig);
2972
Ady Abraham9e16a482019-12-03 17:19:41 -08002973 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2974
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002975 // start the EventThread
2976 mScheduler =
2977 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002978 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002979 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002980 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002981 impl::EventThread::InterceptVSyncsCallback());
2982 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002983 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002984 [this](nsecs_t timestamp) {
2985 mInterceptor->saveVSyncEvent(timestamp);
2986 });
2987
2988 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2989 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002990 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002991
2992 mRegionSamplingThread =
2993 new RegionSamplingThread(*this, *mScheduler,
2994 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002995 // Dispatch a config change request for the primary display on scheduler
2996 // initialization, so that the EventThreads always contain a reference to a
2997 // prior configuration.
2998 //
2999 // This is a bit hacky, but this avoids a back-pointer into the main SF
3000 // classes from EventThread, and there should be no run-time binder cost
3001 // anyway since there are no connected apps at this point.
3002 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07003003 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07003004 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, primaryDisplayId.value,
3005 currentConfig, vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003006}
3007
Mathias Agopian4fec8732012-06-29 14:12:52 -07003008void SurfaceFlinger::commitTransaction()
3009{
Vishnu Nair60db8c02020-04-02 11:55:16 -07003010 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003011 mTransactionPending = false;
3012 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003013 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003014}
3015
Lloyd Pique58e24a32019-08-01 15:50:14 -07003016void SurfaceFlinger::commitTransactionLocked() {
3017 if (!mLayersPendingRemoval.isEmpty()) {
3018 // Notify removed layers now that they can't be drawn from
3019 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003020 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003021
3022 // Ensure any buffers set to display on any children are released.
3023 if (l->isRemovedFromCurrentState()) {
3024 l->latchAndReleaseBuffer();
3025 }
3026
3027 // If the layer has been removed and has no parent, then it will not be reachable
3028 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3029 // ensure we can copy its current to drawing state.
3030 if (!l->getParent()) {
3031 mOffscreenLayers.emplace(l.get());
3032 }
3033 }
3034 mLayersPendingRemoval.clear();
3035 }
3036
3037 // If this transaction is part of a window animation then the next frame
3038 // we composite should be considered an animation as well.
3039 mAnimCompositionPending = mAnimTransactionPending;
3040
3041 mDrawingState = mCurrentState;
3042 // clear the "changed" flags in current state
3043 mCurrentState.colorMatrixChanged = false;
3044
Edgar Arriaga844fa672020-01-16 14:21:42 -08003045 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003046 layer->commitChildList();
3047
3048 // If the layer can be reached when traversing mDrawingState, then the layer is no
3049 // longer offscreen. Remove the layer from the offscreenLayer set.
3050 if (mOffscreenLayers.count(layer)) {
3051 mOffscreenLayers.erase(layer);
3052 }
3053 });
3054
3055 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003056 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003057}
3058
chaviw74d90ad2019-04-26 14:45:26 -07003059void SurfaceFlinger::commitOffscreenLayers() {
3060 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003061 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003062 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3063 if (!trFlags) return;
3064
3065 layer->doTransaction(0);
3066 layer->commitChildList();
3067 });
3068 }
3069}
3070
Chia-I Wuab0c3192017-08-01 11:29:00 -07003071void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07003072 for (const auto& [token, displayDevice] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003073 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003074 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003075 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003076 }
3077 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003078}
3079
Dan Stoza6b9454d2014-11-07 16:00:59 -08003080bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081{
Ady Abraham09bd3922019-04-08 10:44:56 -07003082 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003083 ALOGV("handlePageFlip");
3084
Brian Andersond6927fb2016-07-23 23:37:30 -07003085 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086
Mathias Agopian4fec8732012-06-29 14:12:52 -07003087 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003088 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003089 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003090
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003091 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3092
Eric Penner51c59cd2014-07-28 19:51:58 -07003093 // Store the set of layers that need updates. This set must not change as
3094 // buffers are being latched, as this could result in a deadlock.
3095 // Example: Two producers share the same command stream and:
3096 // 1.) Layer 0 is latched
3097 // 2.) Layer 0 gets a new frame
3098 // 2.) Layer 1 gets a new frame
3099 // 3.) Layer 1 is latched.
3100 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3101 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003102 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003103 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003104 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003105 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003106 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003107 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003108 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003109 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003110 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003111 } else {
3112 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003113 }
Robert Carr2047fae2016-11-28 14:09:09 -08003114 });
3115
chaviw49a108c2019-08-12 11:23:06 -07003116 // The client can continue submitting buffers for offscreen layers, but they will not
3117 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3118 // layers to ensure dequeueBuffer doesn't block indefinitely.
3119 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003120 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003121 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3122 }
3123
Lloyd Piquef2c79392018-12-20 16:23:33 -08003124 if (!mLayersWithQueuedFrames.empty()) {
3125 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3126 // writes to Layer current state. See also b/119481871
3127 Mutex::Autolock lock(mStateLock);
3128
3129 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003130 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003131 mLayersPendingRefresh.push_back(layer);
3132 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003133 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003134 if (layer->isBufferLatched()) {
3135 newDataLatched = true;
3136 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003137 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003138 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003139
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003140 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003141
3142 // If we will need to wake up at some time in the future to deal with a
3143 // queued frame that shouldn't be displayed during this vsync period, wake
3144 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003145 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003146 signalLayerUpdate();
3147 }
3148
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003149 // enter boot animation on first buffer latch
3150 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3151 ALOGI("Enter boot animation");
3152 mBootStage = BootStage::BOOTANIMATION;
3153 }
3154
Edgar Arriaga844fa672020-01-16 14:21:42 -08003155 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003156
Dan Stoza6b9454d2014-11-07 16:00:59 -08003157 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003158 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159}
3160
Mathias Agopianad456f92011-01-13 17:53:01 -08003161void SurfaceFlinger::invalidateHwcGeometry()
3162{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003163 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003164}
3165
Robert Carrc0df3122019-04-11 13:18:21 -07003166status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3167 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3168 const sp<IBinder>& parentHandle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003169 const sp<Layer>& parentLayer, bool addToCurrentState,
3170 uint32_t* outTransformHint) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003171 // add this layer to the current state list
3172 {
3173 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003174 sp<Layer> parent;
3175 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003176 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003177 if (parent == nullptr) {
3178 return NAME_NOT_FOUND;
3179 }
3180 } else {
3181 parent = parentLayer;
3182 }
3183
Ady Abraham0a525092020-03-03 12:51:24 -08003184 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003185 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003186 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003187 return NO_MEMORY;
3188 }
Robert Carrc0df3122019-04-11 13:18:21 -07003189
3190 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3191
Robert Carrb89ea9d2018-12-10 13:01:14 -08003192 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003193 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003194 } else if (parent == nullptr) {
3195 lbc->onRemovedFromCurrentState();
3196 } else if (parent->isRemovedFromCurrentState()) {
3197 parent->addChild(lbc);
3198 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003199 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003200 parent->addChild(lbc);
3201 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003202
Yiwei Zhang243b3782018-05-15 17:40:04 -07003203 if (gbc != nullptr) {
3204 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3205 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3206 mMaxGraphicBufferProducerListSize,
3207 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3208 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003209 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003210 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003211
3212 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07003213 lbc->updateTransformHint(display->getTransformHint());
Vishnu Nair6213bd92020-05-08 17:42:25 -07003214 }
3215 if (outTransformHint) {
3216 *outTransformHint = lbc->getTransformHint();
3217 }
3218
Robert Carr1f0a16a2016-10-24 16:27:39 -07003219 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003220 }
3221
Mathias Agopian96f08192010-06-02 23:28:45 -07003222 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003223 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003224
Dan Stoza7d89d062015-04-30 13:29:25 -07003225 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003226}
3227
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003228void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3229 static_cast<void>(schedule([=] {
3230 Mutex::Autolock lock(mStateLock);
3231 mGraphicBufferProducerList.erase(binder);
3232 }));
3233}
3234
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003235uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003236 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003237}
3238
Mathias Agopian3f844832013-08-07 21:24:32 -07003239uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003240 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241}
3242
Mathias Agopian3f844832013-08-07 21:24:32 -07003243uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ady Abrahambf1349c2020-06-12 14:26:18 -07003244 return setTransactionFlags(flags, Scheduler::TransactionStart::Normal);
Dan Stoza84d619e2018-03-28 17:07:36 -07003245}
3246
3247uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003248 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003249 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003250 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003251 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003252 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253 }
3254 return old;
3255}
3256
Valerie Haud50e7412020-06-16 17:58:14 -07003257void SurfaceFlinger::setTraversalNeeded() {
3258 mForceTraversal = true;
Robert Carr7ec777d2020-05-29 12:02:51 -07003259}
3260
Marissa Wall713b63f2018-10-17 15:42:43 -07003261bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003262 // to prevent onHandleDestroyed from being called while the lock is held,
3263 // we must keep a copy of the transactions (specifically the composer
3264 // states) around outside the scope of the lock
3265 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003266 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003267 {
3268 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003269
Valerie Haufce31b82019-04-30 16:41:14 -07003270 auto it = mTransactionQueues.begin();
3271 while (it != mTransactionQueues.end()) {
3272 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003273
Valerie Haufce31b82019-04-30 16:41:14 -07003274 while (!transactionQueue.empty()) {
3275 const auto& transaction = transactionQueue.front();
3276 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3277 transaction.states)) {
3278 setTransactionFlags(eTransactionFlushNeeded);
3279 break;
3280 }
3281 transactions.push_back(transaction);
3282 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3283 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003284 transaction.buffer, transaction.postTime,
3285 transaction.privileged, transaction.hasListenerCallbacks,
3286 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003287 transactionQueue.pop();
3288 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003289 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003290
Valerie Haufce31b82019-04-30 16:41:14 -07003291 if (transactionQueue.empty()) {
3292 it = mTransactionQueues.erase(it);
3293 mTransactionCV.broadcast();
3294 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003295 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003296 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003297 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003298 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003299 return flushedATransaction;
3300}
3301
3302bool SurfaceFlinger::transactionFlushNeeded() {
3303 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003304}
3305
chaviwca27f252018-02-06 16:46:39 -08003306
Marissa Wall17b4e452018-12-26 16:32:34 -08003307bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3308 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003309
3310 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003311 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3312 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3313 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3314 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3315 return false;
3316 }
3317
Marissa Wall713b63f2018-10-17 15:42:43 -07003318 for (const ComposerState& state : states) {
3319 const layer_state_t& s = state.state;
3320 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3321 continue;
3322 }
3323 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003324 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003325 }
3326 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003327 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003328}
3329
Valerie Hau9dab9732019-08-20 09:29:25 -07003330void SurfaceFlinger::setTransactionState(
3331 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3332 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3333 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3334 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003335 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003336
Valerie Haubc6ddb12019-03-08 11:10:15 -08003337 const int64_t postTime = systemTime();
3338
Robert Carr14167e02019-02-13 13:50:55 -08003339 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3340
Mathias Agopian698c0872011-06-28 19:09:31 -07003341 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003342
Marissa Wall713b63f2018-10-17 15:42:43 -07003343 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003344 auto itr = mTransactionQueues.find(applyToken);
3345 // if this is an animation frame, wait until prior animation frame has
3346 // been applied by SF
3347 if (flags & eAnimation) {
3348 while (itr != mTransactionQueues.end()) {
3349 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3350 if (CC_UNLIKELY(err != NO_ERROR)) {
3351 ALOGW_IF(err == TIMED_OUT,
3352 "setTransactionState timed out "
3353 "waiting for animation frame to apply");
3354 break;
3355 }
3356 itr = mTransactionQueues.find(applyToken);
3357 }
3358 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003359
Ady Abraham5facfb12020-04-22 15:18:31 -07003360 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003361 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003362 if (!pendingTransactions) {
3363 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3364 }
3365
3366 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003367 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003368 uncacheBuffer, postTime, privileged,
3369 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003370 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003371 return;
3372 }
3373
Valerie Haubc6ddb12019-03-08 11:10:15 -08003374 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003375 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3376 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003377}
3378
Valerie Hau9dab9732019-08-20 09:29:25 -07003379void SurfaceFlinger::applyTransactionState(
3380 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3381 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3382 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3383 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3384 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003385 uint32_t transactionFlags = 0;
3386
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003387 if (flags & eAnimation) {
3388 // For window updates that are part of an animation we must wait for
3389 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003390 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003391 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003392 if (CC_UNLIKELY(err != NO_ERROR)) {
3393 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003394 // caller after a few seconds.
3395 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3396 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003397 mAnimTransactionPending = false;
3398 break;
3399 }
3400 }
3401 }
3402
chaviwca27f252018-02-06 16:46:39 -08003403 for (const DisplayState& display : displays) {
3404 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003405 }
3406
Valerie Hau9dab9732019-08-20 09:29:25 -07003407 // start and end registration for listeners w/ no surface so they can get their callback. Note
3408 // that listeners with SurfaceControls will start registration during setClientStateLocked
3409 // below.
3410 for (const auto& listener : listenerCallbacks) {
3411 mTransactionCompletedThread.startRegistration(listener);
3412 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003413 }
3414
Valerie Hau9dab9732019-08-20 09:29:25 -07003415 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003416 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003417 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003418 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3419 listenerCallbacksWithSurfaces);
Ady Abraham5def7332020-05-29 16:13:47 -07003420 if ((flags & eAnimation) && state.state.surface) {
3421 if (const auto layer = fromHandleLocked(state.state.surface).promote(); layer) {
3422 mScheduler->recordLayerHistory(layer.get(), desiredPresentTime,
3423 LayerHistory::LayerUpdateType::AnimationTX);
3424 }
3425 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07003426 }
3427
Valerie Hau9dab9732019-08-20 09:29:25 -07003428 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003429 mTransactionCompletedThread.endRegistration(listenerCallback);
3430 }
3431
Marissa Walle2ffb422018-10-12 11:33:52 -07003432 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003433 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003434 mTransactionCompletedThread.sendCallbacks();
3435 }
3436 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003437
chaviw273171b2018-12-26 11:46:30 -08003438 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3439
Marissa Wall947d34e2019-03-29 14:03:53 -07003440 if (uncacheBuffer.isValid()) {
3441 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003442 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003443 }
3444
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003445 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3446 // anyway. This can be used as a flush mechanism for previous async transactions.
3447 // Empty animation transaction can be used to simulate back-pressure, so also force a
3448 // transaction for empty animation transactions.
3449 if (transactionFlags == 0 &&
3450 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003451 transactionFlags = eTransactionNeeded;
3452 }
3453
Marissa Wall06255332019-03-27 13:48:27 -07003454 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3455 // so we don't have to wake up again next frame to preform an uneeded traversal.
3456 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3457 transactionFlags = transactionFlags & (~eTraversalNeeded);
Valerie Haud50e7412020-06-16 17:58:14 -07003458 mForceTraversal = true;
Marissa Wall06255332019-03-27 13:48:27 -07003459 }
3460
Ady Abrahambf1349c2020-06-12 14:26:18 -07003461 const auto transactionStart = [](uint32_t flags) {
3462 if (flags & eEarlyWakeup) {
3463 return Scheduler::TransactionStart::Early;
3464 }
3465 if (flags & eExplicitEarlyWakeupEnd) {
3466 return Scheduler::TransactionStart::EarlyEnd;
3467 }
3468 if (flags & eExplicitEarlyWakeupStart) {
3469 return Scheduler::TransactionStart::EarlyStart;
3470 }
3471 return Scheduler::TransactionStart::Normal;
3472 }(flags);
3473
Mathias Agopian386aa982011-11-07 21:58:03 -08003474 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003475 if (mInterceptor->isEnabled()) {
3476 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003477 }
Irvel468051e2016-06-13 16:44:44 -07003478
Ady Abrahambf1349c2020-06-12 14:26:18 -07003479 // TODO(b/159125966): Remove eEarlyWakeup completly as no client should use this flag
3480 if (flags & eEarlyWakeup) {
3481 ALOGW("eEarlyWakeup is deprecated. Use eExplicitEarlyWakeup[Start|End]");
3482 }
3483
3484 if (!privileged && (flags & (eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd))) {
3485 ALOGE("Only WindowManager is allowed to use eExplicitEarlyWakeup[Start|End] flags");
3486 flags &= ~(eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd);
3487 }
3488
Mathias Agopian386aa982011-11-07 21:58:03 -08003489 // this triggers the transaction
Ady Abrahambf1349c2020-06-12 14:26:18 -07003490 setTransactionFlags(transactionFlags, transactionStart);
Mathias Agopian386aa982011-11-07 21:58:03 -08003491
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003492 if (flags & eAnimation) {
3493 mAnimTransactionPending = true;
3494 }
Robert Carr238f4a22020-04-29 13:04:02 -07003495
3496 // if this is a synchronous transaction, wait for it to take effect
3497 // before returning.
3498 const bool synchronous = flags & eSynchronous;
3499 const bool syncInput = inputWindowCommands.syncInputWindows;
3500 if (!synchronous && !syncInput) {
3501 return;
3502 }
3503
3504 if (synchronous) {
3505 mTransactionPending = true;
3506 }
3507 if (syncInput) {
chaviw4fe36852019-04-15 16:25:49 -07003508 mPendingSyncInputWindows = true;
3509 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003510
Robert Carr238f4a22020-04-29 13:04:02 -07003511
Valerie Hau0779ded2019-03-19 12:43:04 -07003512 // applyTransactionState can be called by either the main SF thread or by
3513 // another process through setTransactionState. While a given process may wish
3514 // to wait on synchronous transactions, the main SF thread should never
3515 // be blocked. Therefore, we only wait if isMainThread is false.
3516 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003517 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3518 if (CC_UNLIKELY(err != NO_ERROR)) {
3519 // just in case something goes wrong in SF, return to the
3520 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003521 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3522 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003523 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003524 break;
3525 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003526 }
Ady Abrahambf1349c2020-06-12 14:26:18 -07003527 } else {
3528 // even if a transaction is not needed, we need to update VsyncModulator
3529 // about explicit early indications
3530 if (transactionStart == Scheduler::TransactionStart::EarlyStart ||
3531 transactionStart == Scheduler::TransactionStart::EarlyEnd) {
3532 mVSyncModulator->setTransactionStart(transactionStart);
3533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003534 }
3535}
3536
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003537uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3538 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3539 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003540
Mathias Agopiane57f2922012-08-09 16:29:12 -07003541 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003542 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3543
3544 const uint32_t what = s.what;
3545 if (what & DisplayState::eSurfaceChanged) {
3546 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3547 state.surface = s.surface;
3548 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003549 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003550 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003551 if (what & DisplayState::eLayerStackChanged) {
3552 if (state.layerStack != s.layerStack) {
3553 state.layerStack = s.layerStack;
3554 flags |= eDisplayTransactionNeeded;
3555 }
3556 }
3557 if (what & DisplayState::eDisplayProjectionChanged) {
3558 if (state.orientation != s.orientation) {
3559 state.orientation = s.orientation;
3560 flags |= eDisplayTransactionNeeded;
3561 }
3562 if (state.frame != s.frame) {
3563 state.frame = s.frame;
3564 flags |= eDisplayTransactionNeeded;
3565 }
3566 if (state.viewport != s.viewport) {
3567 state.viewport = s.viewport;
3568 flags |= eDisplayTransactionNeeded;
3569 }
3570 }
3571 if (what & DisplayState::eDisplaySizeChanged) {
3572 if (state.width != s.width) {
3573 state.width = s.width;
3574 flags |= eDisplayTransactionNeeded;
3575 }
3576 if (state.height != s.height) {
3577 state.height = s.height;
3578 flags |= eDisplayTransactionNeeded;
3579 }
3580 }
3581
Mathias Agopiane57f2922012-08-09 16:29:12 -07003582 return flags;
3583}
3584
Steven Thomasd4071902020-03-24 16:02:53 -07003585bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003586 IPCThreadState* ipc = IPCThreadState::self();
3587 const int pid = ipc->getCallingPid();
3588 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003589 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003590 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3591 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003592 return false;
3593 }
3594 return true;
3595}
3596
Marissa Wall3dad52d2019-03-22 14:03:19 -07003597uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003598 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3599 bool privileged,
3600 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003601 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003602
Valerie Hau9dab9732019-08-20 09:29:25 -07003603 for (auto& listener : s.listeners) {
3604 // note that startRegistration will not re-register if the listener has
3605 // already be registered for a prior surface control
3606 mTransactionCompletedThread.startRegistration(listener);
3607 listenerCallbacks.insert(listener);
3608 }
3609
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003610 sp<Layer> layer = nullptr;
3611 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003612 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003613 } else {
3614 // The client may provide us a null handle. Treat it as if the layer was removed.
3615 ALOGW("Attempt to set client state with a null layer handle");
3616 }
chaviw8b3871a2017-11-01 17:41:01 -07003617 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003618 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003619 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003620 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003621 }
chaviw8b3871a2017-11-01 17:41:01 -07003622 return 0;
3623 }
3624
chaviw8b3871a2017-11-01 17:41:01 -07003625 uint32_t flags = 0;
3626
Garfield Tan8a3083e2018-12-03 13:21:07 -08003627 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003628
3629 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3630 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003631 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003632 layer->pushPendingState();
3633 }
3634
Valerie Hau871d6352020-01-29 08:44:02 -08003635 // Only set by BLAST adapter layers
3636 if (what & layer_state_t::eProducerDisconnect) {
3637 layer->onDisconnect();
3638 }
3639
chaviw8b3871a2017-11-01 17:41:01 -07003640 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003641 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003642 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003643 }
chaviw8b3871a2017-11-01 17:41:01 -07003644 }
3645 if (what & layer_state_t::eLayerChanged) {
3646 // NOTE: index needs to be calculated before we update the state
3647 const auto& p = layer->getParent();
3648 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003649 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003650 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003651 mCurrentState.layersSortedByZ.removeAt(idx);
3652 mCurrentState.layersSortedByZ.add(layer);
3653 // we need traversal (state changed)
3654 // AND transaction (list changed)
3655 flags |= eTransactionNeeded|eTraversalNeeded;
3656 }
chaviw8b3871a2017-11-01 17:41:01 -07003657 } else {
3658 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003659 flags |= eTransactionNeeded|eTraversalNeeded;
3660 }
3661 }
chaviw8b3871a2017-11-01 17:41:01 -07003662 }
3663 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003664 // NOTE: index needs to be calculated before we update the state
3665 const auto& p = layer->getParent();
3666 if (p == nullptr) {
3667 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3668 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3669 mCurrentState.layersSortedByZ.removeAt(idx);
3670 mCurrentState.layersSortedByZ.add(layer);
3671 // we need traversal (state changed)
3672 // AND transaction (list changed)
3673 flags |= eTransactionNeeded|eTraversalNeeded;
3674 }
3675 } else {
3676 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3677 flags |= eTransactionNeeded|eTraversalNeeded;
3678 }
chaviw8b3871a2017-11-01 17:41:01 -07003679 }
3680 }
3681 if (what & layer_state_t::eSizeChanged) {
3682 if (layer->setSize(s.w, s.h)) {
3683 flags |= eTraversalNeeded;
3684 }
3685 }
3686 if (what & layer_state_t::eAlphaChanged) {
3687 if (layer->setAlpha(s.alpha))
3688 flags |= eTraversalNeeded;
3689 }
3690 if (what & layer_state_t::eColorChanged) {
3691 if (layer->setColor(s.color))
3692 flags |= eTraversalNeeded;
3693 }
Peiyong Lind3788632018-09-18 16:01:31 -07003694 if (what & layer_state_t::eColorTransformChanged) {
3695 if (layer->setColorTransform(s.colorTransform)) {
3696 flags |= eTraversalNeeded;
3697 }
3698 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003699 if (what & layer_state_t::eBackgroundColorChanged) {
3700 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3701 flags |= eTraversalNeeded;
3702 }
3703 }
chaviw8b3871a2017-11-01 17:41:01 -07003704 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003705 // TODO: b/109894387
3706 //
3707 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3708 // rotation. To see the problem observe that if we have a square parent, and a child
3709 // of the same size, then we rotate the child 45 degrees around it's center, the child
3710 // must now be cropped to a non rectangular 8 sided region.
3711 //
3712 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3713 // private API, and the WindowManager only uses rotation in one case, which is on a top
3714 // level layer in which cropping is not an issue.
3715 //
3716 // However given that abuse of rotation matrices could lead to surfaces extending outside
3717 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3718 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3719 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003720 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003721 flags |= eTraversalNeeded;
3722 }
3723 if (what & layer_state_t::eTransparentRegionChanged) {
3724 if (layer->setTransparentRegionHint(s.transparentRegion))
3725 flags |= eTraversalNeeded;
3726 }
3727 if (what & layer_state_t::eFlagsChanged) {
3728 if (layer->setFlags(s.flags, s.mask))
3729 flags |= eTraversalNeeded;
3730 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003731 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003732 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003733 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003734 if (what & layer_state_t::eCornerRadiusChanged) {
3735 if (layer->setCornerRadius(s.cornerRadius))
3736 flags |= eTraversalNeeded;
3737 }
Lucas Dupin130e55c2020-05-26 16:11:18 -07003738 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003739 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3740 }
chaviw8b3871a2017-11-01 17:41:01 -07003741 if (what & layer_state_t::eLayerStackChanged) {
3742 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3743 // We only allow setting layer stacks for top level layers,
3744 // everything else inherits layer stack from its parent.
3745 if (layer->hasParent()) {
3746 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003747 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003748 } else if (idx < 0) {
3749 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003750 "that also does not appear in the top level layer list. Something"
3751 " has gone wrong.",
3752 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003753 } else if (layer->setLayerStack(s.layerStack)) {
3754 mCurrentState.layersSortedByZ.removeAt(idx);
3755 mCurrentState.layersSortedByZ.add(layer);
3756 // we need traversal (state changed)
3757 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07003758 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003759 }
3760 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003761 if (what & layer_state_t::eDeferTransaction_legacy) {
3762 if (s.barrierHandle_legacy != nullptr) {
3763 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3764 } else if (s.barrierGbp_legacy != nullptr) {
3765 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003766 if (authenticateSurfaceTextureLocked(gbp)) {
3767 const auto& otherLayer =
3768 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003769 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003770 } else {
3771 ALOGE("Attempt to defer transaction to to an"
3772 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003773 }
3774 }
chaviw8b3871a2017-11-01 17:41:01 -07003775 // We don't trigger a traversal here because if no other state is
3776 // changed, we don't want this to cause any more work
3777 }
chaviw8b3871a2017-11-01 17:41:01 -07003778 if (what & layer_state_t::eReparentChildren) {
3779 if (layer->reparentChildren(s.reparentHandle)) {
3780 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003781 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003782 }
chaviw8b3871a2017-11-01 17:41:01 -07003783 if (what & layer_state_t::eDetachChildren) {
3784 layer->detachChildren();
3785 }
3786 if (what & layer_state_t::eOverrideScalingModeChanged) {
3787 layer->setOverrideScalingMode(s.overrideScalingMode);
3788 // We don't trigger a traversal here because if no other state is
3789 // changed, we don't want this to cause any more work
3790 }
Marissa Wall61c58622018-07-18 10:12:20 -07003791 if (what & layer_state_t::eTransformChanged) {
3792 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3793 }
3794 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3795 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3796 flags |= eTraversalNeeded;
3797 }
3798 if (what & layer_state_t::eCropChanged) {
3799 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3800 }
Marissa Wall861616d2018-10-22 12:52:23 -07003801 if (what & layer_state_t::eFrameChanged) {
3802 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3803 }
Marissa Wall61c58622018-07-18 10:12:20 -07003804 if (what & layer_state_t::eAcquireFenceChanged) {
3805 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3806 }
3807 if (what & layer_state_t::eDataspaceChanged) {
3808 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3809 }
3810 if (what & layer_state_t::eHdrMetadataChanged) {
3811 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3812 }
3813 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3814 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3815 }
3816 if (what & layer_state_t::eApiChanged) {
3817 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3818 }
3819 if (what & layer_state_t::eSidebandStreamChanged) {
3820 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3821 }
Robert Carr720e5062018-07-30 17:45:14 -07003822 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003823 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003824 layer->setInputInfo(s.inputInfo);
3825 flags |= eTraversalNeeded;
3826 } else {
3827 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3828 }
Robert Carr720e5062018-07-30 17:45:14 -07003829 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003830 if (what & layer_state_t::eMetadataChanged) {
3831 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3832 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003833 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3834 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3835 flags |= eTraversalNeeded;
3836 }
3837 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003838 if (what & layer_state_t::eShadowRadiusChanged) {
3839 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3840 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003841 if (what & layer_state_t::eFrameRateSelectionPriority) {
3842 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3843 flags |= eTraversalNeeded;
3844 }
3845 }
Steven Thomas3172e202020-01-06 19:25:30 -08003846 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003847 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3848 "SurfaceFlinger::setClientStateLocked") &&
3849 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3850 Layer::FrameRate::convertCompatibility(
3851 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003852 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003853 }
Steven Thomas3172e202020-01-06 19:25:30 -08003854 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003855 if (what & layer_state_t::eFixedTransformHintChanged) {
3856 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
3857 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
3858 }
3859 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003860 // This has to happen after we reparent children because when we reparent to null we remove
3861 // child layers from current state and remove its relative z. If the children are reparented in
3862 // the same transaction, then we have to make sure we reparent the children first so we do not
3863 // lose its relative z order.
3864 if (what & layer_state_t::eReparent) {
3865 bool hadParent = layer->hasParent();
3866 if (layer->reparent(s.parentHandleForChild)) {
3867 if (!hadParent) {
3868 mCurrentState.layersSortedByZ.remove(layer);
3869 }
3870 flags |= eTransactionNeeded | eTraversalNeeded;
3871 }
3872 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003873 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003874 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3875 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003876 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3877 }
3878 }
Marissa Wall78b72202019-03-15 14:58:34 -07003879 bool bufferChanged = what & layer_state_t::eBufferChanged;
3880 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3881 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003882 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003883 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003884 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3885 if (success) {
3886 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3887 success = ClientCache::getInstance()
3888 .registerErasedRecipient(s.cachedBuffer,
3889 wp<ClientCache::ErasedRecipient>(this));
3890 if (!success) {
3891 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3892 }
3893 }
Marissa Wall78b72202019-03-15 14:58:34 -07003894 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003895 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003896 } else if (bufferChanged) {
3897 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003898 }
Marissa Wall78b72202019-03-15 14:58:34 -07003899 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003900 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3901 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003902 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003903 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003904 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003905 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3906 // Do not put anything that updates layer state or modifies flags after
3907 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003908 return flags;
3909}
3910
chaviw273171b2018-12-26 11:46:30 -08003911uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3912 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003913 if (inputWindowCommands.syncInputWindows) {
3914 flags |= eTraversalNeeded;
3915 }
3916
Vishnu Nairec0ab382019-02-13 15:32:56 -08003917 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003918 return flags;
3919}
3920
chaviwfe94a222019-08-21 13:52:59 -07003921status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3922 sp<IBinder>* outHandle) {
3923 if (!mirrorFromHandle) {
3924 return NAME_NOT_FOUND;
3925 }
3926
3927 sp<Layer> mirrorLayer;
3928 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003929 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003930
3931 {
3932 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003933 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003934 if (!mirrorFrom) {
3935 return NAME_NOT_FOUND;
3936 }
3937
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003938 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3939 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003940 if (result != NO_ERROR) {
3941 return result;
3942 }
3943
3944 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3945 }
3946
Vishnu Nair6213bd92020-05-08 17:42:25 -07003947 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false,
3948 nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07003949}
3950
Marissa Wall2d814fb2019-04-09 18:52:57 +00003951status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3952 uint32_t h, PixelFormat format, uint32_t flags,
3953 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003954 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003955 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3956 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003957 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003958 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003959 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003960 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003961 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003962
Robert Carrc0df3122019-04-11 13:18:21 -07003963 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3964 "Expected only one of parentLayer or parentHandle to be non-null. "
3965 "Programmer error?");
3966
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003967 status_t result = NO_ERROR;
3968
3969 sp<Layer> layer;
3970
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003971 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003972
Evan Roskya1f1e152019-01-24 16:17:46 -08003973 bool primaryDisplayOnly = false;
3974
3975 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3976 // TODO b/64227542
3977 if (metadata.has(METADATA_WINDOW_TYPE)) {
3978 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3979 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003980 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003981 primaryDisplayOnly = true;
3982 }
3983 }
3984
Mathias Agopian3165cc22012-08-08 19:42:09 -07003985 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003986 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003987 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3988 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003989
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003990 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003991 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003992 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003993 std::move(metadata), handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003994 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003995 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003996 // check if buffer size is set for color layer.
3997 if (w > 0 || h > 0) {
3998 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3999 int(w), int(h));
4000 return BAD_VALUE;
4001 }
4002
Vishnu Nairfa247b12020-02-11 08:58:26 -08004003 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
4004 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004005 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004006 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004007 // check if buffer size is set for container layer.
4008 if (w > 0 || h > 0) {
4009 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4010 int(w), int(h));
4011 return BAD_VALUE;
4012 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004013 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
4014 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004015 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004016 default:
4017 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018 break;
4019 }
4020
Dan Stoza7d89d062015-04-30 13:29:25 -07004021 if (result != NO_ERROR) {
4022 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004023 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004024
Evan Roskya1f1e152019-01-24 16:17:46 -08004025 if (primaryDisplayOnly) {
4026 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004027 }
4028
Robert Carrb89ea9d2018-12-10 13:01:14 -08004029 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004030 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004031 addToCurrentState, outTransformHint);
Dan Stoza7d89d062015-04-30 13:29:25 -07004032 if (result != NO_ERROR) {
4033 return result;
4034 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004035 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004036
4037 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004038 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004039}
4040
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004041std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
4042 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06004043
4044 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004045 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004046
Dan Stoza436ccf32018-06-21 12:10:12 -07004047 // Grab the state lock since we're accessing mCurrentState
4048 Mutex::Autolock lock(mStateLock);
4049
Cody Northropbc755282017-03-31 12:00:08 -06004050 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004051 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06004052 while (matchFound) {
4053 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08004054 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004055 if (layer->getName() == uniqueName) {
4056 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004057 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004058 }
4059 });
4060 }
4061
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004062 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004063 return uniqueName;
4064}
4065
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004066status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07004067 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004068 LayerMetadata metadata, PixelFormat& format,
4069 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004070 sp<IGraphicBufferProducer>* gbp,
4071 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004072 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004073 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004074 case PIXEL_FORMAT_TRANSPARENT:
4075 case PIXEL_FORMAT_TRANSLUCENT:
4076 format = PIXEL_FORMAT_RGBA_8888;
4077 break;
4078 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004079 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004080 break;
4081 }
4082
chaviwb4c6e582019-08-16 14:35:07 -07004083 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004084 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004085 args.textureName = getNewTexture();
4086 {
4087 // Grab the SF state lock during this since it's the only safe way to access
4088 // RenderEngine when creating a BufferLayerConsumer
4089 // TODO: Check if this lock is still needed here
4090 Mutex::Autolock lock(mStateLock);
4091 layer = getFactory().createBufferQueueLayer(args);
4092 }
4093
Marissa Wallfd668622018-05-10 10:21:13 -07004094 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004095 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004096 *handle = layer->getHandle();
4097 *gbp = layer->getProducer();
4098 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004099 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004100
Marissa Wallfd668622018-05-10 10:21:13 -07004101 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004102 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004103}
4104
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004105status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004106 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004107 LayerMetadata metadata, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004108 sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004109 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004110 args.textureName = getNewTexture();
4111 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07004112 *handle = layer->getHandle();
4113 *outLayer = layer;
4114
4115 return NO_ERROR;
4116}
4117
Vishnu Nairfa247b12020-02-11 08:58:26 -08004118status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4119 uint32_t h, uint32_t flags, LayerMetadata metadata,
4120 sp<IBinder>* handle, sp<Layer>* outLayer) {
4121 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004122 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004123 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004124 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004125}
4126
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004127status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004128 uint32_t w, uint32_t h, uint32_t flags,
4129 LayerMetadata metadata, sp<IBinder>* handle,
4130 sp<Layer>* outLayer) {
4131 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004132 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004133 *handle = (*outLayer)->getHandle();
4134 return NO_ERROR;
4135}
4136
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004137void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004138 mLayersPendingRemoval.add(layer);
4139 mLayersRemoved = true;
4140 setTransactionFlags(eTransactionNeeded);
4141}
4142
Robert Carr695d5282018-12-18 15:27:58 -08004143void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004144{
Robert Carr2e102c92018-10-23 12:11:15 -07004145 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004146 // If a layer has a parent, we allow it to out-live it's handle
4147 // with the idea that the parent holds a reference and will eventually
4148 // be cleaned up. However no one cleans up the top-level so we do so
4149 // here.
4150 if (layer->getParent() == nullptr) {
4151 mCurrentState.layersSortedByZ.remove(layer);
4152 }
4153 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004154
4155 auto it = mLayersByLocalBinderToken.begin();
4156 while (it != mLayersByLocalBinderToken.end()) {
4157 if (it->second == layer) {
4158 it = mLayersByLocalBinderToken.erase(it);
4159 } else {
4160 it++;
4161 }
4162 }
4163
Robert Carr695d5282018-12-18 15:27:58 -08004164 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004165}
4166
Mathias Agopianb60314a2012-04-10 22:09:54 -07004167// ---------------------------------------------------------------------------
4168
Andy McFadden13a082e2012-08-24 10:16:42 -07004169void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004170 const auto display = getDefaultDisplayDeviceLocked();
4171 if (!display) return;
4172
4173 const sp<IBinder> token = display->getDisplayToken().promote();
4174 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004175
Jesse Hall01e29052013-02-19 16:13:35 -08004176 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004177 Vector<ComposerState> state;
4178 Vector<DisplayState> displays;
4179 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004180 d.what = DisplayState::eDisplayProjectionChanged |
4181 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004182 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004183 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004184 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004185 d.frame.makeInvalid();
4186 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004187 d.width = 0;
4188 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004189 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004190 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4191 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004192
Peiyong Lin65248e02020-04-18 21:15:07 -07004193 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004194
Dominik Laskowski83b88212018-12-11 13:34:06 -08004195 const nsecs_t vsyncPeriod = getVsyncPeriod();
4196 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004197
Brian Andersond0010582017-03-07 13:20:31 -08004198 // Use phase of 0 since phase is not known.
4199 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004200 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004201 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004202}
4203
4204void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004205 // Async since we may be called from the main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004206 static_cast<void>(schedule([this]() MAIN_THREAD { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004207}
4208
Peiyong Lin65248e02020-04-18 21:15:07 -07004209void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004210 if (display->isVirtual()) {
4211 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004212 return;
4213 }
4214
Dominik Laskowski075d3172018-05-24 15:50:06 -07004215 const auto displayId = display->getId();
4216 LOG_ALWAYS_FATAL_IF(!displayId);
4217
Dominik Laskowski34157762018-10-31 13:07:19 -07004218 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004219
Peiyong Lin65248e02020-04-18 21:15:07 -07004220 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004221 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004222 return;
4223 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004224
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004225 display->setPowerMode(mode);
4226
Lloyd Pique4dccc412018-01-22 17:21:36 -08004227 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004228 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004229 }
4230
Peiyong Lin65248e02020-04-18 21:15:07 -07004231 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004232 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4233 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4234 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004235 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004236 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004237 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004238 mScheduler->onScreenAcquired(mAppConnectionHandle);
4239 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004240 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004241
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004242 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004243 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004244 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004245 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004246 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004247 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4248 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004249 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004250 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004251 mScheduler->disableHardwareVsync(true);
4252 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004253 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004254
Ady Abraham27c70212019-06-11 10:52:26 -07004255 // Make sure HWVsync is disabled before turning off the display
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004256 getHwComposer().setVsyncEnabled(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004257
Dominik Laskowski075d3172018-05-24 15:50:06 -07004258 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004259 mVisibleRegionsDirty = true;
4260 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004261 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004262 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004263 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004264 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004265 mScheduler->onScreenAcquired(mAppConnectionHandle);
4266 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004267 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004268 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004269 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004270 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004271 mScheduler->disableHardwareVsync(true);
4272 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004273 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004274 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004275 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004276 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004277 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004278 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004279
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004280 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004281 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004282 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004283 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004284 }
4285
Dominik Laskowski34157762018-10-31 13:07:19 -07004286 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004287}
4288
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004289void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004290 schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004291 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004292 if (!display) {
4293 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4294 displayToken.get());
4295 } else if (display->isVirtual()) {
4296 ALOGW("Attempt to set power mode %d for virtual display", mode);
4297 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004298 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004299 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004300 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004301}
4302
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004303status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004304 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004305
Mathias Agopianbd115332013-04-18 16:41:04 -07004306 IPCThreadState* ipc = IPCThreadState::self();
4307 const int pid = ipc->getCallingPid();
4308 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004309
Mathias Agopianbd115332013-04-18 16:41:04 -07004310 if ((uid != AID_SHELL) &&
4311 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004312 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4313 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004314 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004315 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004316 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004317 {"--dispsync"s,
4318 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004319 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004320 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4321 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4322 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4323 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4324 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4325 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004326 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004327 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4328 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004329
Dominik Laskowskic2867142019-01-21 11:33:38 -08004330 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004331
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004332 bool dumpLayers = true;
4333 {
4334 TimedLock lock(mStateLock, s2ns(1), __FUNCTION__);
4335 if (!lock.locked()) {
4336 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4337 strerror(-lock.status), lock.status);
4338 }
4339
4340 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4341 (it->second)(args, asProto, result);
4342 dumpLayers = false;
4343 } else if (!asProto) {
4344 dumpAllLocked(args, result);
4345 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004346 }
4347
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004348 if (dumpLayers) {
Dominik Laskowski46470112019-08-02 13:13:11 -07004349 const LayersProto layersProto = dumpProtoFromMainThread();
4350 if (asProto) {
4351 result.append(layersProto.SerializeAsString());
4352 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004353 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004354 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4355 result.append(LayerProtoParser::layerTreeToString(layerTree));
4356 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004357 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004358 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004359 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004360 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004361 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004362 return NO_ERROR;
4363}
4364
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004365status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4366 if (asProto && mTracing.isEnabled()) {
4367 mTracing.writeToFileAsync();
4368 }
4369
4370 return doDump(fd, DumpArgs(), asProto);
4371}
4372
Dominik Laskowskic2867142019-01-21 11:33:38 -08004373void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004374 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004375 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004376}
4377
Dominik Laskowskic2867142019-01-21 11:33:38 -08004378void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004379 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004380
Dominik Laskowskic2867142019-01-21 11:33:38 -08004381 if (args.size() > 1) {
4382 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004383 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004384 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004385 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004386 }
Robert Carr2047fae2016-11-28 14:09:09 -08004387 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004388 } else {
4389 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004390 }
4391}
4392
Dominik Laskowskic2867142019-01-21 11:33:38 -08004393void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004394 const bool clearAll = args.size() < 2;
4395 const auto name = clearAll ? String8() : String8(args[1]);
4396
Edgar Arriaga844fa672020-01-16 14:21:42 -08004397 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004398 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004399 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004400 }
Robert Carr2047fae2016-11-28 14:09:09 -08004401 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004402
Svetoslavd85084b2014-03-20 10:28:31 -07004403 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004404}
4405
Dominik Laskowskic2867142019-01-21 11:33:38 -08004406void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4407 mTimeStats->parseArgs(asProto, args, result);
4408}
4409
Jamie Gennis6547ff42013-07-16 20:12:42 -07004410// This should only be called from the main thread. Otherwise it would need
4411// the lock and should use mCurrentState rather than mDrawingState.
4412void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004413 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004414 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004415 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004416
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004417 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004418}
4419
Yiwei Zhang5434a782018-12-05 18:06:32 -08004420void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004421 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004422
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004423 if (isLayerTripleBufferingDisabled())
4424 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004425
Yiwei Zhang5434a782018-12-05 18:06:32 -08004426 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4427 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4428 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4429 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4430 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4431 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004432 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004433}
4434
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004435void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004436 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004437
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004438 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004439 result.append("\n");
4440
Ady Abraham9e16a482019-12-03 17:19:41 -08004441 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004442 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004443 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004444 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004445
Steven Thomasd4071902020-03-24 16:02:53 -07004446 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004447 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004448 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004449 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4450 policy.defaultConfig.value(), policy.primaryRange.min, policy.primaryRange.max,
4451 policy.appRequestRange.min, policy.appRequestRange.max);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004452 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4453 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004454 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4455 if (currentPolicy != policy) {
4456 StringAppendF(&result,
4457 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004458 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4459 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
4460 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
4461 currentPolicy.appRequestRange.max);
Ady Abraham07e54702020-04-16 15:05:37 -07004462 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004463
Ana Krulecc2870422019-01-29 19:00:58 -08004464 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004465 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004466}
4467
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4469 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004470 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4471 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004472 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004473 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004474 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004475 }
David Sodman4a36e932017-11-07 14:29:47 -08004476 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004477 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004478 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004479 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4480 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004481}
4482
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004483void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4484 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004485 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4486 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004487 for (const auto& segment : history) {
4488 if (!segment.usedThirdBuffer) {
4489 stats.twoBufferTime += segment.totalTime;
4490 }
4491 if (segment.occupancyAverage < 1.0f) {
4492 stats.doubleBufferedTime += segment.totalTime;
4493 } else if (segment.occupancyAverage < 2.0f) {
4494 stats.tripleBufferedTime += segment.totalTime;
4495 }
4496 ++stats.numSegments;
4497 stats.totalTime += segment.totalTime;
4498 }
4499}
4500
Yiwei Zhang5434a782018-12-05 18:06:32 -08004501void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4502 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004503
4504 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4505 const size_t count = currentLayers.size();
4506 for (size_t i=0 ; i<count ; i++) {
4507 currentLayers[i]->dumpFrameEvents(result);
4508 }
4509}
4510
Yiwei Zhang5434a782018-12-05 18:06:32 -08004511void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004512 result.append("Buffering stats:\n");
4513 result.append(" [Layer name] <Active time> <Two buffer> "
4514 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004515 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004516 typedef std::tuple<std::string, float, float, float> BufferTuple;
4517 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004518 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004519 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004520 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004521 if (stats.numSegments == 0) {
4522 continue;
4523 }
4524 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4525 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4526 stats.totalTime;
4527 float doubleBufferRatio = static_cast<float>(
4528 stats.doubleBufferedTime) / stats.totalTime;
4529 float tripleBufferRatio = static_cast<float>(
4530 stats.tripleBufferedTime) / stats.totalTime;
4531 sorted.insert({activeTime, {name, twoBufferRatio,
4532 doubleBufferRatio, tripleBufferRatio}});
4533 }
4534 for (const auto& sortedPair : sorted) {
4535 float activeTime = sortedPair.first;
4536 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004537 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4538 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004539 }
4540 result.append("\n");
4541}
4542
Yiwei Zhang5434a782018-12-05 18:06:32 -08004543void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004544 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004545 const auto displayId = display->getId();
4546 if (!displayId) {
4547 continue;
4548 }
4549 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004550 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004551 continue;
4552 }
4553
Yiwei Zhang5434a782018-12-05 18:06:32 -08004554 StringAppendF(&result,
4555 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4556 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004557 uint8_t port;
4558 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004559 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004560 result.append("no identification data\n");
4561 continue;
4562 }
4563
4564 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004565 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004566 continue;
4567 }
4568
4569 const auto edid = parseEdid(data);
4570 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004571 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004572 continue;
4573 }
4574
Yiwei Zhang5434a782018-12-05 18:06:32 -08004575 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004576 result.append(edid->displayName.data(), edid->displayName.length());
4577 result.append("\"\n");
4578 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004579}
4580
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004581void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4582 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004583 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004584 uint8_t port;
4585 DisplayIdentificationData data;
4586
4587 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4588 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4589 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4590 }
4591}
4592
Yiwei Zhang5434a782018-12-05 18:06:32 -08004593void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004594 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004595 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4596 StringAppendF(&result, "DisplayColorSetting: %s\n",
4597 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004598
4599 // TODO: print out if wide-color mode is active or not
4600
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004601 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004602 const auto displayId = display->getId();
4603 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004604 continue;
4605 }
4606
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004608 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004609 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004610 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004611 }
4612
Lloyd Pique32cbe282018-10-19 13:09:22 -07004613 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004614 StringAppendF(&result, " Current color mode: %s (%d)\n",
4615 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004616 }
4617 result.append("\n");
4618}
4619
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004620LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4621 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004622 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004623
chaviw1d044282017-09-27 12:19:28 -07004624 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004625 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004626 layer->writeToProto(layersProto, traceFlags, display.get());
chaviw08f3cb22020-01-13 13:17:21 -08004627 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004628
chaviw1d044282017-09-27 12:19:28 -07004629 return layersProto;
4630}
4631
Alec Mouri6b9e9912020-01-21 10:50:24 -08004632void SurfaceFlinger::dumpHwc(std::string& result) const {
4633 getHwComposer().dump(result);
4634}
4635
Vishnu Nair0f085c62019-08-30 08:49:12 -07004636void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4637 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4638 // it.
4639 LayerProto* rootProto = layersProto.add_layers();
4640 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4641 rootProto->set_id(offscreenRootLayerId);
4642 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004643 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004644
4645 for (Layer* offscreenLayer : mOffscreenLayers) {
4646 // Add layer as child of the fake root
4647 rootProto->add_children(offscreenLayer->sequence);
4648
4649 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004650 LayerProto* layerProto =
4651 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004652 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004653 }
4654}
4655
Vishnu Nair8406fd72019-07-30 11:29:31 -07004656LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004657 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004658}
4659
Vishnu Nair0f085c62019-08-30 08:49:12 -07004660void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4661 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004662 result.append(schedule([this] {
4663 std::string result;
4664 for (Layer* offscreenLayer : mOffscreenLayers) {
4665 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4666 [&](Layer* layer) {
4667 layer->dumpCallingUidPid(result);
4668 });
4669 }
4670 return result;
4671 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004672}
4673
Dominik Laskowskic2867142019-01-21 11:33:38 -08004674void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4675 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004676 Colorizer colorizer(colorize);
4677
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004678 // figure out if we're stuck somewhere
4679 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004680 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004681 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4682
4683 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004684 * Dump library configuration.
4685 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004686
4687 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004688 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004689 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004690 appendSfConfigString(result);
4691 appendUiConfigString(result);
4692 appendGuiConfigString(result);
4693 result.append("\n");
4694
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004695 result.append("\nDisplay identification data:\n");
4696 dumpDisplayIdentificationData(result);
4697
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004698 result.append("\nWide-Color information:\n");
4699 dumpWideColorInfo(result);
4700
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004701 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004702 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004703 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004704 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004705 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004706
Andy McFadden41d67d72014-04-25 16:58:34 -07004707 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004708 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004709 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004710 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004711 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004712
Dan Stozab90cf072015-03-05 11:05:59 -08004713 dumpStaticScreenStats(result);
4714 result.append("\n");
4715
Alec Mouri40189b02019-03-05 15:07:54 -08004716 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4717 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4718 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004719
Dan Stozae77c7662016-05-13 11:37:28 -07004720 dumpBufferingStats(result);
4721
Andy McFadden4803b742012-09-24 19:07:20 -07004722 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004723 * Dump the visible layer list
4724 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004725 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004726 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004727 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4728 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004729 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004730
Chia-I Wu2f884132018-09-13 15:17:58 -07004731 {
Lloyd Pique207def92019-02-28 16:09:52 -08004732 StringAppendF(&result, "Composition layers\n");
4733 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004734 auto* compositionState = layer->getCompositionState();
4735 if (!compositionState) return;
4736
4737 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4738 layer->getDebugName() ? layer->getDebugName()
4739 : "<unknown>");
4740 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004741 });
4742 }
4743
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004744 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004745 * Dump Display state
4746 */
4747
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004748 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004749 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004750 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004751 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004752 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004753 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004754 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004755
4756 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004757 * Dump CompositionEngine state
4758 */
4759
4760 mCompositionEngine->dump(result);
4761
4762 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004763 * Dump SurfaceFlinger global state
4764 */
4765
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004766 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004767 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004768 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004769
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004770 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004771
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004772 DebugEGLImageTracker::getInstance()->dump(result);
4773
Dominik Laskowski075d3172018-05-24 15:50:06 -07004774 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004775 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4776 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004777 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4778 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004779 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004780 StringAppendF(&result,
4781 " transaction-flags : %08x\n"
4782 " gpu_to_cpu_unsupported : %d\n",
4783 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004784
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004785 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004786 displayId && getHwComposer().isConnected(*displayId)) {
4787 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004788 StringAppendF(&result,
4789 " refresh-rate : %f fps\n"
4790 " x-dpi : %f\n"
4791 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004792 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4793 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004794 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004795
Yiwei Zhang5434a782018-12-05 18:06:32 -08004796 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004797
Dan Stozae22aec72016-08-01 13:20:59 -07004798 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004799 * Tracing state
4800 */
4801 mTracing.dump(result);
4802 result.append("\n");
4803
4804 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004805 * HWC layer minidump
4806 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004807 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004808 const auto displayId = display->getId();
4809 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004810 continue;
4811 }
4812
Yiwei Zhang5434a782018-12-05 18:06:32 -08004813 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004814 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004815
4816 const DisplayDevice& ref = *display;
4817 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07004818 result.append("\n");
4819 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004820
4821 /*
4822 * Dump HWComposer state
4823 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004824 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004825 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004826 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004827 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004828 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004829 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004830
4831 /*
4832 * Dump gralloc state
4833 */
4834 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4835 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004836
4837 /*
4838 * Dump VrFlinger state if in use.
4839 */
4840 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4841 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004842 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004843 result.append("\n");
4844 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004845
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004846 result.append(mTimeStats->miniDump());
4847 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004848}
4849
Chia-I Wu28f320b2018-05-03 11:02:56 -07004850void SurfaceFlinger::updateColorMatrixLocked() {
4851 mat4 colorMatrix;
4852 if (mGlobalSaturationFactor != 1.0f) {
4853 // Rec.709 luma coefficients
4854 float3 luminance{0.213f, 0.715f, 0.072f};
4855 luminance *= 1.0f - mGlobalSaturationFactor;
4856 mat4 saturationMatrix = mat4(
4857 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4858 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4859 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4860 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4861 );
4862 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4863 } else {
4864 colorMatrix = mClientColorMatrix * mDaltonizer();
4865 }
4866
4867 if (mCurrentState.colorMatrix != colorMatrix) {
4868 mCurrentState.colorMatrix = colorMatrix;
4869 mCurrentState.colorMatrixChanged = true;
4870 setTransactionFlags(eTransactionNeeded);
4871 }
4872}
4873
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004874status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004875#pragma clang diagnostic push
4876#pragma clang diagnostic error "-Wswitch-enum"
4877 switch (static_cast<ISurfaceComposerTag>(code)) {
4878 // These methods should at minimum make sure that the client requested
4879 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004880 case BOOT_FINISHED:
4881 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004882 case CREATE_DISPLAY:
4883 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004884 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004885 case GET_ANIMATION_FRAME_STATS:
4886 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004887 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004888 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004889 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004890 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4891 case SET_AUTO_LOW_LATENCY_MODE:
4892 case GET_GAME_CONTENT_TYPE_SUPPORT:
4893 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004894 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004895 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004896 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004897 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004898 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004899 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004900 case SET_GLOBAL_SHADOW_SETTINGS:
4901 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4902 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4903 // necessary permission dynamically. Don't use the permission cache for this check.
4904 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4905 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004906 IPCThreadState* ipc = IPCThreadState::self();
4907 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4908 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004909 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004910 }
Robert Carr1db73f62016-12-21 12:58:51 -08004911 return OK;
4912 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004913 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004914 IPCThreadState* ipc = IPCThreadState::self();
4915 const int pid = ipc->getCallingPid();
4916 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004917 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4918 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004919 return PERMISSION_DENIED;
4920 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004921 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004922 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004923 // Used by apps to hook Choreographer to SurfaceFlinger.
4924 case CREATE_DISPLAY_EVENT_CONNECTION:
4925 // The following calls are currently used by clients that do not
4926 // request necessary permissions. However, they do not expose any secret
4927 // information, so it is OK to pass them.
4928 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004929 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004930 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004931 case GET_PHYSICAL_DISPLAY_IDS:
4932 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004933 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004934 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004935 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004936 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004937 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004938 case GET_DISPLAY_STATS:
4939 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4940 // Calling setTransactionState is safe, because you need to have been
4941 // granted a reference to Client* and Handle* to do anything with it.
4942 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004943 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004944 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004945 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004946 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004947 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004948 // setFrameRate() is deliberately available for apps to call without any
4949 // special permissions.
4950 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004951 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4952 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004953 return OK;
4954 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004955 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004956 case CAPTURE_SCREEN:
4957 case ADD_REGION_SAMPLING_LISTENER:
4958 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004959 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004960 IPCThreadState* ipc = IPCThreadState::self();
4961 const int pid = ipc->getCallingPid();
4962 const int uid = ipc->getCallingUid();
4963 if ((uid != AID_GRAPHICS) &&
4964 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4965 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4966 return PERMISSION_DENIED;
4967 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004968 return OK;
4969 }
chaviw93df2ea2019-04-30 16:45:12 -07004970 case CAPTURE_SCREEN_BY_ID: {
4971 IPCThreadState* ipc = IPCThreadState::self();
4972 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004973 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004974 return OK;
4975 }
4976 return PERMISSION_DENIED;
4977 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004978 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004979
4980 // These codes are used for the IBinder protocol to either interrogate the recipient
4981 // side of the transaction for its canonical interface descriptor or to dump its state.
4982 // We let them pass by default.
4983 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4984 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4985 code == IBinder::SYSPROPS_TRANSACTION) {
4986 return OK;
4987 }
Ady Abraham07e54702020-04-16 15:05:37 -07004988 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004989 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004990 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004991 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4992 return OK;
4993 }
4994 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4995 return PERMISSION_DENIED;
4996#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004997}
4998
Ana Krulec13be8ad2018-08-21 02:43:56 +00004999status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5000 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005001 status_t credentialCheck = CheckTransactCodeCredentials(code);
5002 if (credentialCheck != OK) {
5003 return credentialCheck;
5004 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005005
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005006 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5007 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005008 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005009 IPCThreadState* ipc = IPCThreadState::self();
5010 const int uid = ipc->getCallingUid();
5011 if (CC_UNLIKELY(uid != AID_SYSTEM
5012 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005013 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005014 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005015 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005016 return PERMISSION_DENIED;
5017 }
5018 int n;
5019 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005020 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005021 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005022 return NO_ERROR;
5023 case 1002: // SHOW_UPDATES
5024 n = data.readInt32();
5025 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005026 invalidateHwcGeometry();
5027 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005028 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005029 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005030 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005031 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005032 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005033 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005034 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005035 setTransactionFlags(
5036 eTransactionNeeded|
5037 eDisplayTransactionNeeded|
5038 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005039 return NO_ERROR;
5040 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005041 case 1006:{ // send empty update
5042 signalRefresh();
5043 return NO_ERROR;
5044 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005045 case 1008: // toggle use of hw composer
5046 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005047 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005048 invalidateHwcGeometry();
5049 repaintEverything();
5050 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005051 case 1009: // toggle use of transform hint
5052 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005053 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005054 invalidateHwcGeometry();
5055 repaintEverything();
5056 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005057 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005058 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005059 reply->writeInt32(0);
5060 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005061 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005062 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005063 return NO_ERROR;
5064 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005065 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005066 if (!display) {
5067 return NAME_NOT_FOUND;
5068 }
5069
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005070 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005071 return NO_ERROR;
5072 }
5073 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005074 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005075 // daltonize
5076 n = data.readInt32();
5077 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005078 case 1:
5079 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5080 break;
5081 case 2:
5082 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5083 break;
5084 case 3:
5085 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5086 break;
5087 default:
5088 mDaltonizer.setType(ColorBlindnessType::None);
5089 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005090 }
5091 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005092 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005093 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005094 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005095 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005096
5097 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005098 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005099 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005100 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005101 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005102 // apply a color matrix
5103 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005104 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005105 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005106 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005107 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005108 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005109 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005110 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005111 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005112 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005113 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005114
5115 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5116 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005117 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005118 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5119 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5120 }
5121
Chia-I Wu28f320b2018-05-03 11:02:56 -07005122 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005123 return NO_ERROR;
5124 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005125 case 1016: { // Unused.
5126 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005127 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005128 case 1017: {
5129 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005130 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005131 return NO_ERROR;
5132 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005133 case 1018: { // Modify Choreographer's phase offset
5134 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005135 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005136 return NO_ERROR;
5137 }
5138 case 1019: { // Modify SurfaceFlinger's phase offset
5139 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005140 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005141 return NO_ERROR;
5142 }
Irvel468051e2016-06-13 16:44:44 -07005143 case 1020: { // Layer updates interceptor
5144 n = data.readInt32();
5145 if (n) {
5146 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005147 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005148 }
5149 else{
5150 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005151 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005152 }
5153 return NO_ERROR;
5154 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005155 case 1021: { // Disable HWC virtual displays
5156 n = data.readInt32();
5157 mUseHwcVirtualDisplays = !n;
5158 return NO_ERROR;
5159 }
Romain Guy0147a172017-06-01 13:53:56 -07005160 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005161 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005162 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005163
Chia-I Wu28f320b2018-05-03 11:02:56 -07005164 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005165 return NO_ERROR;
5166 }
Romain Guy54f154a2017-10-24 21:40:32 +01005167 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005168 int32_t colorMode;
5169
Chia-I Wu0d711262018-05-21 15:19:35 -07005170 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005171 if (data.readInt32(&colorMode) == NO_ERROR) {
5172 mForceColorMode = static_cast<ColorMode>(colorMode);
5173 }
Romain Guy54f154a2017-10-24 21:40:32 +01005174 invalidateHwcGeometry();
5175 repaintEverything();
5176 return NO_ERROR;
5177 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005178 // Deprecate, use 1030 to check whether the device is color managed.
5179 case 1024: {
5180 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005181 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005182 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005183 n = data.readInt32();
5184 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005185 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005186 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005187 reply->writeInt32(NO_ERROR);
5188 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005189 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005190 mTracingEnabledChanged = mTracing.disable();
5191 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005192 reply->writeInt32(mTracing.writeToFile());
5193 } else {
5194 reply->writeInt32(NO_ERROR);
5195 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005196 }
5197 return NO_ERROR;
5198 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005199 case 1026: { // Get layer tracing status
5200 reply->writeBool(mTracing.isEnabled());
5201 return NO_ERROR;
5202 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005203 // Is a DisplayColorSetting supported?
5204 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005205 const auto display = getDefaultDisplayDevice();
5206 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005207 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005208 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005209
5210 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5211 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005212 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005213 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005214 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005215 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005216 reply->writeBool(true);
5217 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005218 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005219 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005220 break;
5221 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005222 reply->writeBool(
5223 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005224 break;
5225 }
5226 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005227 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005228 // Is VrFlinger active?
5229 case 1028: {
5230 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005231 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005232 return NO_ERROR;
5233 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005234 // Set buffer size for SF tracing (value in KB)
5235 case 1029: {
5236 n = data.readInt32();
5237 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5238 ALOGW("Invalid buffer size: %d KB", n);
5239 reply->writeInt32(BAD_VALUE);
5240 return BAD_VALUE;
5241 }
5242
5243 ALOGD("Updating trace buffer to %d KB", n);
5244 mTracing.setBufferSize(n * 1024);
5245 reply->writeInt32(NO_ERROR);
5246 return NO_ERROR;
5247 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005248 // Is device color managed?
5249 case 1030: {
5250 reply->writeBool(useColorManagement);
5251 return NO_ERROR;
5252 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005253 // Override default composition data space
5254 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5255 // && adb shell stop zygote && adb shell start zygote
5256 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5257 // adb shell stop zygote && adb shell start zygote
5258 case 1031: {
5259 Mutex::Autolock _l(mStateLock);
5260 n = data.readInt32();
5261 if (n) {
5262 n = data.readInt32();
5263 if (n) {
5264 Dataspace dataspace = static_cast<Dataspace>(n);
5265 if (!validateCompositionDataspace(dataspace)) {
5266 return BAD_VALUE;
5267 }
5268 mDefaultCompositionDataspace = dataspace;
5269 }
5270 n = data.readInt32();
5271 if (n) {
5272 Dataspace dataspace = static_cast<Dataspace>(n);
5273 if (!validateCompositionDataspace(dataspace)) {
5274 return BAD_VALUE;
5275 }
5276 mWideColorGamutCompositionDataspace = dataspace;
5277 }
5278 } else {
5279 // restore composition data space.
5280 mDefaultCompositionDataspace = defaultCompositionDataspace;
5281 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5282 }
5283 return NO_ERROR;
5284 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005285 // Set trace flags
5286 case 1033: {
5287 n = data.readUint32();
5288 ALOGD("Updating trace flags to 0x%x", n);
5289 mTracing.setTraceFlags(n);
5290 reply->writeInt32(NO_ERROR);
5291 return NO_ERROR;
5292 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005293 case 1034: {
Dominik Laskowski20134642020-04-20 22:36:44 -07005294 switch (n = data.readInt32()) {
5295 case 0:
5296 case 1:
5297 enableRefreshRateOverlay(static_cast<bool>(n));
5298 break;
5299 default: {
5300 Mutex::Autolock lock(mStateLock);
5301 reply->writeBool(mRefreshRateOverlay != nullptr);
5302 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005303 }
5304 return NO_ERROR;
5305 }
Ady Abraham34392f72019-04-10 11:29:27 -07005306 case 1035: {
5307 n = data.readInt32();
5308 mDebugDisplayConfigSetByBackdoor = false;
5309 if (n >= 0) {
5310 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005311 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005312 if (result != NO_ERROR) {
5313 return result;
5314 }
5315 mDebugDisplayConfigSetByBackdoor = true;
5316 }
5317 return NO_ERROR;
5318 }
Ady Abraham07e54702020-04-16 15:05:37 -07005319 case 1036: {
5320 if (data.readInt32() > 0) {
5321 status_t result =
5322 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5323 if (result != NO_ERROR) {
5324 return result;
5325 }
5326 } else {
5327 mDebugFrameRateFlexibilityToken = nullptr;
5328 }
5329 return NO_ERROR;
5330 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005331 }
5332 }
5333 return err;
5334}
5335
Steven Thomas6d8110b2017-08-31 18:24:21 -07005336void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005337 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005338 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005339}
5340
Ana Krulec7d1d6832018-12-27 11:10:09 -08005341void SurfaceFlinger::repaintEverythingForHWC() {
5342 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005343 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005344 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005345}
5346
Ady Abrahama09852a2020-02-20 14:23:42 -08005347void SurfaceFlinger::kernelTimerChanged(bool expired) {
5348 static bool updateOverlay =
5349 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005350 if (!updateOverlay) return;
5351 if (Mutex::Autolock lock(mStateLock); !mRefreshRateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005352
5353 // Update the overlay on the main thread to avoid race conditions with
5354 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowski20134642020-04-20 22:36:44 -07005355 static_cast<void>(schedule([=] {
5356 const auto desiredActiveConfig = getDesiredActiveConfig();
5357 const auto& current = desiredActiveConfig
5358 ? mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId)
5359 : mRefreshRateConfigs->getCurrentRefreshRate();
5360 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5361
5362 if (current != min) {
Ana Krulecb9afd792020-06-11 13:16:15 -07005363 const bool timerExpired = mKernelIdleTimerEnabled && expired;
Ady Abrahama09852a2020-02-20 14:23:42 -08005364
Dominik Laskowski20134642020-04-20 22:36:44 -07005365 if (Mutex::Autolock lock(mStateLock); mRefreshRateOverlay) {
Ady Abrahama09852a2020-02-20 14:23:42 -08005366 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
Ady Abrahama09852a2020-02-20 14:23:42 -08005367 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005368 mEventQueue->invalidate();
Ady Abrahama09852a2020-02-20 14:23:42 -08005369 }
5370 }));
5371}
5372
Ana Krulecb9afd792020-06-11 13:16:15 -07005373void SurfaceFlinger::toggleKernelIdleTimer() {
5374 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
5375
5376 // If the support for kernel idle timer is disabled in SF code, don't do anything.
5377 if (!mSupportKernelIdleTimer) {
5378 return;
5379 }
5380 const KernelIdleTimerAction action = mRefreshRateConfigs->getIdleTimerAction();
5381
5382 switch (action) {
5383 case KernelIdleTimerAction::TurnOff:
5384 if (mKernelIdleTimerEnabled) {
5385 ATRACE_INT("KernelIdleTimer", 0);
5386 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "false");
5387 mKernelIdleTimerEnabled = false;
5388 }
5389 break;
5390 case KernelIdleTimerAction::TurnOn:
5391 if (!mKernelIdleTimerEnabled) {
5392 ATRACE_INT("KernelIdleTimer", 1);
5393 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "true");
5394 mKernelIdleTimerEnabled = true;
5395 }
5396 break;
5397 case KernelIdleTimerAction::NoChange:
5398 break;
5399 }
5400}
5401
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005402// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5403class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005404public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005405 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5406 ~WindowDisconnector() {
5407 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005408 }
5409
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005410private:
5411 ANativeWindow* mWindow;
5412 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005413};
5414
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005415status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005416 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005417 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5418 const Rect& sourceCrop, uint32_t reqWidth,
5419 uint32_t reqHeight, bool useIdentityTransform,
5420 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005421 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005422
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005423 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005424
Dominik Laskowski718f9602019-11-09 20:01:35 -08005425 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5426 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5427 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5428 renderAreaRotation = ui::Transform::ROT_0;
5429 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005430
Chia-I Wu20261cb2018-08-23 12:55:44 -07005431 sp<DisplayDevice> display;
5432 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005433 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005434
Chia-I Wu20261cb2018-08-23 12:55:44 -07005435 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005436 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005437
Chia-I Wucb023152018-08-28 12:57:23 -07005438 // set the requested width/height to the logical display viewport size
5439 // by default
5440 if (reqWidth == 0 || reqHeight == 0) {
5441 reqWidth = uint32_t(display->getViewport().width());
5442 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005443 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005444 }
5445
Peiyong Lin0e003c92018-09-17 11:09:51 -07005446 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005447 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005448 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5449 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005450 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005451 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005452}
5453
chaviw93df2ea2019-04-30 16:45:12 -07005454static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5455 switch (colorMode) {
5456 case ColorMode::DISPLAY_P3:
5457 case ColorMode::BT2100_PQ:
5458 case ColorMode::BT2100_HLG:
5459 case ColorMode::DISPLAY_BT2020:
5460 return Dataspace::DISPLAY_P3;
5461 default:
5462 return Dataspace::V0_SRGB;
5463 }
5464}
5465
Martin Liu4a322352020-03-24 21:30:38 +08005466status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5467 static constexpr int kFifoPriority = 2;
5468 static constexpr int kOtherPriority = 0;
5469
5470 struct sched_param param = {0};
5471 int sched_policy;
5472 if (enabled) {
5473 sched_policy = SCHED_FIFO;
5474 param.sched_priority = kFifoPriority;
5475 } else {
5476 sched_policy = SCHED_OTHER;
5477 param.sched_priority = kOtherPriority;
5478 }
5479
5480 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5481 return -errno;
5482 }
5483 return NO_ERROR;
5484}
5485
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005486sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005487 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5488 if (displayToken) {
5489 return getDisplayDeviceLocked(displayToken);
5490 }
5491 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5492 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005493 return getDisplayByLayerStack(displayOrLayerStack);
5494}
5495
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005496sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005497 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005498 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005499 return display;
5500 }
5501 }
5502 return nullptr;
5503}
5504
5505status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5506 sp<GraphicBuffer>* outBuffer) {
5507 sp<DisplayDevice> display;
5508 uint32_t width;
5509 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005510 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005511 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005512 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005513 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5514 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005515 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005516 }
5517
5518 width = uint32_t(display->getViewport().width());
5519 height = uint32_t(display->getViewport().height());
5520
Dominik Laskowski718f9602019-11-09 20:01:35 -08005521 const auto orientation = display->getOrientation();
5522 captureOrientation = ui::Transform::toRotationFlags(orientation);
5523
5524 switch (captureOrientation) {
5525 case ui::Transform::ROT_90:
5526 captureOrientation = ui::Transform::ROT_270;
5527 break;
5528
5529 case ui::Transform::ROT_270:
5530 captureOrientation = ui::Transform::ROT_90;
5531 break;
5532
5533 case ui::Transform::ROT_INVALID:
5534 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5535 captureOrientation = ui::Transform::ROT_0;
5536 break;
5537
5538 default:
5539 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005540 }
chaviw93df2ea2019-04-30 16:45:12 -07005541 *outDataspace =
5542 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5543 }
5544
5545 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5546 false /* captureSecureLayers */);
5547
5548 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5549 std::placeholders::_1);
5550 bool ignored = false;
5551 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5552 false /* useIdentityTransform */,
5553 ignored /* outCapturedSecureLayers */);
5554}
5555
Robert Carr866455f2019-04-02 16:28:26 -07005556status_t SurfaceFlinger::captureLayers(
5557 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5558 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5559 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5560 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005561 ATRACE_CALL();
5562
5563 class LayerRenderArea : public RenderArea {
5564 public:
Robert Carr578038f2018-03-09 12:25:24 -08005565 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005566 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005567 bool childrenOnly, const Rect& displayViewport)
5568 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005569 mLayer(layer),
5570 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005571 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005572 mFlinger(flinger),
5573 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005574 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005575 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005576 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005577 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005578 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005579 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005580 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005581 }
chaviwa76b2712017-09-20 12:02:26 -07005582 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005583 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005584 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005585 Rect getSourceCrop() const override {
5586 if (mCrop.isEmpty()) {
5587 return getBounds();
5588 } else {
5589 return mCrop;
5590 }
5591 }
Robert Carr578038f2018-03-09 12:25:24 -08005592 class ReparentForDrawing {
5593 public:
5594 const sp<Layer>& oldParent;
5595 const sp<Layer>& newParent;
5596
Vishnu Nair4351ad52019-02-11 14:13:02 -08005597 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5598 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005599 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005600 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005601 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5602 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005603 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005604 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005605 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005606 };
5607
5608 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005609 const Rect sourceCrop = getSourceCrop();
5610 // no need to check rotation because there is none
5611 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5612 sourceCrop.height() != getReqHeight();
5613
Robert Carr578038f2018-03-09 12:25:24 -08005614 if (!mChildrenOnly) {
5615 mTransform = mLayer->getTransform().inverse();
5616 drawLayers();
5617 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005618 uint32_t w = static_cast<uint32_t>(getWidth());
5619 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005620 // In the "childrenOnly" case we reparent the children to a screenshot
5621 // layer which has no properties set and which does not draw.
5622 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005623 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5624 "Screenshot Parent"s, w, h, 0,
5625 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005626
Vishnu Nair4351ad52019-02-11 14:13:02 -08005627 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005628 drawLayers();
5629 }
5630 }
chaviwa76b2712017-09-20 12:02:26 -07005631
chaviwa76b2712017-09-20 12:02:26 -07005632 private:
chaviw7206d492017-11-10 16:16:12 -08005633 const sp<Layer> mLayer;
5634 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005635
Peiyong Linefefaac2018-08-17 12:27:51 -07005636 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005637 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005638
5639 SurfaceFlinger* mFlinger;
5640 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005641 };
5642
Robert Carrc0df3122019-04-11 13:18:21 -07005643 int reqWidth = 0;
5644 int reqHeight = 0;
5645 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005646 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005647 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005648 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005649 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005650 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005651
Alec Mouri9a02eda2020-04-21 17:39:34 -07005652 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005653 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5654 ALOGE("captureLayers called with an invalid or removed parent");
5655 return NAME_NOT_FOUND;
5656 }
5657
5658 const int uid = IPCThreadState::self()->getCallingUid();
5659 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5660 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5661 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5662 return PERMISSION_DENIED;
5663 }
5664
Vishnu Nairefc42e22019-12-03 17:36:12 -08005665 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005666 if (sourceCrop.width() <= 0) {
5667 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005668 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005669 }
5670
5671 if (sourceCrop.height() <= 0) {
5672 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005673 crop.bottom = parentSourceBounds.getHeight();
5674 }
5675
5676 if (crop.isEmpty() || frameScale <= 0.0f) {
5677 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5678 // crop was not specified, or an invalid frame scale was provided.
5679 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005680 }
5681 reqWidth = crop.width() * frameScale;
5682 reqHeight = crop.height() * frameScale;
5683
5684 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005685 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005686 if (excludeLayer != nullptr) {
5687 excludeLayers.emplace(excludeLayer);
5688 } else {
5689 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5690 return NAME_NOT_FOUND;
5691 }
5692 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005693
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005694 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005695 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005696 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005697 }
5698
5699 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005700 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005701
Chia-I Wu20261cb2018-08-23 12:55:44 -07005702 // really small crop or frameScale
5703 if (reqWidth <= 0) {
5704 reqWidth = 1;
5705 }
5706 if (reqHeight <= 0) {
5707 reqHeight = 1;
5708 }
5709
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005710 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5711 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005712 auto traverseLayers = [parent, childrenOnly,
5713 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005714 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5715 if (!layer->isVisible()) {
5716 return;
Robert Carr578038f2018-03-09 12:25:24 -08005717 } else if (childrenOnly && layer == parent.get()) {
5718 return;
chaviwa76b2712017-09-20 12:02:26 -07005719 }
Robert Carr866455f2019-04-02 16:28:26 -07005720
5721 sp<Layer> p = layer;
5722 while (p != nullptr) {
5723 if (excludeLayers.count(p) != 0) {
5724 return;
5725 }
5726 p = p->getParent();
5727 }
5728
chaviwa76b2712017-09-20 12:02:26 -07005729 visitor(layer);
5730 });
5731 };
Robert Carr108b2c72019-04-02 16:32:58 -07005732
5733 bool outCapturedSecureLayers = false;
5734 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5735 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005736}
5737
5738status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5739 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005740 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005741 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005742 bool useIdentityTransform,
5743 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005744 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005745
Peiyong Lin0e003c92018-09-17 11:09:51 -07005746 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005747 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5748 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005749 *outBuffer =
5750 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5751 static_cast<android_pixel_format>(reqPixelFormat), 1,
5752 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005753
Robert Carr108b2c72019-04-02 16:32:58 -07005754 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005755 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005756}
5757
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005758status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5759 TraverseLayersFunction traverseLayers,
5760 const sp<GraphicBuffer>& buffer,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005761 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005762 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005763 const int uid = IPCThreadState::self()->getCallingUid();
5764 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5765
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005766 status_t result;
5767 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005768
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005769 do {
5770 std::tie(result, syncFd) =
5771 schedule([&] {
5772 if (mRefreshPending) {
5773 ATRACE_NAME("Skipping screenshot for now");
5774 return std::make_pair(EAGAIN, -1);
5775 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005776
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005777 status_t result = NO_ERROR;
5778 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005779
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005780 Mutex::Autolock lock(mStateLock);
5781 renderArea.render([&] {
5782 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5783 useIdentityTransform, forSystem, &fd,
5784 regionSampling, outCapturedSecureLayers);
5785 });
5786
5787 return std::make_pair(result, fd);
5788 }).get();
5789 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005790
5791 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005792 sync_wait(syncFd, -1);
5793 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005794 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005795
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005796 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005797}
5798
chaviwa76b2712017-09-20 12:02:26 -07005799void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005800 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005801 ANativeWindowBuffer* buffer, bool useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005802 bool regionSampling, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005803 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005804
chaviwa76b2712017-09-20 12:02:26 -07005805 const auto reqWidth = renderArea.getReqWidth();
5806 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005807 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005808 const auto transform = renderArea.getTransform();
5809 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005810 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005811
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005812 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005813 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005814
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005815 // assume that bounds are never offset, and that they are the same as the
5816 // buffer bounds.
5817 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005818 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005819 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005820
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005821 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5822 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005823
chaviw50da5042018-04-09 13:49:37 -07005824 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005825
Vishnu Nair9b079a22020-01-21 14:36:08 -08005826 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005827 fillLayer.source.buffer.buffer = nullptr;
5828 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005829 fillLayer.geometry.boundaries =
5830 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005831 fillLayer.alpha = half(alpha);
5832 clientCompositionLayers.push_back(fillLayer);
5833
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005834 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08005835 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005836 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005837 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005838 const bool supportProtectedContent = false;
5839 Region clip(renderArea.getBounds());
5840 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5841 clip,
5842 useIdentityTransform,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005843 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07005844 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005845 renderArea.isSecure(),
5846 supportProtectedContent,
5847 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005848 displayViewport,
5849 clientCompositionDisplay.outputDataspace,
5850 true, /* realContentIsVisible */
5851 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005852 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005853 std::vector<compositionengine::LayerFE::LayerSettings> results =
5854 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005855 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005856 for (auto& settings : results) {
5857 settings.geometry.positionTransform =
5858 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupinf11eba52020-04-20 18:42:31 -07005859 // There's no need to process blurs when we're executing region sampling,
5860 // we're just trying to understand what we're drawing, and doing so without
5861 // blurs is already a pretty good approximation.
5862 if (regionSampling) {
5863 settings.backgroundBlurRadius = 0;
5864 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005865 }
Yichi Chen40773d92020-04-01 10:10:18 +08005866 clientCompositionLayers.insert(clientCompositionLayers.end(),
5867 std::make_move_iterator(results.begin()),
5868 std::make_move_iterator(results.end()));
5869 renderedLayers.push_back(layer);
5870 }
chaviwa76b2712017-09-20 12:02:26 -07005871 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005872
Yichi Chen40773d92020-04-01 10:10:18 +08005873 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5874 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005875 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005876 clientCompositionLayerPointers.begin(),
5877 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005878
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005879 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005880 // Use an empty fence for the buffer fence, since we just created the buffer so
5881 // there is no need for synchronization with the GPU.
5882 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005883 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005884 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005885 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005886 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005887
5888 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005889
5890 if (*outSyncFd >= 0) {
5891 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5892 for (auto* layer : renderedLayers) {
5893 layer->onLayerDisplayed(releaseFence);
5894 }
5895 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005896}
5897
chaviwa76b2712017-09-20 12:02:26 -07005898status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5899 TraverseLayersFunction traverseLayers,
5900 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005901 bool useIdentityTransform, bool forSystem,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005902 int* outSyncFd, bool regionSampling,
5903 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005904 ATRACE_CALL();
5905
chaviwa76b2712017-09-20 12:02:26 -07005906 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005907 outCapturedSecureLayers =
5908 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005909 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005910
Robert Carr03480e22018-01-04 16:02:06 -08005911 // We allow the system server to take screenshots of secure layers for
5912 // use in situations like the Screen-rotation animation and place
5913 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005914 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005915 ALOGW("FB is protected: PERMISSION_DENIED");
5916 return PERMISSION_DENIED;
5917 }
Lucas Dupinf11eba52020-04-20 18:42:31 -07005918 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5919 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005920 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005921}
5922
chaviw95ef3c42019-02-14 10:55:09 -08005923void SurfaceFlinger::setInputWindowsFinished() {
5924 Mutex::Autolock _l(mStateLock);
5925
5926 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005927
chaviw95ef3c42019-02-14 10:55:09 -08005928 mTransactionCV.broadcast();
5929}
chaviw5f21a5e2019-02-14 10:00:34 -08005930
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005931// ---------------------------------------------------------------------------
5932
Edgar Arriaga844fa672020-01-16 14:21:42 -08005933void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5934 layersSortedByZ.traverse(visitor);
5935}
5936
Dan Stoza412903f2017-04-27 13:42:17 -07005937void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5938 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005939}
5940
Dan Stoza412903f2017-04-27 13:42:17 -07005941void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5942 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005943}
5944
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005945void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005946 const LayerVector::Visitor& visitor) {
5947 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005948 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005949 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005950 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005951 continue;
5952 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005953 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005954 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005955 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005956 return;
5957 }
chaviwa76b2712017-09-20 12:02:26 -07005958 if (!layer->isVisible()) {
5959 return;
5960 }
5961 visitor(layer);
5962 });
5963 }
5964}
5965
Steven Thomasd4071902020-03-24 16:02:53 -07005966status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5967 const sp<DisplayDevice>& display,
5968 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005969 Mutex::Autolock lock(mStateLock);
5970
Steven Thomasd4071902020-03-24 16:02:53 -07005971 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5972 "Can only set override policy on the primary display");
5973 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5974
Dominik Laskowski22488f62019-03-28 09:53:04 -07005975 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005976 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5977 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5978 // it should go thru setDesiredActiveConfig, similar to primary display.
5979 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5980 const auto displayId = display->getId();
5981 LOG_ALWAYS_FATAL_IF(!displayId);
5982
Peiyong Line9d809e2020-04-14 13:10:48 -07005983 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005984 constraints.desiredTimeNanos = systemTime();
5985 constraints.seamlessRequired = false;
5986
Peiyong Line9d809e2020-04-14 13:10:48 -07005987 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005988 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5989 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005990 constraints, &timeline) < 0) {
5991 return BAD_VALUE;
5992 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005993 if (timeline.refreshRequired) {
5994 repaintEverythingForHWC();
5995 }
5996
Steven Thomasd4071902020-03-24 16:02:53 -07005997 display->setActiveConfig(policy->defaultConfig);
5998 const nsecs_t vsyncPeriod = getHwComposer()
5999 .getConfigs(*displayId)[policy->defaultConfig.value()]
6000 ->getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006001 mScheduler->onNonPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6002 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006003 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08006004 }
6005
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006006 if (mDebugDisplayConfigSetByBackdoor) {
6007 // ignore this request as config is overridden by backdoor
6008 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006009 }
6010
Steven Thomasd4071902020-03-24 16:02:53 -07006011 status_t setPolicyResult = overridePolicy
6012 ? mRefreshRateConfigs->setOverridePolicy(policy)
6013 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
6014 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006015 return BAD_VALUE;
6016 }
Steven Thomasd4071902020-03-24 16:02:53 -07006017 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006018 return NO_ERROR;
6019 }
Steven Thomasd4071902020-03-24 16:02:53 -07006020 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006021
Steven Thomasf734df42020-04-13 21:09:28 -07006022 ALOGV("Setting desired display config specs: defaultConfig: %d primaryRange: [%.0f %.0f]"
6023 " expandedRange: [%.0f %.0f]",
6024 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
6025 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
6026 currentPolicy.appRequestRange.max);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006027
Ana Krulecb9afd792020-06-11 13:16:15 -07006028 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6029 // be depending in this callback.
Alec Mouri60aee1c2019-10-28 16:18:59 -07006030 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07006031 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
6032 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006033 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6034 display->getActiveConfig(), vsyncPeriod);
Ana Krulecb9afd792020-06-11 13:16:15 -07006035 toggleKernelIdleTimer();
Ady Abraham838de062019-02-04 10:24:03 -08006036
Ana Krulec3f6a2062020-01-23 15:48:01 -08006037 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08006038 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08006039 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
6040 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07006041 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08006042 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07006043 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006044
Ady Abrahamabc27602020-04-08 17:20:29 -07006045 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
6046 ALOGV("switching to Scheduler preferred config %d",
6047 preferredRefreshRate.getConfigId().value());
6048 setDesiredActiveConfig(
6049 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006050 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07006051 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
6052 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006053 }
6054
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006055 return NO_ERROR;
6056}
6057
Ana Krulec0782b882019-10-15 17:34:54 -07006058status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Steven Thomasf734df42020-04-13 21:09:28 -07006059 int32_t defaultConfig,
6060 float primaryRefreshRateMin,
6061 float primaryRefreshRateMax,
6062 float appRequestRefreshRateMin,
6063 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006064 ATRACE_CALL();
6065
6066 if (!displayToken) {
6067 return BAD_VALUE;
6068 }
6069
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006070 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006071 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006072 if (!display) {
6073 ALOGE("Attempt to set desired display configs for invalid display token %p",
6074 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006075 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006076 } else if (display->isVirtual()) {
6077 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006078 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006079 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006080 using Policy = scheduler::RefreshRateConfigs::Policy;
Steven Thomasf734df42020-04-13 21:09:28 -07006081 const Policy policy{HwcConfigIndexType(defaultConfig),
6082 {primaryRefreshRateMin, primaryRefreshRateMax},
6083 {appRequestRefreshRateMin, appRequestRefreshRateMax}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006084 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006085
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006086 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
6087 }
6088 });
6089
6090 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006091}
6092
6093status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006094 int32_t* outDefaultConfig,
Steven Thomasf734df42020-04-13 21:09:28 -07006095 float* outPrimaryRefreshRateMin,
6096 float* outPrimaryRefreshRateMax,
6097 float* outAppRequestRefreshRateMin,
6098 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006099 ATRACE_CALL();
6100
Steven Thomasf734df42020-04-13 21:09:28 -07006101 if (!displayToken || !outDefaultConfig || !outPrimaryRefreshRateMin ||
6102 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006103 return BAD_VALUE;
6104 }
6105
6106 Mutex::Autolock lock(mStateLock);
6107 const auto display = getDisplayDeviceLocked(displayToken);
6108 if (!display) {
6109 return NAME_NOT_FOUND;
6110 }
6111
6112 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006113 scheduler::RefreshRateConfigs::Policy policy =
6114 mRefreshRateConfigs->getDisplayManagerPolicy();
6115 *outDefaultConfig = policy.defaultConfig.value();
Steven Thomasf734df42020-04-13 21:09:28 -07006116 *outPrimaryRefreshRateMin = policy.primaryRange.min;
6117 *outPrimaryRefreshRateMax = policy.primaryRange.max;
6118 *outAppRequestRefreshRateMin = policy.appRequestRange.min;
6119 *outAppRequestRefreshRateMax = policy.appRequestRange.max;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006120 return NO_ERROR;
6121 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006122 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006123 } else {
6124 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006125 LOG_FATAL_IF(!displayId);
6126
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006127 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6128 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
Steven Thomasf734df42020-04-13 21:09:28 -07006129 *outPrimaryRefreshRateMin = 1e9f / vsyncPeriod;
6130 *outPrimaryRefreshRateMax = 1e9f / vsyncPeriod;
6131 *outAppRequestRefreshRateMin = 1e9f / vsyncPeriod;
6132 *outAppRequestRefreshRateMax = 1e9f / vsyncPeriod;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006133 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006134 }
Ana Krulec0782b882019-10-15 17:34:54 -07006135}
6136
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006137void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006138 mFlinger->setInputWindowsFinished();
6139}
6140
Alec Mouri9a02eda2020-04-21 17:39:34 -07006141wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6142 Mutex::Autolock _l(mStateLock);
6143 return fromHandleLocked(handle);
6144}
6145
6146wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006147 BBinder* b = nullptr;
6148 if (handle) {
6149 b = handle->localBinder();
6150 }
Robert Carrc0df3122019-04-11 13:18:21 -07006151 if (b == nullptr) {
6152 return nullptr;
6153 }
6154 auto it = mLayersByLocalBinderToken.find(b);
6155 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006156 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006157 }
6158 return nullptr;
6159}
6160
Dominik Laskowski75848362019-11-11 17:57:20 -08006161void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006162 mNumLayers++;
6163 mScheduler->registerLayer(layer);
6164}
6165
6166void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6167 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006168 removeFromOffscreenLayers(layer);
6169}
6170
6171// WARNING: ONLY CALL THIS FROM LAYER DTOR
6172// Here we add children in the current state to offscreen layers and remove the
6173// layer itself from the offscreen layer list. Since
6174// this is the dtor, it is safe to access the current state. This keeps us
6175// from dangling children layers such that they are not reachable from the
6176// Drawing state nor the offscreen layer list
6177// See b/141111965
6178void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6179 for (auto& child : layer->getCurrentChildren()) {
6180 mOffscreenLayers.emplace(child.get());
6181 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006182 mOffscreenLayers.erase(layer);
6183}
6184
Alec Mouri4545a8a2019-08-08 20:05:32 -07006185void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6186 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6187}
6188
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006189status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6190 float lightPosY, float lightPosZ,
6191 float lightRadius) {
6192 Mutex::Autolock _l(mStateLock);
6193 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6194 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6195 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6196 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6197 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6198
6199 // these values are overridden when calculating the shadow settings for a layer.
6200 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6201 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006202 return NO_ERROR;
6203}
6204
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006205const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6206 const {
6207 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6208 // on the work to remove the table in that bug rather than adding more to
6209 // it.
6210 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6211 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6212 // supported, and exposed via the
6213 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6214 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6215 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6216 };
6217 return genericLayerMetadataKeyMap;
6218}
6219
Steven Thomas62a4cf82020-01-31 12:04:03 -08006220status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6221 int8_t compatibility) {
6222 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6223 return BAD_VALUE;
6224 }
6225
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006226 static_cast<void>(schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006227 Mutex::Autolock lock(mStateLock);
6228 if (authenticateSurfaceTextureLocked(surface)) {
6229 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6230 if (layer->setFrameRate(
6231 Layer::FrameRate(frameRate,
6232 Layer::FrameRate::convertCompatibility(compatibility)))) {
6233 setTransactionFlags(eTraversalNeeded);
6234 }
6235 } else {
6236 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6237 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006238 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006239 return NO_ERROR;
6240 }));
6241
Steven Thomas62a4cf82020-01-31 12:04:03 -08006242 return NO_ERROR;
6243}
6244
Steven Thomasd4071902020-03-24 16:02:53 -07006245status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6246 if (!outToken) {
6247 return BAD_VALUE;
6248 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006249
6250 auto future = schedule([this] {
6251 status_t result = NO_ERROR;
6252 sp<IBinder> token;
6253
Steven Thomasd4071902020-03-24 16:02:53 -07006254 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006255 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Steven Thomasd4071902020-03-24 16:02:53 -07006256
6257 // This is a little racy, but not in a way that hurts anything. As we grab the
6258 // defaultConfig from the display manager policy, we could be setting a new display
6259 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6260 // matter for the override policy though, since we set allowGroupSwitching to true, so
6261 // it's not a problem.
6262 scheduler::RefreshRateConfigs::Policy overridePolicy;
6263 overridePolicy.defaultConfig =
6264 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6265 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006266 constexpr bool kOverridePolicy = true;
6267 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006268 }
6269
6270 if (result == NO_ERROR) {
6271 mFrameRateFlexibilityTokenCount++;
6272 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6273 // below, is something to consider carefully. The lifetime of the
6274 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6275 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6276 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6277 // in this case, for two reasons:
6278 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6279 // the program exits is via a crash. So we won't have a situation where the
6280 // SurfaceFlinger object is dead but the process is still up.
6281 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6282 // if condition 1 were changed, the problem would only show up when running CTS tests,
6283 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006284 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006285 [this]() { onFrameRateFlexibilityTokenReleased(); });
6286 ALOGD("Frame rate flexibility token acquired. count=%d",
6287 mFrameRateFlexibilityTokenCount);
6288 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006289
6290 return std::make_pair(result, token);
6291 });
6292
6293 status_t result;
6294 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006295 return result;
6296}
6297
6298void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006299 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006300 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6301 "Failed tracking frame rate flexibility tokens");
6302 mFrameRateFlexibilityTokenCount--;
6303 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6304 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006305 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006306 constexpr bool kOverridePolicy = true;
6307 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006308 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6309 }
6310 }));
6311}
6312
Dominik Laskowski20134642020-04-20 22:36:44 -07006313void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
6314 static_cast<void>(schedule([=] {
6315 std::unique_ptr<RefreshRateOverlay> overlay;
6316 if (enable) {
6317 overlay = std::make_unique<RefreshRateOverlay>(*this);
6318 }
6319
6320 {
6321 Mutex::Autolock lock(mStateLock);
6322
6323 // Destroy the layer of the current overlay, if any, outside the lock.
6324 mRefreshRateOverlay.swap(overlay);
6325 if (!mRefreshRateOverlay) return;
6326
6327 if (const auto display = getDefaultDisplayDeviceLocked()) {
6328 mRefreshRateOverlay->setViewport(display->getSize());
6329 }
6330
6331 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
6332 }
6333 }));
6334}
6335
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006336} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006337
Mathias Agopian3f844832013-08-07 21:24:32 -07006338#if defined(__gl_h_)
6339#error "don't include gl/gl.h in this file"
6340#endif
6341
6342#if defined(__gl2_h_)
6343#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006344#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006345
6346// TODO(b/129481165): remove the #pragma below and fix conversion issues
6347#pragma clang diagnostic pop // ignored "-Wconversion"