blob: 4165df9ae5539e3423b35a38652fb4e4dd3b5ba8 [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 }
603
Steven Thomas050b2c82017-03-06 11:45:16 -0800604 if (mVrFlinger) {
605 mVrFlinger->OnBootFinished();
606 }
607
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700608 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700609 // formerly we would just kill the process, but we now ask it to exit so it
610 // can choose where to stop the animation.
611 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700612
613 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
614 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
615 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700616
Denis Hsu58fbf9f2020-06-17 10:17:30 +0800617 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
618
Chavi Weingarten60f3ab22020-12-09 00:36:11 +0000619 static_cast<void>(schedule([=] {
Denis Hsu58fbf9f2020-06-17 10:17:30 +0800620 if (input == nullptr) {
621 ALOGE("Failed to link to input service");
622 } else {
623 mInputFlinger = interface_cast<IInputFlinger>(input);
624 }
625
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800626 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700627 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800628 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800629
Ady Abraham8a82ba62020-01-17 12:43:17 -0800630 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700631 enableRefreshRateOverlay(true);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800632 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800633 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800634}
635
Dan Stoza436ccf32018-06-21 12:10:12 -0700636uint32_t SurfaceFlinger::getNewTexture() {
637 {
638 std::lock_guard lock(mTexturePoolMutex);
639 if (!mTexturePool.empty()) {
640 uint32_t name = mTexturePool.back();
641 mTexturePool.pop_back();
642 ATRACE_INT("TexturePoolSize", mTexturePool.size());
643 return name;
644 }
645
646 // The pool was too small, so increase it for the future
647 ++mTexturePoolSize;
648 }
649
650 // The pool was empty, so we need to get a new texture name directly using a
651 // blocking call to the main thread
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700652 return schedule([this] {
653 uint32_t name = 0;
654 getRenderEngine().genTextures(1, &name);
655 return name;
656 })
657 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700658}
659
Mathias Agopian3f844832013-08-07 21:24:32 -0700660void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700661 std::lock_guard lock(mTexturePoolMutex);
662 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
663 // to actually delete this or not based on mTexturePoolSize
664 mTexturePool.push_back(texture);
665 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700666}
667
Wei Wangf9b05ee2017-07-19 20:59:39 -0700668// Do not call property_set on main thread which will be blocked by init
669// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700670void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700671 ALOGI( "SurfaceFlinger's main thread ready to run. "
672 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700673 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800674
Steven Thomasb02664d2017-07-26 18:48:28 -0700675 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700676 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800677 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700678 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
679 renderengine::RenderEngineCreationArgs::Builder()
680 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
681 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
682 .setUseColorManagerment(useColorManagement)
683 .setEnableProtectedContext(enable_protected_contents(false))
684 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700685 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700686 .setContextPriority(useContextPriority
687 ? renderengine::RenderEngine::ContextPriority::HIGH
688 : renderengine::RenderEngine::ContextPriority::MEDIUM)
689 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800690 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700691
692 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
693 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700694 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800695 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800696 // Process any initial hotplug and resulting display changes.
697 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700698 const auto display = getDefaultDisplayDeviceLocked();
699 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700700 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700701 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800702
Steven Thomas050b2c82017-03-06 11:45:16 -0800703 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700704 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700705 // This callback is called from the vr flinger dispatch thread. We
706 // need to call signalTransaction(), which requires holding
707 // mStateLock when we're not on the main thread. Acquiring
708 // mStateLock from the vr flinger dispatch thread might trigger a
709 // deadlock in surface flinger (see b/66916578), so post a message
710 // to be handled on the main thread instead.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700711 static_cast<void>(schedule([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700712 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
713 mVrFlingerRequestsDisplay = requestDisplay;
714 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700715 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800716 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700717 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
718 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700719 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700720 .value_or(0),
721 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800722 if (!mVrFlinger) {
723 ALOGE("Failed to start vrflinger");
724 }
725 }
726
Mathias Agopian92a979a2012-08-02 18:32:23 -0700727 // initialize our drawing state
728 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700729
Andy McFadden13a082e2012-08-24 10:16:42 -0700730 // set initial conditions (e.g. unblank default device)
731 initializeDisplays();
732
Steven Thomas137d4bc2019-07-25 16:55:14 -0700733 char primeShaderCache[PROPERTY_VALUE_MAX];
734 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
735 if (atoi(primeShaderCache)) {
736 getRenderEngine().primeCache();
737 }
Dan Stoza4e637772016-07-28 13:31:51 -0700738
Wei Wangf9b05ee2017-07-19 20:59:39 -0700739 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700740
741 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700742 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700743 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744
745 if (mStartPropertySetThread->Start() != NO_ERROR) {
746 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800747 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800748
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700750}
751
Romain Guy11d63f42017-07-20 12:47:14 -0700752void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700753 Mutex::Autolock _l(mStateLock);
754
Romain Guy11d63f42017-07-20 12:47:14 -0700755 char value[PROPERTY_VALUE_MAX];
756
757 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800758 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800760 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100761
762 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700763 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800764
765 property_get("persist.sys.sf.color_mode", value, "0");
766 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700767
768 property_get("persist.sys.sf.disable_blurs", value, "0");
769 bool disableBlurs = atoi(value);
770 mDisableBlurs = disableBlurs;
771 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700772}
773
Mathias Agopiana67e4182012-06-19 17:26:12 -0700774void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800775 // Start boot animation service by setting a property mailbox
776 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700777 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800778 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700779 if (mStartPropertySetThread->join() != NO_ERROR) {
780 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800781 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700782}
783
Mathias Agopian875d8e12013-06-07 15:35:48 -0700784size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700785 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700786}
787
Mathias Agopian875d8e12013-06-07 15:35:48 -0700788size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700789 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700790}
791
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800792// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800793
Jamie Gennis582270d2011-08-17 18:19:00 -0700794bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800795 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800796 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800797 return authenticateSurfaceTextureLocked(bufferProducer);
798}
799
800bool SurfaceFlinger::authenticateSurfaceTextureLocked(
801 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800802 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800803 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800804}
805
Brian Anderson6b376712017-04-04 10:51:39 -0700806status_t SurfaceFlinger::getSupportedFrameTimestamps(
807 std::vector<FrameEvent>* outSupported) const {
808 *outSupported = {
809 FrameEvent::REQUESTED_PRESENT,
810 FrameEvent::ACQUIRE,
811 FrameEvent::LATCH,
812 FrameEvent::FIRST_REFRESH_START,
813 FrameEvent::LAST_REFRESH_START,
814 FrameEvent::GPU_COMPOSITION_DONE,
815 FrameEvent::DEQUEUE_READY,
816 FrameEvent::RELEASE,
817 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700818 ConditionalLock _l(mStateLock,
819 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700820 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700821 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
822 }
823 return NO_ERROR;
824}
825
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800826status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
827 if (!displayToken || !state) {
828 return BAD_VALUE;
829 }
830
831 Mutex::Autolock lock(mStateLock);
832
833 const auto display = getDisplayDeviceLocked(displayToken);
834 if (!display) {
835 return NAME_NOT_FOUND;
836 }
837
838 state->layerStack = display->getLayerStack();
839 state->orientation = display->getOrientation();
840
841 const Rect viewport = display->getViewport();
842 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
843
844 return NO_ERROR;
845}
846
847status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
848 if (!displayToken || !info) {
849 return BAD_VALUE;
850 }
851
852 Mutex::Autolock lock(mStateLock);
853
854 const auto display = getDisplayDeviceLocked(displayToken);
855 if (!display) {
856 return NAME_NOT_FOUND;
857 }
858
Dominik Laskowski55c85402020-01-21 16:25:47 -0800859 if (const auto connectionType = display->getConnectionType())
860 info->connectionType = *connectionType;
861 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800862 return INVALID_OPERATION;
863 }
864
865 if (mEmulatedDisplayDensity) {
866 info->density = mEmulatedDisplayDensity;
867 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800868 info->density = info->connectionType == DisplayConnectionType::Internal
869 ? mInternalDisplayDensity
870 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800871 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700872 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800873
874 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200875 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800876
877 return NO_ERROR;
878}
879
Dominik Laskowski22488f62019-03-28 09:53:04 -0700880status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800881 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700882 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700883 return BAD_VALUE;
884 }
885
Dominik Laskowski22488f62019-03-28 09:53:04 -0700886 Mutex::Autolock lock(mStateLock);
887
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800888 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700889 if (!displayId) {
890 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700891 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700892
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800893 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700894
Dan Stoza7f7da322014-05-02 15:26:25 -0700895 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700896
Dominik Laskowski075d3172018-05-24 15:50:06 -0700897 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800898 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700899
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800900 auto width = hwConfig->getWidth();
901 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700902
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800903 auto xDpi = hwConfig->getDpiX();
904 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700905
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800906 if (isInternal &&
907 (internalDisplayOrientation == ui::ROTATION_90 ||
908 internalDisplayOrientation == ui::ROTATION_270)) {
909 std::swap(width, height);
910 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700911 }
912
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800913 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800914
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800915 if (mEmulatedDisplayDensity) {
916 config.xDpi = mEmulatedDisplayDensity;
917 config.yDpi = mEmulatedDisplayDensity;
918 } else {
919 config.xDpi = xDpi;
920 config.yDpi = yDpi;
921 }
922
923 const nsecs_t period = hwConfig->getVsyncPeriod();
924 config.refreshRate = 1e9f / period;
925
926 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
927 config.appVsyncOffset = offsets.late.app;
928 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800929 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800930
Andy McFadden91b2ca82014-06-13 14:04:23 -0700931 // This is how far in advance a buffer must be queued for
932 // presentation at a given time. If you want a buffer to appear
933 // on the screen at time N, you must submit the buffer before
934 // (N - presentationDeadline).
935 //
936 // Normally it's one full refresh period (to give SF a chance to
937 // latch the buffer), but this can be reduced by configuring a
938 // DispSync offset. Any additional delays introduced by the hardware
939 // composer or panel must be accounted for here.
940 //
941 // We add an additional 1ms to allow for processing time and
942 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800943 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700944
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800945 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700946 }
947
Dan Stoza7f7da322014-05-02 15:26:25 -0700948 return NO_ERROR;
949}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
952 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700953 return BAD_VALUE;
954 }
955
Ana Krulecc2870422019-01-29 19:00:58 -0800956 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700957 return NO_ERROR;
958}
959
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700961 int activeConfig;
962 bool isPrimary;
963
964 {
965 Mutex::Autolock lock(mStateLock);
966
967 if (const auto display = getDisplayDeviceLocked(displayToken)) {
968 activeConfig = display->getActiveConfig().value();
969 isPrimary = display->isPrimary();
970 } else {
971 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
972 return NAME_NOT_FOUND;
973 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800974 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700975
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700976 if (isPrimary) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700977 if (const auto config = getDesiredActiveConfig()) {
978 return config->configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700979 }
Steven Thomasc9098452019-09-30 17:15:05 -0700980 }
Ady Abraham2139f732019-11-13 18:56:40 -0800981
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700982 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700983}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700984
Ady Abraham03b02dd2019-03-21 15:40:11 -0700985void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800987 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700988 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800989
Ady Abrahamb838aed2019-02-12 15:30:16 -0800990 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800991 if (mDesiredActiveConfigChanged) {
992 // If a config change is pending, just cache the latest request in
993 // mDesiredActiveConfig
994 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
995 mDesiredActiveConfig = info;
996 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
997 } else {
998 // Check is we are already at the desired config
999 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -07001000 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -08001001 return;
1002 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001003
Ady Abraham59db0a32020-03-02 18:04:20 -08001004 // Initiate a config change.
1005 mDesiredActiveConfigChanged = true;
1006 mDesiredActiveConfig = info;
1007
Ady Abrahamb838aed2019-02-12 15:30:16 -08001008 // This will trigger HWC refresh without resetting the idle timer.
1009 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -07001010 // Start receiving vsync samples now, so that we can detect a period
1011 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -07001012 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -07001013 // As we called to set period, we will call to onRefreshRateChangeCompleted once
1014 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001015 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -08001016
Ady Abrahamabc27602020-04-08 17:20:29 -07001017 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001018 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001019 mScheduler->setConfigChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07001021
1022 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -08001023 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -07001024 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001025}
1026
1027status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1028 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001029
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001030 if (!displayToken) {
1031 return BAD_VALUE;
1032 }
Ady Abraham838de062019-02-04 10:24:03 -08001033
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001034 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001035 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001036 if (!display) {
1037 ALOGE("Attempt to set allowed display configs for invalid display token %p",
1038 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001039 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001040 } else if (display->isVirtual()) {
1041 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001042 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001043 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001044 const HwcConfigIndexType config(mode);
1045 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
Steven Thomasf734df42020-04-13 21:09:28 -07001046 const scheduler::RefreshRateConfigs::Policy policy{config, {fps, fps}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001047 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001048
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001049 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1050 }
1051 });
1052
1053 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001054}
1055
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001056void SurfaceFlinger::setActiveConfigInternal() {
1057 ATRACE_CALL();
1058
Dominik Laskowski22488f62019-03-28 09:53:04 -07001059 const auto display = getDefaultDisplayDeviceLocked();
1060 if (!display) {
1061 return;
1062 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001063
Alec Mouri8de697e2020-03-19 10:52:01 -07001064 auto& oldRefreshRate =
1065 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1066
Dominik Laskowski22488f62019-03-28 09:53:04 -07001067 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001068 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001069 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001070 display->setActiveConfig(mUpcomingActiveConfig.configId);
1071
Ady Abraham2e1dd892020-03-05 13:48:36 -08001072 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001073 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001074 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001075 mTimeStats->incrementRefreshRateSwitches();
1076 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001077 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001078 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001079 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001080
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001081 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001082 const nsecs_t vsyncPeriod =
1083 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001084 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001085 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
1086 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001087 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001088}
1089
Ady Abraham53852a52019-05-28 18:07:44 -07001090void SurfaceFlinger::desiredActiveConfigChangeDone() {
1091 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1092 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1093 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001094
Ady Abraham2e1dd892020-03-05 13:48:36 -08001095 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001096 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001097 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1098 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001099 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001100 mScheduler->setConfigChangePending(false);
Ady Abraham53852a52019-05-28 18:07:44 -07001101}
1102
Ady Abraham27cbed72020-04-10 12:56:59 -07001103void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001104 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001105 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001106 // Store the local variable to release the lock.
Dominik Laskowski20134642020-04-20 22:36:44 -07001107 const auto desiredActiveConfig = getDesiredActiveConfig();
Ady Abraham27cbed72020-04-10 12:56:59 -07001108 if (!desiredActiveConfig) {
1109 // No desired active config pending to be applied
1110 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001111 }
1112
Ady Abraham2e1dd892020-03-05 13:48:36 -08001113 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001114 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001115 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1116 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001117 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001118 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001119 // display is not valid or we are already in the requested mode
1120 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001121 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001122 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001123 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001124
Ady Abraham838de062019-02-04 10:24:03 -08001125 // Desired active config was set, it is different than the config currently in use, however
1126 // allowed configs might have change by the time we process the refresh.
1127 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001128 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001129 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001130 return;
Ady Abraham838de062019-02-04 10:24:03 -08001131 }
Alec Mouri7f015182019-07-11 13:56:22 -07001132
Ady Abraham27cbed72020-04-10 12:56:59 -07001133 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001134 const auto displayId = display->getId();
1135 LOG_ALWAYS_FATAL_IF(!displayId);
1136
Ady Abrahamabc27602020-04-08 17:20:29 -07001137 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001138
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001139 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001140 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001141 constraints.desiredTimeNanos = systemTime();
1142 constraints.seamlessRequired = false;
1143
Peiyong Line9d809e2020-04-14 13:10:48 -07001144 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001145 auto status =
1146 getHwComposer().setActiveConfigWithConstraints(*displayId,
1147 mUpcomingActiveConfig.configId.value(),
1148 constraints, &outTimeline);
1149 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001150 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1151 // to be sent. We just log the error in this case.
1152 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001153 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001154 }
1155
1156 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1157 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001158 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001159}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001160
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001161status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1162 Vector<ColorMode>* outColorModes) {
1163 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001164 return BAD_VALUE;
1165 }
1166
Peiyong Lina52f0292018-03-14 17:26:31 -07001167 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001168 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001169 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001170 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1171
1172 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1173 if (!displayId) {
1174 return NAME_NOT_FOUND;
1175 }
1176
Dominik Laskowski075d3172018-05-24 15:50:06 -07001177 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001178 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001179 }
Michael Wright28f24d02016-07-12 13:30:53 -07001180 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001181
1182 // If it's built-in display and the configuration claims it's not wide color capable,
1183 // filter out all wide color modes. The typical reason why this happens is that the
1184 // hardware is not good enough to support GPU composition of wide color, and thus the
1185 // OEMs choose to disable this capability.
1186 if (isInternalDisplay && !hasWideColorDisplay) {
1187 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1188 isWideColorMode);
1189 } else {
1190 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1191 }
Michael Wright28f24d02016-07-12 13:30:53 -07001192
1193 return NO_ERROR;
1194}
1195
Daniel Solomon42d04562019-01-20 21:03:19 -08001196status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1197 ui::DisplayPrimaries &primaries) {
1198 if (!displayToken) {
1199 return BAD_VALUE;
1200 }
1201
1202 // Currently we only support this API for a single internal display.
1203 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001204 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001205 }
1206
1207 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1208 return NO_ERROR;
1209}
1210
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001211ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001212 Mutex::Autolock lock(mStateLock);
1213
1214 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001215 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001216 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001217 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001218}
1219
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001220status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001221 schedule([=]() MAIN_THREAD {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001222 Vector<ColorMode> modes;
1223 getDisplayColorModes(displayToken, &modes);
1224 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1225 if (mode < ColorMode::NATIVE || !exists) {
1226 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1227 decodeColorMode(mode).c_str(), mode, displayToken.get());
1228 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001229 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001230 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001231 if (!display) {
1232 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1233 decodeColorMode(mode).c_str(), mode, displayToken.get());
1234 } else if (display->isVirtual()) {
1235 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1236 decodeColorMode(mode).c_str(), mode);
1237 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001238 display->getCompositionDisplay()->setColorProfile(
1239 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1240 RenderIntent::COLORIMETRIC,
1241 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001242 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001243 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001244
Michael Wright28f24d02016-07-12 13:30:53 -07001245 return NO_ERROR;
1246}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001247
Galia Peycheva5492cb52019-10-30 14:13:16 +01001248status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1249 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001250 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001251 return BAD_VALUE;
1252 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001253
1254 Mutex::Autolock lock(mStateLock);
1255
Galia Peycheva5492cb52019-10-30 14:13:16 +01001256 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1257 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001258 return NAME_NOT_FOUND;
1259 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001260 *outSupport =
1261 getHwComposer().hasDisplayCapability(*displayId,
1262 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001263 return NO_ERROR;
1264}
1265
1266void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001267 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001268 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1269 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1270 } else {
1271 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1272 }
1273 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001274}
1275
1276status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1277 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001278 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001279 return BAD_VALUE;
1280 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001281
1282 Mutex::Autolock lock(mStateLock);
1283
Galia Peycheva5492cb52019-10-30 14:13:16 +01001284 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1285 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001286 return NAME_NOT_FOUND;
1287 }
1288
Peiyong Line9d809e2020-04-14 13:10:48 -07001289 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001290 getHwComposer().getSupportedContentTypes(*displayId, &types);
1291
1292 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001293 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001294 return NO_ERROR;
1295}
1296
1297void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001298 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001299 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001300 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001301 getHwComposer().setContentType(*displayId, type);
1302 } else {
1303 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1304 }
1305 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001306}
1307
Svetoslavd85084b2014-03-20 10:28:31 -07001308status_t SurfaceFlinger::clearAnimationFrameStats() {
1309 Mutex::Autolock _l(mStateLock);
1310 mAnimFrameTracker.clearStats();
1311 return NO_ERROR;
1312}
1313
1314status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1315 Mutex::Autolock _l(mStateLock);
1316 mAnimFrameTracker.getStats(outStats);
1317 return NO_ERROR;
1318}
1319
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001320status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1321 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001322 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001323
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001324 const auto display = getDisplayDeviceLocked(displayToken);
1325 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001326 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1327 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001328 }
1329
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001330 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001331 // meaning the luminance information is already queried from
1332 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001333 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001334 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1335 capabilities.getDesiredMaxLuminance(),
1336 capabilities.getDesiredMaxAverageLuminance(),
1337 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001338
1339 return NO_ERROR;
1340}
1341
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001342std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1343 const DisplayDevice& display) const {
1344 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1345 // avoid repetitive HAL IPC and EDID parsing.
1346 const auto displayId = display.getId();
1347 LOG_FATAL_IF(!displayId);
1348
1349 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1350 LOG_FATAL_IF(!hwcDisplayId);
1351
1352 uint8_t port;
1353 DisplayIdentificationData data;
1354 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1355 ALOGV("%s: No identification data.", __FUNCTION__);
1356 return {};
1357 }
1358
1359 const auto info = parseDisplayIdentificationData(port, data);
1360 if (!info) {
1361 return {};
1362 }
1363 return info->deviceProductInfo;
1364}
1365
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001366status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1367 ui::PixelFormat* outFormat,
1368 ui::Dataspace* outDataspace,
1369 uint8_t* outComponentMask) const {
1370 if (!outFormat || !outDataspace || !outComponentMask) {
1371 return BAD_VALUE;
1372 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001373
1374 Mutex::Autolock lock(mStateLock);
1375
1376 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1377 if (!displayId) {
1378 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001379 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001380
1381 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001382 outDataspace, outComponentMask);
1383}
1384
Kevin DuBois74e53772018-11-19 10:52:38 -08001385status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1386 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001387 uint64_t maxFrames) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001388 return schedule([=]() MAIN_THREAD -> status_t {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001389 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1390 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1391 componentMask,
1392 maxFrames);
1393 } else {
1394 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1395 return NAME_NOT_FOUND;
1396 }
1397 })
1398 .get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001399}
1400
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001401status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1402 uint64_t maxFrames, uint64_t timestamp,
1403 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001404 Mutex::Autolock lock(mStateLock);
1405
1406 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1407 if (!displayId) {
1408 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001409 }
1410
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001411 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001412}
1413
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001414status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1415 if (!outSupported) {
1416 return BAD_VALUE;
1417 }
1418 *outSupported = getRenderEngine().supportsProtectedContent();
1419 return NO_ERROR;
1420}
1421
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001422status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1423 bool* outIsWideColorDisplay) const {
1424 if (!displayToken || !outIsWideColorDisplay) {
1425 return BAD_VALUE;
1426 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001427
1428 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001429 const auto display = getDisplayDeviceLocked(displayToken);
1430 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001431 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001432 }
Peiyong Linff84a152019-05-17 18:36:19 -07001433
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001434 *outIsWideColorDisplay =
1435 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001436 return NO_ERROR;
1437}
1438
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001439status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001440 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001441 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001442
Dominik Laskowski6505f792019-09-18 11:10:05 -07001443 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1444 mEventQueue->setEventConnection(
1445 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001446 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001447 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001448
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001449 return NO_ERROR;
1450}
1451
1452status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001453 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001454 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001455}
1456
Vishnu Nair43bccf82020-06-05 10:53:37 -07001457status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001458 outLayers->clear();
Vishnu Nair43bccf82020-06-05 10:53:37 -07001459 schedule([=] {
1460 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
1461 mDrawingState.traverseInZOrder([&](Layer* layer) {
1462 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1463 });
1464 }).wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001465 return NO_ERROR;
1466}
1467
Peiyong Linc6780972018-10-28 15:24:08 -07001468status_t SurfaceFlinger::getCompositionPreference(
1469 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1470 Dataspace* outWideColorGamutDataspace,
1471 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001472 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001473 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001474 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001475 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001476 return NO_ERROR;
1477}
1478
Dan Stozaec460082018-12-17 15:35:09 -08001479status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1480 const sp<IBinder>& stopLayerHandle,
1481 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001482 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001483 return BAD_VALUE;
1484 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001485
1486 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1487 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001488 return NO_ERROR;
1489}
1490
Dan Stozaec460082018-12-17 15:35:09 -08001491status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001492 if (!listener) {
1493 return BAD_VALUE;
1494 }
Dan Stozaec460082018-12-17 15:35:09 -08001495 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001496 return NO_ERROR;
1497}
Dan Gittik57e63c52019-01-18 16:37:54 +00001498
1499status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1500 bool* outSupport) const {
1501 if (!displayToken || !outSupport) {
1502 return BAD_VALUE;
1503 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001504
1505 Mutex::Autolock lock(mStateLock);
1506
Dan Gittik57e63c52019-01-18 16:37:54 +00001507 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1508 if (!displayId) {
1509 return NAME_NOT_FOUND;
1510 }
1511 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001512 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001513 return NO_ERROR;
1514}
1515
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001516status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001517 if (!displayToken) {
1518 return BAD_VALUE;
1519 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001520
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001521 return promise::chain(schedule([=]() MAIN_THREAD {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001522 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1523 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1524 } else {
1525 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001526 return promise::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001527 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001528 }))
1529 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001530 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001531}
1532
Ady Abraham8532d012019-05-08 14:50:56 -07001533status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1534 PowerHint powerHint = static_cast<PowerHint>(hintId);
1535
1536 if (powerHint == PowerHint::INTERACTION) {
1537 mScheduler->notifyTouchEvent();
1538 }
1539
1540 return NO_ERROR;
1541}
1542
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001543// ----------------------------------------------------------------------------
1544
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001545sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001546 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001547 const auto& handle =
1548 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001549
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001550 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001551}
1552
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001553void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001554 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001555 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001556 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001557}
1558
1559void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001560 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001561 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001562 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001563}
1564
1565void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001566 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001567 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001568}
1569
Dominik Laskowski83b88212018-12-11 13:34:06 -08001570nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001571 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001572 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1573 return 0;
1574 }
1575
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001576 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001577}
1578
Peiyong Line9d809e2020-04-14 13:10:48 -07001579void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001580 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001581 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001582 ATRACE_NAME("SF onVsync");
1583
Steven Thomas3cfac282017-02-06 12:29:30 -08001584 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001585 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001586 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001587 return;
1588 }
1589
Dominik Laskowski075d3172018-05-24 15:50:06 -07001590 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001591 return;
1592 }
1593
Dominik Laskowski075d3172018-05-24 15:50:06 -07001594 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001595 // For now, we don't do anything with external display vsyncs.
1596 return;
1597 }
1598
Alec Mourif8e689c2019-05-20 18:32:22 -07001599 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001600 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001601 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001602 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001603 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001604}
1605
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001607 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1608 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001609}
1610
Ady Abraham2139f732019-11-13 18:56:40 -08001611bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001612 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001613}
1614
Ady Abraham2139f732019-11-13 18:56:40 -08001615void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1616 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001617 const auto display = getDefaultDisplayDeviceLocked();
1618 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001619 return;
1620 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001621 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001622
Ana Krulec7d1d6832018-12-27 11:10:09 -08001623 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001624 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001625 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001626 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001627 return;
1628 }
1629
Ady Abrahamabc27602020-04-08 17:20:29 -07001630 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001631}
1632
Peiyong Line9d809e2020-04-14 13:10:48 -07001633void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001634 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001635 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001636 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001637
Lloyd Piqueba04e622017-12-14 17:11:26 -08001638 // Ignore events that do not have the right sequenceId.
1639 if (sequenceId != getBE().mComposerSequenceId) {
1640 return;
1641 }
1642
Steven Thomasb02664d2017-07-26 18:48:28 -07001643 // Only lock if we're not on the main thread. This function is normally
1644 // called on a hwbinder thread, but for the primary display it's called on
1645 // the main thread with the state lock already held, so don't attempt to
1646 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001647 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001648
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001649 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001650
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001651 if (std::this_thread::get_id() == mMainThreadId) {
1652 // Process all pending hot plug events immediately if we are on the main thread.
1653 processDisplayHotplugEventsLocked();
1654 }
1655
Lloyd Piqueba04e622017-12-14 17:11:26 -08001656 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001657}
1658
Ady Abraham7159f572019-10-11 11:10:18 -07001659void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001660 int32_t sequenceId, hal::HWDisplayId /*display*/,
1661 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001662 Mutex::Autolock lock(mStateLock);
1663 if (sequenceId != getBE().mComposerSequenceId) {
1664 return;
1665 }
1666 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001667}
1668
Peiyong Line9d809e2020-04-14 13:10:48 -07001669void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001670 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1671 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1672}
1673
Peiyong Line9d809e2020-04-14 13:10:48 -07001674void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001675 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001676 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001677 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001678 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001679 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001680}
1681
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001682void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001683 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001684
1685 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1686 // display power state.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001687 static_cast<void>(schedule([=]() MAIN_THREAD { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001688}
1689
1690void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1691 ATRACE_CALL();
1692
Peiyong Line9d809e2020-04-14 13:10:48 -07001693 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001694
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001695 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001696 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1697 if (display && display->isPoweredOn()) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02001698 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001699 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001700 }
Mathias Agopian86303202012-07-24 22:46:10 -07001701}
1702
Steven Thomasb02664d2017-07-26 18:48:28 -07001703void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001704 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001705 // Clear the drawing state so that the logic inside of
1706 // handleTransactionLocked will fire. It will determine the delta between
1707 // mCurrentState and mDrawingState and re-apply all changes when we make the
1708 // transition.
1709 mDrawingState.displays.clear();
1710 mDisplays.clear();
1711}
1712
Steven Thomas050b2c82017-03-06 11:45:16 -08001713void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001714 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001715 if (!mVrFlinger)
1716 return;
1717 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001718 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001719 return;
1720 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001721
Lloyd Pique441d5042018-10-18 16:49:51 -07001722 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001723 ALOGE("Vr flinger is only supported for remote hardware composer"
1724 " service connections. Ignoring request to transition to vr"
1725 " flinger.");
1726 mVrFlingerRequestsDisplay = false;
1727 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001728 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001729
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001730 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001731
Steven Thomas0123ac62018-07-12 11:32:34 -07001732 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001733 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001734
Peiyong Lin65248e02020-04-18 21:15:07 -07001735 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001736
1737 // Clear out all the output layers from the composition engine for all
1738 // displays before destroying the hardware composer interface. This ensures
1739 // any HWC layers are destroyed through that interface before it becomes
1740 // invalid.
1741 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001742 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001743 }
1744
Steven Thomas0123ac62018-07-12 11:32:34 -07001745 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1746 // called below. Clear the reference now so we don't accidentally use it
1747 // later.
1748 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001749
Steven Thomasb02664d2017-07-26 18:48:28 -07001750 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001751 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001752 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001753
Steven Thomasb02664d2017-07-26 18:48:28 -07001754 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001755 // Delete the current instance before creating the new one
1756 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1757 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1758 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001759 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001760
Lloyd Pique441d5042018-10-18 16:49:51 -07001761 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001762 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001763
1764 if (vrFlingerRequestsDisplay) {
1765 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001766 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001767
1768 mVisibleRegionsDirty = true;
1769 invalidateHwcGeometry();
1770
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001771 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001772 display = getDefaultDisplayDeviceLocked();
1773 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001774 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001775
Steven Thomasb02664d2017-07-26 18:48:28 -07001776 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001777 const nsecs_t vsyncPeriod = getVsyncPeriod();
1778 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001779
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001780 // The present fences returned from vr_hwc are not an accurate
1781 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001782 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001783
Steven Thomasb02664d2017-07-26 18:48:28 -07001784 // Use phase of 0 since phase is not known.
1785 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001786 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001787 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001788
Ana Krulecc2870422019-01-29 19:00:58 -08001789 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001790
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001791 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001792 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001793}
1794
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001795sp<Fence> SurfaceFlinger::previousFrameFence() {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001796 // We are storing the last 2 present fences. If sf's phase offset is to be
1797 // woken up before the actual vsync but targeting the next vsync, we need to check
1798 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001799 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1800 : mPreviousPresentFences[1];
1801}
1802
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001803bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001804 ATRACE_CALL();
1805 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001806
Ady Abraham11579302019-09-19 12:35:58 -07001807 if (fence == Fence::NO_FENCE) {
1808 return false;
1809 }
1810
Dan Stoza59083052020-04-28 10:13:20 -07001811 const status_t status = fence->wait(graceTimeMs);
1812 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1813 // which calls wait(0) again internally
1814 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001815}
1816
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001817nsecs_t SurfaceFlinger::previousFramePresentTime() {
Alec Mouri6d414b52020-03-17 11:18:05 -07001818 const sp<Fence>& fence = previousFrameFence();
1819
1820 if (fence == Fence::NO_FENCE) {
1821 return Fence::SIGNAL_TIME_INVALID;
1822 }
1823
1824 return fence->getSignalTime();
1825}
1826
Ady Abraham5facfb12020-04-22 15:18:31 -07001827nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001828 DisplayStatInfo stats;
1829 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001830 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001831 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001832 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001833}
1834
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001835void SurfaceFlinger::onMessageReceived(int32_t what, nsecs_t expectedVSyncTime) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001836 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001837 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001838 case MessageQueue::INVALIDATE: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001839 onMessageInvalidate(expectedVSyncTime);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001840 break;
1841 }
1842 case MessageQueue::REFRESH: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001843 onMessageRefresh();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001844 break;
1845 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001846 }
1847}
1848
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001849void SurfaceFlinger::onMessageInvalidate(nsecs_t expectedVSyncTime) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001850 ATRACE_CALL();
1851
1852 const nsecs_t frameStart = systemTime();
1853 // calculate the expected present time once and use the cached
1854 // value throughout this frame to make sure all layers are
1855 // seeing this same value.
1856 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
1857 mExpectedPresentTime = expectedVSyncTime;
1858
1859 // When Backpressure propagation is enabled we want to give a small grace period
1860 // for the present fence to fire instead of just giving up on this frame to handle cases
1861 // where present fence is just about to get signaled.
1862 const int graceTimeForPresentFenceMs =
1863 (mPropagateBackpressure &&
1864 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1865 ? 1
1866 : 0;
1867
1868 // Pending frames may trigger backpressure propagation.
1869 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1870 previousFramePending(graceTimeForPresentFenceMs)};
1871
1872 // Frame missed counts for metrics tracking.
1873 // A frame is missed if the prior frame is still pending. If no longer pending,
1874 // then we still count the frame as missed if the predicted present time
1875 // was further in the past than when the fence actually fired.
1876
1877 // Add some slop to correct for drift. This should generally be
1878 // smaller than a typical frame duration, but should not be so small
1879 // that it reports reasonable drift as a missed frame.
1880 DisplayStatInfo stats;
1881 mScheduler->getDisplayStatInfo(&stats);
1882 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1883 const nsecs_t previousPresentTime = previousFramePresentTime();
1884 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
1885 framePending ||
1886 (previousPresentTime >= 0 &&
1887 (lastExpectedPresentTime <
1888 previousPresentTime - frameMissedSlop))};
1889 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
1890 mHadDeviceComposition && frameMissed};
1891 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
1892 mHadClientComposition && frameMissed};
1893
1894 if (frameMissed) {
1895 mFrameMissedCount++;
1896 mTimeStats->incrementMissedFrames();
1897 if (mMissedFrameJankCount == 0) {
1898 mMissedFrameJankStart = systemTime();
1899 }
1900 mMissedFrameJankCount++;
1901 }
1902
1903 if (hwcFrameMissed) {
1904 mHwcFrameMissedCount++;
1905 }
1906
1907 if (gpuFrameMissed) {
1908 mGpuFrameMissedCount++;
1909 }
1910
1911 // If we are in the middle of a config change and the fence hasn't
1912 // fired yet just wait for the next invalidate
1913 if (mSetActiveConfigPending) {
1914 if (framePending) {
1915 mEventQueue->invalidate();
1916 return;
1917 }
1918
1919 // We received the present fence from the HWC, so we assume it successfully updated
1920 // the config, hence we update SF.
1921 mSetActiveConfigPending = false;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001922 ON_MAIN_THREAD(setActiveConfigInternal());
Dan Stoza28d46a52020-04-28 09:54:54 -07001923 }
1924
1925 if (framePending && mPropagateBackpressure) {
1926 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
1927 signalLayerUpdate();
1928 return;
1929 }
1930 }
1931
1932 // Our jank window is always at least 100ms since we missed a
1933 // frame...
1934 static constexpr nsecs_t kMinJankyDuration =
1935 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1936 // ...but if it's larger than 1s then we missed the trace cutoff.
1937 static constexpr nsecs_t kMaxJankyDuration =
1938 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001939 nsecs_t jankDurationToUpload = -1;
Dan Stoza28d46a52020-04-28 09:54:54 -07001940 // If we're in a user build then don't push any atoms
1941 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001942 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dan Stoza28d46a52020-04-28 09:54:54 -07001943 // Only report jank when the display is on, as displays in DOZE
1944 // power mode may operate at a different frame rate than is
1945 // reported in their config, which causes noticeable (but less
1946 // severe) jank.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001947 if (display && display->getPowerMode() == hal::PowerMode::ON) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001948 const nsecs_t currentTime = systemTime();
1949 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1950 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001951 jankDurationToUpload = jankDuration;
Dan Stoza28d46a52020-04-28 09:54:54 -07001952 }
1953
1954 // We either reported a jank event or we missed the trace
1955 // window, so clear counters here.
1956 if (jankDuration > kMinJankyDuration) {
1957 mMissedFrameJankCount = 0;
1958 mMissedFrameJankStart = 0;
1959 }
1960 }
1961 }
1962
1963 // Now that we're going to make it to the handleMessageTransaction()
1964 // call below it's safe to call updateVrFlinger(), which will
1965 // potentially trigger a display handoff.
1966 updateVrFlinger();
1967
1968 if (mTracingEnabledChanged) {
1969 mTracingEnabled = mTracing.isEnabled();
1970 mTracingEnabledChanged = false;
1971 }
1972
1973 bool refreshNeeded;
1974 {
1975 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1976
1977 refreshNeeded = handleMessageTransaction();
1978 refreshNeeded |= handleMessageInvalidate();
1979 if (mTracingEnabled) {
1980 mAddCompositionStateToTrace =
1981 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1982 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1983 mTracing.notifyLocked("visibleRegionsDirty");
1984 }
1985 }
1986 }
1987
1988 // Layers need to get updated (in the previous line) before we can use them for
1989 // choosing the refresh rate.
1990 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1991 // and may eventually call to ~Layer() if it holds the last reference
1992 {
1993 Mutex::Autolock _l(mStateLock);
1994 mScheduler->chooseRefreshRateForContent();
1995 }
1996
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001997 ON_MAIN_THREAD(performSetActiveConfig());
Dan Stoza28d46a52020-04-28 09:54:54 -07001998
1999 updateCursorAsync();
2000 updateInputFlinger();
2001
2002 refreshNeeded |= mRepaintEverything;
2003 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002004 mLastJankDuration = jankDurationToUpload;
Dan Stoza28d46a52020-04-28 09:54:54 -07002005 // Signal a refresh if a transaction modified the window state,
2006 // a new buffer was latched, or if HWC has requested a full
2007 // repaint
2008 if (mFrameStartTime <= 0) {
2009 // We should only use the time of the first invalidate
2010 // message that signals a refresh as the beginning of the
2011 // frame. Otherwise the real frame time will be
2012 // underestimated.
2013 mFrameStartTime = frameStart;
2014 }
2015 signalRefresh();
2016 }
2017}
2018
Dan Stoza6b9454d2014-11-07 16:00:59 -08002019bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08002020 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002021 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002022
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002023 bool flushedATransaction = flushTransactionQueues();
2024
Valerie Hau47826a72020-06-15 12:34:40 -07002025 bool runHandleTransaction =
2026 (transactionFlags && (transactionFlags != eTransactionFlushNeeded)) ||
Robert Carr6417d2e2020-06-24 15:26:32 -07002027 flushedATransaction ||
2028 mForceTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002029
2030 if (runHandleTransaction) {
2031 handleTransaction(eTransactionMask);
2032 } else {
2033 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002034 }
2035
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002036 if (transactionFlushNeeded()) {
2037 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002038 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002039
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002040 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002041}
2042
Dan Stoza28d46a52020-04-28 09:54:54 -07002043void SurfaceFlinger::onMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002044 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002045
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002046 mRefreshPending = false;
2047
Lloyd Piqueab039b52019-02-13 14:22:42 -08002048 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002049 const auto& displays = ON_MAIN_THREAD(mDisplays);
2050 refreshArgs.outputs.reserve(displays.size());
2051 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002052 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2053 }
2054 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002055 if (auto layerFE = layer->getCompositionEngineLayerFE())
2056 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002057 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002058 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2059 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002060 if (auto layerFE = layer->getCompositionEngineLayerFE())
2061 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002062 }
2063
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002064 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002065 refreshArgs.outputColorSetting = useColorManagement
2066 ? mDisplayColorSetting
2067 : compositionengine::OutputColorSetting::kUnmanaged;
2068 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2069 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002070
2071 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2072 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002073 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002074 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002075
2076 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2077 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2078 mDrawingState.colorMatrixChanged = false;
2079 }
2080
2081 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2082
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002083 if (mDebugRegion != 0) {
2084 refreshArgs.devOptFlashDirtyRegionsDelay =
2085 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2086 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002087
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002088 mGeometryInvalid = false;
2089
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002090 // Store the present time just before calling to the composition engine so we could notify
2091 // the scheduler.
2092 const auto presentTime = systemTime();
2093
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002094 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002095 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2096 // Reset the frame start time now that we've recorded this frame.
2097 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002098
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002099 mScheduler->onDisplayRefreshed(presentTime);
2100
David Sodmanfa9b2af2017-12-24 13:28:59 -08002101 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002102 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002103
Alec Mouri8f7a0102020-04-15 12:11:10 -07002104 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2105
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002106 mHadClientComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2107 const auto& state = pair.second->getCompositionDisplay()->getState();
2108 return state.usesClientComposition && !state.reusedClientComposition;
2109 });
2110 mHadDeviceComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2111 const auto& state = pair.second->getCompositionDisplay()->getState();
2112 return state.usesDeviceComposition;
2113 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002114 mReusedClientComposition =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002115 std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2116 const auto& state = pair.second->getCompositionDisplay()->getState();
2117 return state.reusedClientComposition;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002118 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002119
Alec Mouri8f7a0102020-04-15 12:11:10 -07002120 // Only report a strategy change if we move in and out of composition with hw overlays
2121 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2122 mTimeStats->incrementCompositionStrategyChanges();
2123 }
2124
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002125 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002126
David Sodman7e4ae112018-02-09 15:02:28 -08002127 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002128 if (mVisibleRegionsDirty) {
2129 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002130 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002131 mTracing.notify("visibleRegionsDirty");
2132 }
2133 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002134
2135 if (mCompositionEngine->needsAnotherUpdate()) {
2136 signalLayerUpdate();
2137 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002138}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002139
David Sodmanfa9b2af2017-12-24 13:28:59 -08002140bool SurfaceFlinger::handleMessageInvalidate() {
2141 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002142 bool refreshNeeded = handlePageFlip();
2143
Vishnu Nair4351ad52019-02-11 14:13:02 -08002144 if (mVisibleRegionsDirty) {
2145 computeLayerBounds();
2146 }
2147
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002148 for (auto& layer : mLayersPendingRefresh) {
2149 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002150 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002151 invalidateLayerStack(layer, visibleReg);
2152 }
2153 mLayersPendingRefresh.clear();
2154 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002155}
2156
Ana Krulece588e312018-09-18 12:32:24 -07002157void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2158 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002159 // Update queue of past composite+present times and determine the
2160 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002161 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002162 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002163 while (!getBE().mCompositePresentTimes.empty()) {
2164 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002165 // Cached values should have been updated before calling this method,
2166 // which helps avoid duplicate syscalls.
2167 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2168 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2169 break;
2170 }
2171 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002172 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002173 }
2174
2175 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002176 while (getBE().mCompositePresentTimes.size() > 16) {
2177 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002178 }
2179
Ana Krulece588e312018-09-18 12:32:24 -07002180 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002181}
2182
Ana Krulece588e312018-09-18 12:32:24 -07002183void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2184 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002185 // Integer division and modulo round toward 0 not -inf, so we need to
2186 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002187 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2188 ? (stats.vsyncPeriod -
2189 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2190 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002191
Ady Abraham9e16a482019-12-03 17:19:41 -08002192 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002193 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002194 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002195 }
2196
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002197 // Snap the latency to a value that removes scheduling jitter from the
2198 // composition and present times, which often have >1ms of jitter.
2199 // Reducing jitter is important if an app attempts to extrapolate
2200 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002201 // Snapping also allows an app to precisely calculate
2202 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002203 nsecs_t bias = stats.vsyncPeriod / 2;
2204 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2205 nsecs_t snappedCompositeToPresentLatency =
2206 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002207
David Sodman99974d22017-11-28 12:04:33 -08002208 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002209 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2210 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002211 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002212}
2213
David Sodman2b406362017-12-15 13:33:47 -08002214void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002215{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002216 ATRACE_CALL();
2217 ALOGV("postComposition");
2218
Brian Andersonf6386862016-10-31 16:34:13 -07002219 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002220 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002221 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002222 }
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002223
2224 const auto* display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002225
David Sodman73beded2017-11-15 11:56:06 -08002226 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002227 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002228 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002229 glCompositionDoneFenceTime =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002230 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002231 ->getRenderSurface()
2232 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002233 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002234 } else {
2235 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2236 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002237
David Sodman73beded2017-11-15 11:56:06 -08002238 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002239 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002240 mPreviousPresentFences[0] =
2241 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Ady Abrahambe0f9482019-04-24 15:41:53 -07002242 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002243 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002244
Ana Krulece588e312018-09-18 12:32:24 -07002245 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002246 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002247
Lloyd Piqueab039b52019-02-13 14:22:42 -08002248 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2249 // be sampled a little later than when we started doing work for this frame,
2250 // but that should be okay since updateCompositorTiming has snapping logic.
2251 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2252 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002253 CompositorTiming compositorTiming;
2254 {
David Sodman99974d22017-11-28 12:04:33 -08002255 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2256 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002257 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002258
Edgar Arriaga844fa672020-01-16 14:21:42 -08002259 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002260 const bool frameLatched = layer->onPostComposition(display, glCompositionDoneFenceTime,
2261 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002262 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002263 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002264 }
Robert Carr2047fae2016-11-28 14:09:09 -08002265 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002266
Valerie Hau4b678442020-04-14 10:50:42 -07002267 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2268 mTransactionCompletedThread.sendCallbacks();
2269
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002270 if (display && display->isPrimary() && display->getPowerMode() == hal::PowerMode::ON &&
2271 presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002272 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002273 }
2274
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002275 const bool isDisplayConnected = display && getHwComposer().isConnected(*display->getId());
2276
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002277 if (!hasSyncFramework) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002278 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002279 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002280 }
2281 }
2282
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002283 if (mAnimCompositionPending) {
2284 mAnimCompositionPending = false;
2285
Brian Anderson4e606e32017-03-16 15:34:57 -07002286 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002287 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002288 std::move(presentFenceTime));
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002289 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002290 // The HWC doesn't support present fences, so use the refresh
2291 // timestamp instead.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002292 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002293 mAnimFrameTracker.setActualPresentTime(presentTime);
2294 }
2295 mAnimFrameTracker.advanceFrame();
2296 }
Dan Stozab90cf072015-03-05 11:05:59 -08002297
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002298 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002299 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002300 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002301 }
2302
Vishnu Nair9b079a22020-01-21 14:36:08 -08002303 if (mReusedClientComposition) {
2304 mTimeStats->incrementClientCompositionReusedFrames();
2305 }
2306
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002307 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002308
Alec Mouri717bcb62020-02-10 17:07:19 -08002309 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2310 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2311 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2312
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002313 if (mLastJankDuration > 0) {
2314 ATRACE_NAME("Jank detected");
2315 const int32_t jankyDurationMillis = mLastJankDuration / (1000 * 1000);
2316 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED, jankyDurationMillis,
2317 mMissedFrameJankCount);
2318 mLastJankDuration = -1;
2319 }
2320
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002321 if (isDisplayConnected && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002322 return;
2323 }
2324
2325 nsecs_t currentTime = systemTime();
2326 if (mHasPoweredOff) {
2327 mHasPoweredOff = false;
2328 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002329 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002330 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002331 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2332 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002333 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002334 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002335 }
David Sodman4a36e932017-11-07 14:29:47 -08002336 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002337 }
David Sodman4a36e932017-11-07 14:29:47 -08002338 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002339
Alec Mouri4dde1782019-09-30 17:27:13 -07002340 // Cleanup any outstanding resources due to rendering a prior frame.
2341 getRenderEngine().cleanupPostRender();
2342
Dan Stoza436ccf32018-06-21 12:10:12 -07002343 {
2344 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002345 if (mTexturePool.size() < mTexturePoolSize) {
2346 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002347 const size_t offset = mTexturePool.size();
2348 mTexturePool.resize(mTexturePoolSize);
2349 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2350 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002351 } else if (mTexturePool.size() > mTexturePoolSize) {
2352 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2353 const size_t offset = mTexturePoolSize;
2354 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2355 mTexturePool.resize(mTexturePoolSize);
2356 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002357 }
2358 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002359
Kevin DuBois413287f2019-02-25 08:46:47 -08002360 if (mLumaSampling && mRegionSamplingThread) {
2361 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002362 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002363
2364 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2365 // side-effect of getTotalSize(), so we check that again here
2366 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002367 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002368 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2369 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002370}
2371
Lloyd Pique7eebe692020-04-22 22:40:06 -07002372FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2373 return displayDevice.getViewport().toFloatRect();
2374}
2375
Vishnu Nair4351ad52019-02-11 14:13:02 -08002376void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002377 for (const auto& pair : ON_MAIN_THREAD(mDisplays)) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08002378 const auto& displayDevice = pair.second;
2379 const auto display = displayDevice->getCompositionDisplay();
2380 for (const auto& layer : mDrawingState.layersSortedByZ) {
2381 // only consider the layers on the given layer stack
2382 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002383 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002384 }
2385
Lloyd Pique7eebe692020-04-22 22:40:06 -07002386 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002387 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002388 }
2389 }
2390}
2391
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002392void SurfaceFlinger::postFrame() {
2393 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002394 if (display && getHwComposer().isConnected(*display->getId())) {
2395 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002396 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2397 logFrameStats();
2398 }
2399 }
2400}
2401
Mathias Agopian87baae12012-07-31 12:38:26 -07002402void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002403{
Mathias Agopian841cde52012-03-01 15:44:37 -08002404 ATRACE_CALL();
2405
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002406 // here we keep a copy of the drawing state (that is the state that's
2407 // going to be overwritten by handleTransactionLocked()) outside of
2408 // mStateLock so that the side-effects of the State assignment
2409 // don't happen with mStateLock held (which can cause deadlocks).
2410 State drawingState(mDrawingState);
2411
Mathias Agopianca4d3602011-05-19 15:38:14 -07002412 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002413 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002414
Mathias Agopianca4d3602011-05-19 15:38:14 -07002415 // Here we're guaranteed that some transaction flags are set
2416 // so we can call handleTransactionLocked() unconditionally.
2417 // We call getTransactionFlags(), which will also clear the flags,
2418 // with mStateLock held to guarantee that mCurrentState won't change
2419 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002420
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002421 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002422 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002423 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002424
Mathias Agopianca4d3602011-05-19 15:38:14 -07002425 mDebugInTransaction = 0;
2426 invalidateHwcGeometry();
2427 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002428}
2429
Lloyd Piqueba04e622017-12-14 17:11:26 -08002430void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2431 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002432 const std::optional<DisplayIdentificationInfo> info =
2433 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002434
Dominik Laskowski075d3172018-05-24 15:50:06 -07002435 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002436 continue;
2437 }
2438
Dominik Laskowski55c85402020-01-21 16:25:47 -08002439 const DisplayId displayId = info->id;
2440 const auto it = mPhysicalDisplayTokens.find(displayId);
2441
Peiyong Line9d809e2020-04-14 13:10:48 -07002442 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002443 if (it == mPhysicalDisplayTokens.end()) {
2444 ALOGV("Creating display %s", to_string(displayId).c_str());
2445
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002446 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002447 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002448 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002449
Dominik Laskowski075d3172018-05-24 15:50:06 -07002450 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002451 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2452 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002453 state.isSecure = true; // All physical displays are currently considered secure.
2454 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002455
2456 sp<IBinder> token = new BBinder();
2457 mCurrentState.displays.add(token, state);
2458 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2459
Dominik Laskowski075d3172018-05-24 15:50:06 -07002460 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002461 } else {
2462 ALOGV("Recreating display %s", to_string(displayId).c_str());
2463
2464 const auto token = it->second;
2465 auto& state = mCurrentState.displays.editValueFor(token);
2466 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002467 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002468 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002469 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002470
Dominik Laskowski55c85402020-01-21 16:25:47 -08002471 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002472 if (index >= 0) {
2473 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2474 mInterceptor->saveDisplayDeletion(state.sequenceId);
2475 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002476 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002477 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002478 }
2479
2480 processDisplayChangesLocked();
2481 }
2482
2483 mPendingHotplugEvents.clear();
2484}
2485
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002486void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002487 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2488 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002489}
2490
Lloyd Pique99d3da52018-01-22 17:48:03 -08002491sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002492 const wp<IBinder>& displayToken,
2493 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002494 const DisplayDeviceState& state,
2495 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002497 auto displayId = compositionDisplay->getDisplayId();
2498 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002499 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002500 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002501 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002502 creationArgs.hasWideColorGamut = false;
2503 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002504
Dominik Laskowski55c85402020-01-21 16:25:47 -08002505 if (const auto& physical = state.physical) {
2506 creationArgs.connectionType = physical->type;
2507 }
2508
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002509 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002510 creationArgs.isPrimary = isInternalDisplay;
2511
2512 if (useColorManagement && displayId) {
2513 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002514 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002515 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002516 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002517 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002518
Dominik Laskowski7e045462018-05-30 13:02:02 -07002519 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002520 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002521 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522 }
tangrobin6753a022018-08-10 10:58:54 +08002523 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002524
Dominik Laskowski075d3172018-05-24 15:50:06 -07002525 if (displayId) {
2526 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002527 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002528 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002529 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002530
Lloyd Pique90c115d2018-09-18 21:39:42 -07002531 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002532 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002533 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002534
Lloyd Pique99d3da52018-01-22 17:48:03 -08002535 // Make sure that composition can never be stalled by a virtual display
2536 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002537 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002538 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002539 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2540 }
2541
Dominik Laskowski718f9602019-11-09 20:01:35 -08002542 creationArgs.physicalOrientation =
2543 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002544
Lloyd Pique99d3da52018-01-22 17:48:03 -08002545 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002546 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002548 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002549
2550 if (maxFrameBufferAcquiredBuffers >= 3) {
2551 nativeWindowSurface->preallocateBuffers();
2552 }
2553
2554 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002555 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002556 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002558 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002560 display->getCompositionDisplay()->setColorProfile(
2561 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2562 RenderIntent::COLORIMETRIC,
2563 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002564 if (!state.isVirtual()) {
2565 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002566 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2567 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002568 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002570 display->setLayerStack(state.layerStack);
2571 display->setProjection(state.orientation, state.viewport, state.frame);
2572 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002573
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002574 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002575}
2576
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002577void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2578 const DisplayDeviceState& state) {
2579 int width = 0;
2580 int height = 0;
2581 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2582 if (state.physical) {
2583 const auto& activeConfig =
2584 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2585 width = activeConfig->getWidth();
2586 height = activeConfig->getHeight();
2587 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2588 } else if (state.surface != nullptr) {
2589 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2590 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2591 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2592 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2593 int intPixelFormat;
2594 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2595 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2596 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2597 } else {
2598 // Virtual displays without a surface are dormant:
2599 // they have external state (layer stack, projection,
2600 // etc.) but no internal state (i.e. a DisplayDevice).
2601 return;
2602 }
2603
2604 compositionengine::DisplayCreationArgsBuilder builder;
2605 if (const auto& physical = state.physical) {
2606 builder.setPhysical({physical->id, physical->type});
2607 }
2608 builder.setPixels(ui::Size(width, height));
2609 builder.setPixelFormat(pixelFormat);
2610 builder.setIsSecure(state.isSecure);
2611 builder.setLayerStackId(state.layerStack);
2612 builder.setPowerAdvisor(&mPowerAdvisor);
2613 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2614 builder.setName(state.displayName);
2615 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2616
2617 sp<compositionengine::DisplaySurface> displaySurface;
2618 sp<IGraphicBufferProducer> producer;
2619 sp<IGraphicBufferProducer> bqProducer;
2620 sp<IGraphicBufferConsumer> bqConsumer;
2621 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2622
2623 std::optional<DisplayId> displayId = compositionDisplay->getId();
2624
2625 if (state.isVirtual()) {
2626 sp<VirtualDisplaySurface> vds =
2627 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2628 bqConsumer, state.displayName);
2629
2630 displaySurface = vds;
2631 producer = vds;
2632 } else {
2633 ALOGE_IF(state.surface != nullptr,
2634 "adding a supported display, but rendering "
2635 "surface is provided (%p), ignoring it",
2636 state.surface.get());
2637
2638 LOG_ALWAYS_FATAL_IF(!displayId);
2639 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2640 maxGraphicsWidth, maxGraphicsHeight);
2641 producer = bqProducer;
2642 }
2643
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002644 LOG_FATAL_IF(!displaySurface);
2645 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2646 displaySurface, producer);
2647 mDisplays.emplace(displayToken, display);
2648 if (!state.isVirtual()) {
2649 LOG_FATAL_IF(!displayId);
2650 dispatchDisplayHotplugEvent(displayId->value, true);
2651 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002652
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002653 if (display->isPrimary()) {
2654 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002655 }
2656}
2657
2658void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2659 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2660 // Save display ID before disconnecting.
2661 const auto displayId = display->getId();
2662 display->disconnect();
2663
2664 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002665 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002666 dispatchDisplayHotplugEvent(displayId->value, false);
2667 }
2668 }
2669
2670 mDisplays.erase(displayToken);
2671}
2672
2673void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2674 const DisplayDeviceState& currentState,
2675 const DisplayDeviceState& drawingState) {
2676 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2677 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002678 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002679 // changing the surface is like destroying and recreating the DisplayDevice
2680 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2681 display->disconnect();
2682 }
2683 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002684 if (const auto& physical = currentState.physical) {
2685 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2686 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002687 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002688 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002689 const auto display = getDisplayDeviceLocked(displayToken);
2690 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002691 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002692 return;
2693 }
2694
2695 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2696 if (currentState.layerStack != drawingState.layerStack) {
2697 display->setLayerStack(currentState.layerStack);
2698 }
2699 if ((currentState.orientation != drawingState.orientation) ||
2700 (currentState.viewport != drawingState.viewport) ||
2701 (currentState.frame != drawingState.frame)) {
2702 display->setProjection(currentState.orientation, currentState.viewport,
2703 currentState.frame);
2704 }
2705 if (currentState.width != drawingState.width ||
2706 currentState.height != drawingState.height) {
2707 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07002708
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002709 if (display->isPrimary()) {
2710 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2711 }
Dominik Laskowski20134642020-04-20 22:36:44 -07002712
2713 if (mRefreshRateOverlay) {
2714 mRefreshRateOverlay->setViewport(display->getSize());
2715 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002716 }
2717 }
2718}
2719
Lloyd Pique347200f2017-12-14 17:00:15 -08002720void SurfaceFlinger::processDisplayChangesLocked() {
2721 // here we take advantage of Vector's copy-on-write semantics to
2722 // improve performance by skipping the transaction entirely when
2723 // know that the lists are identical
2724 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2725 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2726 if (!curr.isIdenticalTo(draw)) {
2727 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002728
2729 // find the displays that were removed
2730 // (ie: in drawing state but not in current state)
2731 // also handle displays that changed
2732 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002733 for (size_t i = 0; i < draw.size(); i++) {
2734 const wp<IBinder>& displayToken = draw.keyAt(i);
2735 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 if (j < 0) {
2737 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002738 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002739 } else {
2740 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002741 const DisplayDeviceState& currentState = curr[j];
2742 const DisplayDeviceState& drawingState = draw[i];
2743 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002744 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 }
2746
2747 // find displays that were added
2748 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002749 for (size_t i = 0; i < curr.size(); i++) {
2750 const wp<IBinder>& displayToken = curr.keyAt(i);
2751 if (draw.indexOfKey(displayToken) < 0) {
2752 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002753 }
2754 }
2755 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002756
2757 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002758}
2759
Mathias Agopian87baae12012-07-31 12:38:26 -07002760void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002761{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002762 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2763
Dan Stoza7dde5992015-05-22 09:51:44 -07002764 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002765 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002766 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002767 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002768
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 /*
2770 * Traversal of the children
2771 * (perform the transaction for each of them if needed)
2772 */
2773
Valerie Haud50e7412020-06-16 17:58:14 -07002774 if ((transactionFlags & eTraversalNeeded) || mForceTraversal) {
2775 mForceTraversal = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002776 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002778 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779
2780 const uint32_t flags = layer->doTransaction(0);
2781 if (flags & Layer::eVisibleRegion)
2782 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002783
2784 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002785 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002786 }
Robert Carr2047fae2016-11-28 14:09:09 -08002787 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788 }
2789
2790 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002791 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792 */
2793
Mathias Agopiane57f2922012-08-09 16:29:12 -07002794 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002795 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002796 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002797 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798
Vishnu Nair6213bd92020-05-08 17:42:25 -07002799 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002800 // The transform hint might have changed for some layers
2801 // (either because a display has changed, or because a layer
2802 // as changed).
2803 //
2804 // Walk through all the layers in currentLayers,
2805 // and update their transform hint.
2806 //
2807 // If a layer is visible only on a single display, then that
2808 // display is used to calculate the hint, otherwise we use the
2809 // default display.
2810 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002811 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002812 // the hint is set before we acquire a buffer from the surface texture.
2813 //
2814 // NOTE: layer transactions have taken place already, so we use their
2815 // drawing state. However, SurfaceFlinger's own transaction has not
2816 // happened yet, so we must use the current state layer list
2817 // (soon to become the drawing state list).
2818 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002819 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002820 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002821 bool first = true;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002822 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08002823 // NOTE: we rely on the fact that layers are sorted by
2824 // layerStack first (so we don't have to traverse the list
2825 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002826 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002827 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002828 currentlayerStack = layerStack;
2829 // figure out if this layerstack is mirrored
2830 // (more than one display) if so, pick the default display,
2831 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002832 hintDisplay = nullptr;
2833 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002834 if (display->getCompositionDisplay()
2835 ->belongsInOutput(layer->getLayerStack(),
2836 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002837 if (hintDisplay) {
2838 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002839 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002840 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002841 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002842 }
2843 }
2844 }
2845 }
Chet Haase91d25932013-04-11 15:24:55 -07002846
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002847 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002848 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2849 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002850
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002851 // could be null when this layer is using a layerStack
2852 // that is not visible on any display. Also can occur at
2853 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002854 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002855 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002856
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002857 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002858 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002859 if (hintDisplay) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002860 layer->updateTransformHint(hintDisplay->getTransformHint());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002861 }
Robert Carr2047fae2016-11-28 14:09:09 -08002862
2863 first = false;
2864 });
Mathias Agopian84300952012-11-21 16:02:13 -08002865 }
2866
Mathias Agopian3559b072012-08-15 13:46:03 -07002867 /*
2868 * Perform our own transaction if needed
2869 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002870
2871 if (mLayersAdded) {
2872 mLayersAdded = false;
2873 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002874 mVisibleRegionsDirty = true;
2875 }
2876
2877 // some layers might have been removed, so
2878 // we need to update the regions they're exposing.
2879 if (mLayersRemoved) {
2880 mLayersRemoved = false;
2881 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002882 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002884 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002885 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002886 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002887 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002888 }
Robert Carr2047fae2016-11-28 14:09:09 -08002889 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890 }
2891
Vishnu Nairec0ab382019-02-13 15:32:56 -08002892 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002894}
2895
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002896void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002897 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002898 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002899 return;
2900 }
2901
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002902 if (mVisibleRegionsDirty || mInputInfoChanged) {
2903 mInputInfoChanged = false;
2904 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002905 } else if (mInputWindowCommands.syncInputWindows) {
2906 // If the caller requested to sync input windows, but there are no
2907 // changes to input windows, notify immediately.
2908 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002909 }
2910
Arthur Hung6cbb9752019-09-05 16:38:18 +08002911 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002912}
2913
2914void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002915 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002916
2917 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Robert Carredd13602020-04-13 17:24:34 -07002918 if (layer->needsInputInfo()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002919 // When calculating the screen bounds we ignore the transparent region since it may
2920 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002921 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002922 }
2923 });
chaviw291d88a2019-02-14 10:33:58 -08002924
2925 mInputFlinger->setInputWindows(inputHandles,
2926 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2927 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002928}
2929
Vishnu Nairec0ab382019-02-13 15:32:56 -08002930void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002931 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002932 mPendingInputWindowCommands.clear();
2933}
2934
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002935void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002936 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002937 for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002938 if (display->getId()) {
2939 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002940 }
2941 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002942
2943 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002944}
2945
Ady Abraham2139f732019-11-13 18:56:40 -08002946void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002947 Scheduler::ConfigEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08002948 // If this is called from the main thread mStateLock must be locked before
2949 // Currently the only way to call this function from the main thread is from
2950 // Sheduler::chooseRefreshRateForContent
2951
2952 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002953 changeRefreshRateLocked(refreshRate, event);
2954}
2955
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002956void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2957 if (mScheduler) {
2958 // In practice it's not allowed to hotplug in/out the primary display once it's been
2959 // connected during startup, but some tests do it, so just warn and return.
2960 ALOGW("Can't re-init scheduler");
2961 return;
2962 }
2963
Ady Abraham2139f732019-11-13 18:56:40 -08002964 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002965 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002966 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002967 primaryDisplayId),
2968 currentConfig);
2969 mRefreshRateStats =
2970 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002971 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002972 mRefreshRateStats->setConfigMode(currentConfig);
2973
Ady Abraham9e16a482019-12-03 17:19:41 -08002974 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2975
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002976 // start the EventThread
2977 mScheduler =
2978 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002979 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002980 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002981 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002982 impl::EventThread::InterceptVSyncsCallback());
2983 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002984 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002985 [this](nsecs_t timestamp) {
2986 mInterceptor->saveVSyncEvent(timestamp);
2987 });
2988
2989 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2990 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002991 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002992
2993 mRegionSamplingThread =
2994 new RegionSamplingThread(*this, *mScheduler,
2995 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002996 // Dispatch a config change request for the primary display on scheduler
2997 // initialization, so that the EventThreads always contain a reference to a
2998 // prior configuration.
2999 //
3000 // This is a bit hacky, but this avoids a back-pointer into the main SF
3001 // classes from EventThread, and there should be no run-time binder cost
3002 // anyway since there are no connected apps at this point.
3003 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07003004 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07003005 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, primaryDisplayId.value,
3006 currentConfig, vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003007}
3008
Mathias Agopian4fec8732012-06-29 14:12:52 -07003009void SurfaceFlinger::commitTransaction()
3010{
Vishnu Nair60db8c02020-04-02 11:55:16 -07003011 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003012 mTransactionPending = false;
3013 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003014 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003015}
3016
Lloyd Pique58e24a32019-08-01 15:50:14 -07003017void SurfaceFlinger::commitTransactionLocked() {
3018 if (!mLayersPendingRemoval.isEmpty()) {
3019 // Notify removed layers now that they can't be drawn from
3020 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003021 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003022
3023 // Ensure any buffers set to display on any children are released.
3024 if (l->isRemovedFromCurrentState()) {
3025 l->latchAndReleaseBuffer();
3026 }
3027
3028 // If the layer has been removed and has no parent, then it will not be reachable
3029 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3030 // ensure we can copy its current to drawing state.
3031 if (!l->getParent()) {
3032 mOffscreenLayers.emplace(l.get());
3033 }
3034 }
3035 mLayersPendingRemoval.clear();
3036 }
3037
3038 // If this transaction is part of a window animation then the next frame
3039 // we composite should be considered an animation as well.
3040 mAnimCompositionPending = mAnimTransactionPending;
3041
3042 mDrawingState = mCurrentState;
3043 // clear the "changed" flags in current state
3044 mCurrentState.colorMatrixChanged = false;
3045
Edgar Arriaga844fa672020-01-16 14:21:42 -08003046 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003047 layer->commitChildList();
3048
3049 // If the layer can be reached when traversing mDrawingState, then the layer is no
3050 // longer offscreen. Remove the layer from the offscreenLayer set.
3051 if (mOffscreenLayers.count(layer)) {
3052 mOffscreenLayers.erase(layer);
3053 }
3054 });
3055
3056 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003057 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003058}
3059
chaviw74d90ad2019-04-26 14:45:26 -07003060void SurfaceFlinger::commitOffscreenLayers() {
3061 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003062 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003063 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3064 if (!trFlags) return;
3065
3066 layer->doTransaction(0);
3067 layer->commitChildList();
3068 });
3069 }
3070}
3071
Chia-I Wuab0c3192017-08-01 11:29:00 -07003072void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07003073 for (const auto& [token, displayDevice] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003074 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003075 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003076 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003077 }
3078 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003079}
3080
Dan Stoza6b9454d2014-11-07 16:00:59 -08003081bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082{
Ady Abraham09bd3922019-04-08 10:44:56 -07003083 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003084 ALOGV("handlePageFlip");
3085
Brian Andersond6927fb2016-07-23 23:37:30 -07003086 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087
Mathias Agopian4fec8732012-06-29 14:12:52 -07003088 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003089 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003090 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003091
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003092 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3093
Eric Penner51c59cd2014-07-28 19:51:58 -07003094 // Store the set of layers that need updates. This set must not change as
3095 // buffers are being latched, as this could result in a deadlock.
3096 // Example: Two producers share the same command stream and:
3097 // 1.) Layer 0 is latched
3098 // 2.) Layer 0 gets a new frame
3099 // 2.) Layer 1 gets a new frame
3100 // 3.) Layer 1 is latched.
3101 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3102 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003103 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003104 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003105 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003106 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003107 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003108 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003109 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003110 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003111 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003112 } else {
3113 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003114 }
Robert Carr2047fae2016-11-28 14:09:09 -08003115 });
3116
chaviw49a108c2019-08-12 11:23:06 -07003117 // The client can continue submitting buffers for offscreen layers, but they will not
3118 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3119 // layers to ensure dequeueBuffer doesn't block indefinitely.
3120 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003121 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003122 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3123 }
3124
Lloyd Piquef2c79392018-12-20 16:23:33 -08003125 if (!mLayersWithQueuedFrames.empty()) {
3126 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3127 // writes to Layer current state. See also b/119481871
3128 Mutex::Autolock lock(mStateLock);
3129
3130 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003131 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003132 mLayersPendingRefresh.push_back(layer);
3133 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003134 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003135 if (layer->isBufferLatched()) {
3136 newDataLatched = true;
3137 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003138 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003139 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003140
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003141 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003142
3143 // If we will need to wake up at some time in the future to deal with a
3144 // queued frame that shouldn't be displayed during this vsync period, wake
3145 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003146 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003147 signalLayerUpdate();
3148 }
3149
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003150 // enter boot animation on first buffer latch
3151 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3152 ALOGI("Enter boot animation");
3153 mBootStage = BootStage::BOOTANIMATION;
3154 }
3155
Edgar Arriaga844fa672020-01-16 14:21:42 -08003156 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003157
Dan Stoza6b9454d2014-11-07 16:00:59 -08003158 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003159 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160}
3161
Mathias Agopianad456f92011-01-13 17:53:01 -08003162void SurfaceFlinger::invalidateHwcGeometry()
3163{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003164 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003165}
3166
Robert Carrc0df3122019-04-11 13:18:21 -07003167status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3168 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3169 const sp<IBinder>& parentHandle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003170 const sp<Layer>& parentLayer, bool addToCurrentState,
3171 uint32_t* outTransformHint) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003172 // add this layer to the current state list
3173 {
3174 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003175 sp<Layer> parent;
3176 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003177 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003178 if (parent == nullptr) {
3179 return NAME_NOT_FOUND;
3180 }
3181 } else {
3182 parent = parentLayer;
3183 }
3184
Ady Abraham0a525092020-03-03 12:51:24 -08003185 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003186 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003187 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003188 return NO_MEMORY;
3189 }
Robert Carrc0df3122019-04-11 13:18:21 -07003190
3191 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3192
Robert Carrb89ea9d2018-12-10 13:01:14 -08003193 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003194 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003195 } else if (parent == nullptr) {
3196 lbc->onRemovedFromCurrentState();
3197 } else if (parent->isRemovedFromCurrentState()) {
3198 parent->addChild(lbc);
3199 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003200 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003201 parent->addChild(lbc);
3202 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003203
Yiwei Zhang243b3782018-05-15 17:40:04 -07003204 if (gbc != nullptr) {
3205 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3206 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3207 mMaxGraphicBufferProducerListSize,
3208 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3209 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003210 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003211 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003212
3213 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07003214 lbc->updateTransformHint(display->getTransformHint());
Vishnu Nair6213bd92020-05-08 17:42:25 -07003215 }
3216 if (outTransformHint) {
3217 *outTransformHint = lbc->getTransformHint();
3218 }
3219
Robert Carr1f0a16a2016-10-24 16:27:39 -07003220 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003221 }
3222
Mathias Agopian96f08192010-06-02 23:28:45 -07003223 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003224 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003225
Dan Stoza7d89d062015-04-30 13:29:25 -07003226 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003227}
3228
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003229void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3230 static_cast<void>(schedule([=] {
3231 Mutex::Autolock lock(mStateLock);
3232 mGraphicBufferProducerList.erase(binder);
3233 }));
3234}
3235
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003236uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003237 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003238}
3239
Mathias Agopian3f844832013-08-07 21:24:32 -07003240uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003241 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242}
3243
Mathias Agopian3f844832013-08-07 21:24:32 -07003244uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ady Abrahambf1349c2020-06-12 14:26:18 -07003245 return setTransactionFlags(flags, Scheduler::TransactionStart::Normal);
Dan Stoza84d619e2018-03-28 17:07:36 -07003246}
3247
3248uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003249 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003250 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003251 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003253 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003254 }
3255 return old;
3256}
3257
Valerie Haud50e7412020-06-16 17:58:14 -07003258void SurfaceFlinger::setTraversalNeeded() {
3259 mForceTraversal = true;
Robert Carr7ec777d2020-05-29 12:02:51 -07003260}
3261
Marissa Wall713b63f2018-10-17 15:42:43 -07003262bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003263 // to prevent onHandleDestroyed from being called while the lock is held,
3264 // we must keep a copy of the transactions (specifically the composer
3265 // states) around outside the scope of the lock
3266 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003267 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003268 {
3269 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003270
Valerie Haufce31b82019-04-30 16:41:14 -07003271 auto it = mTransactionQueues.begin();
3272 while (it != mTransactionQueues.end()) {
3273 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003274
Valerie Haufce31b82019-04-30 16:41:14 -07003275 while (!transactionQueue.empty()) {
3276 const auto& transaction = transactionQueue.front();
3277 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3278 transaction.states)) {
3279 setTransactionFlags(eTransactionFlushNeeded);
3280 break;
3281 }
3282 transactions.push_back(transaction);
3283 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3284 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003285 transaction.buffer, transaction.postTime,
3286 transaction.privileged, transaction.hasListenerCallbacks,
3287 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003288 transactionQueue.pop();
3289 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003290 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003291
Valerie Haufce31b82019-04-30 16:41:14 -07003292 if (transactionQueue.empty()) {
3293 it = mTransactionQueues.erase(it);
3294 mTransactionCV.broadcast();
3295 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003296 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003297 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003298 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003299 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003300 return flushedATransaction;
3301}
3302
3303bool SurfaceFlinger::transactionFlushNeeded() {
3304 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003305}
3306
chaviwca27f252018-02-06 16:46:39 -08003307
Marissa Wall17b4e452018-12-26 16:32:34 -08003308bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3309 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003310
3311 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003312 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3313 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3314 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3315 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3316 return false;
3317 }
3318
Marissa Wall713b63f2018-10-17 15:42:43 -07003319 for (const ComposerState& state : states) {
3320 const layer_state_t& s = state.state;
3321 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3322 continue;
3323 }
3324 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003325 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003326 }
3327 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003328 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003329}
3330
Valerie Hau9dab9732019-08-20 09:29:25 -07003331void SurfaceFlinger::setTransactionState(
3332 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3333 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3334 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3335 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003336 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003337
Valerie Haubc6ddb12019-03-08 11:10:15 -08003338 const int64_t postTime = systemTime();
3339
Robert Carr14167e02019-02-13 13:50:55 -08003340 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3341
Mathias Agopian698c0872011-06-28 19:09:31 -07003342 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003343
Marissa Wall713b63f2018-10-17 15:42:43 -07003344 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003345 auto itr = mTransactionQueues.find(applyToken);
3346 // if this is an animation frame, wait until prior animation frame has
3347 // been applied by SF
3348 if (flags & eAnimation) {
3349 while (itr != mTransactionQueues.end()) {
3350 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3351 if (CC_UNLIKELY(err != NO_ERROR)) {
3352 ALOGW_IF(err == TIMED_OUT,
3353 "setTransactionState timed out "
3354 "waiting for animation frame to apply");
3355 break;
3356 }
3357 itr = mTransactionQueues.find(applyToken);
3358 }
3359 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003360
Ady Abraham5facfb12020-04-22 15:18:31 -07003361 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003362 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003363 if (!pendingTransactions) {
3364 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3365 }
3366
3367 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003368 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003369 uncacheBuffer, postTime, privileged,
3370 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003371 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003372 return;
3373 }
3374
Valerie Haubc6ddb12019-03-08 11:10:15 -08003375 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003376 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3377 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003378}
3379
Valerie Hau9dab9732019-08-20 09:29:25 -07003380void SurfaceFlinger::applyTransactionState(
3381 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3382 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3383 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3384 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3385 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003386 uint32_t transactionFlags = 0;
3387
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003388 if (flags & eAnimation) {
3389 // For window updates that are part of an animation we must wait for
3390 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003391 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003392 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003393 if (CC_UNLIKELY(err != NO_ERROR)) {
3394 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003395 // caller after a few seconds.
3396 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3397 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003398 mAnimTransactionPending = false;
3399 break;
3400 }
3401 }
3402 }
3403
chaviwca27f252018-02-06 16:46:39 -08003404 for (const DisplayState& display : displays) {
3405 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003406 }
3407
Valerie Hau9dab9732019-08-20 09:29:25 -07003408 // start and end registration for listeners w/ no surface so they can get their callback. Note
3409 // that listeners with SurfaceControls will start registration during setClientStateLocked
3410 // below.
3411 for (const auto& listener : listenerCallbacks) {
3412 mTransactionCompletedThread.startRegistration(listener);
3413 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003414 }
3415
Valerie Hau9dab9732019-08-20 09:29:25 -07003416 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003417 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003418 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003419 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3420 listenerCallbacksWithSurfaces);
Ady Abraham5def7332020-05-29 16:13:47 -07003421 if ((flags & eAnimation) && state.state.surface) {
3422 if (const auto layer = fromHandleLocked(state.state.surface).promote(); layer) {
3423 mScheduler->recordLayerHistory(layer.get(), desiredPresentTime,
3424 LayerHistory::LayerUpdateType::AnimationTX);
3425 }
3426 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07003427 }
3428
Valerie Hau9dab9732019-08-20 09:29:25 -07003429 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003430 mTransactionCompletedThread.endRegistration(listenerCallback);
3431 }
3432
Marissa Walle2ffb422018-10-12 11:33:52 -07003433 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003434 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003435 mTransactionCompletedThread.sendCallbacks();
3436 }
3437 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003438
chaviw273171b2018-12-26 11:46:30 -08003439 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3440
Marissa Wall947d34e2019-03-29 14:03:53 -07003441 if (uncacheBuffer.isValid()) {
3442 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003443 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003444 }
3445
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003446 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3447 // anyway. This can be used as a flush mechanism for previous async transactions.
3448 // Empty animation transaction can be used to simulate back-pressure, so also force a
3449 // transaction for empty animation transactions.
3450 if (transactionFlags == 0 &&
3451 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003452 transactionFlags = eTransactionNeeded;
3453 }
3454
Marissa Wall06255332019-03-27 13:48:27 -07003455 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3456 // so we don't have to wake up again next frame to preform an uneeded traversal.
3457 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3458 transactionFlags = transactionFlags & (~eTraversalNeeded);
Valerie Haud50e7412020-06-16 17:58:14 -07003459 mForceTraversal = true;
Marissa Wall06255332019-03-27 13:48:27 -07003460 }
3461
Ady Abrahambf1349c2020-06-12 14:26:18 -07003462 const auto transactionStart = [](uint32_t flags) {
3463 if (flags & eEarlyWakeup) {
3464 return Scheduler::TransactionStart::Early;
3465 }
3466 if (flags & eExplicitEarlyWakeupEnd) {
3467 return Scheduler::TransactionStart::EarlyEnd;
3468 }
3469 if (flags & eExplicitEarlyWakeupStart) {
3470 return Scheduler::TransactionStart::EarlyStart;
3471 }
3472 return Scheduler::TransactionStart::Normal;
3473 }(flags);
3474
Mathias Agopian386aa982011-11-07 21:58:03 -08003475 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003476 if (mInterceptor->isEnabled()) {
3477 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003478 }
Irvel468051e2016-06-13 16:44:44 -07003479
Ady Abrahambf1349c2020-06-12 14:26:18 -07003480 // TODO(b/159125966): Remove eEarlyWakeup completly as no client should use this flag
3481 if (flags & eEarlyWakeup) {
3482 ALOGW("eEarlyWakeup is deprecated. Use eExplicitEarlyWakeup[Start|End]");
3483 }
3484
3485 if (!privileged && (flags & (eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd))) {
3486 ALOGE("Only WindowManager is allowed to use eExplicitEarlyWakeup[Start|End] flags");
3487 flags &= ~(eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd);
3488 }
3489
Mathias Agopian386aa982011-11-07 21:58:03 -08003490 // this triggers the transaction
Ady Abrahambf1349c2020-06-12 14:26:18 -07003491 setTransactionFlags(transactionFlags, transactionStart);
Mathias Agopian386aa982011-11-07 21:58:03 -08003492
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003493 if (flags & eAnimation) {
3494 mAnimTransactionPending = true;
3495 }
Robert Carr238f4a22020-04-29 13:04:02 -07003496
3497 // if this is a synchronous transaction, wait for it to take effect
3498 // before returning.
3499 const bool synchronous = flags & eSynchronous;
3500 const bool syncInput = inputWindowCommands.syncInputWindows;
3501 if (!synchronous && !syncInput) {
3502 return;
3503 }
3504
3505 if (synchronous) {
3506 mTransactionPending = true;
3507 }
3508 if (syncInput) {
chaviw4fe36852019-04-15 16:25:49 -07003509 mPendingSyncInputWindows = true;
3510 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003511
Robert Carr238f4a22020-04-29 13:04:02 -07003512
Valerie Hau0779ded2019-03-19 12:43:04 -07003513 // applyTransactionState can be called by either the main SF thread or by
3514 // another process through setTransactionState. While a given process may wish
3515 // to wait on synchronous transactions, the main SF thread should never
3516 // be blocked. Therefore, we only wait if isMainThread is false.
3517 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003518 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3519 if (CC_UNLIKELY(err != NO_ERROR)) {
3520 // just in case something goes wrong in SF, return to the
3521 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003522 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3523 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003524 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003525 break;
3526 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003527 }
Ady Abrahambf1349c2020-06-12 14:26:18 -07003528 } else {
3529 // even if a transaction is not needed, we need to update VsyncModulator
3530 // about explicit early indications
3531 if (transactionStart == Scheduler::TransactionStart::EarlyStart ||
3532 transactionStart == Scheduler::TransactionStart::EarlyEnd) {
3533 mVSyncModulator->setTransactionStart(transactionStart);
3534 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003535 }
3536}
3537
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003538uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3539 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3540 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003541
Mathias Agopiane57f2922012-08-09 16:29:12 -07003542 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003543 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3544
3545 const uint32_t what = s.what;
3546 if (what & DisplayState::eSurfaceChanged) {
3547 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3548 state.surface = s.surface;
3549 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003550 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003551 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003552 if (what & DisplayState::eLayerStackChanged) {
3553 if (state.layerStack != s.layerStack) {
3554 state.layerStack = s.layerStack;
3555 flags |= eDisplayTransactionNeeded;
3556 }
3557 }
3558 if (what & DisplayState::eDisplayProjectionChanged) {
3559 if (state.orientation != s.orientation) {
3560 state.orientation = s.orientation;
3561 flags |= eDisplayTransactionNeeded;
3562 }
3563 if (state.frame != s.frame) {
3564 state.frame = s.frame;
3565 flags |= eDisplayTransactionNeeded;
3566 }
3567 if (state.viewport != s.viewport) {
3568 state.viewport = s.viewport;
3569 flags |= eDisplayTransactionNeeded;
3570 }
3571 }
3572 if (what & DisplayState::eDisplaySizeChanged) {
3573 if (state.width != s.width) {
3574 state.width = s.width;
3575 flags |= eDisplayTransactionNeeded;
3576 }
3577 if (state.height != s.height) {
3578 state.height = s.height;
3579 flags |= eDisplayTransactionNeeded;
3580 }
3581 }
3582
Mathias Agopiane57f2922012-08-09 16:29:12 -07003583 return flags;
3584}
3585
Steven Thomasd4071902020-03-24 16:02:53 -07003586bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003587 IPCThreadState* ipc = IPCThreadState::self();
3588 const int pid = ipc->getCallingPid();
3589 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003590 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003591 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3592 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003593 return false;
3594 }
3595 return true;
3596}
3597
Marissa Wall3dad52d2019-03-22 14:03:19 -07003598uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003599 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3600 bool privileged,
3601 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003602 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003603
Valerie Hau9dab9732019-08-20 09:29:25 -07003604 for (auto& listener : s.listeners) {
3605 // note that startRegistration will not re-register if the listener has
3606 // already be registered for a prior surface control
3607 mTransactionCompletedThread.startRegistration(listener);
3608 listenerCallbacks.insert(listener);
3609 }
3610
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003611 sp<Layer> layer = nullptr;
3612 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003613 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003614 } else {
3615 // The client may provide us a null handle. Treat it as if the layer was removed.
3616 ALOGW("Attempt to set client state with a null layer handle");
3617 }
chaviw8b3871a2017-11-01 17:41:01 -07003618 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003619 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003620 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003621 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003622 }
chaviw8b3871a2017-11-01 17:41:01 -07003623 return 0;
3624 }
3625
chaviw8b3871a2017-11-01 17:41:01 -07003626 uint32_t flags = 0;
3627
Garfield Tan8a3083e2018-12-03 13:21:07 -08003628 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003629
3630 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3631 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003632 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003633 layer->pushPendingState();
3634 }
3635
Valerie Hau871d6352020-01-29 08:44:02 -08003636 // Only set by BLAST adapter layers
3637 if (what & layer_state_t::eProducerDisconnect) {
3638 layer->onDisconnect();
3639 }
3640
chaviw8b3871a2017-11-01 17:41:01 -07003641 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003642 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003643 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003644 }
chaviw8b3871a2017-11-01 17:41:01 -07003645 }
3646 if (what & layer_state_t::eLayerChanged) {
3647 // NOTE: index needs to be calculated before we update the state
3648 const auto& p = layer->getParent();
3649 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003650 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003651 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003652 mCurrentState.layersSortedByZ.removeAt(idx);
3653 mCurrentState.layersSortedByZ.add(layer);
3654 // we need traversal (state changed)
3655 // AND transaction (list changed)
3656 flags |= eTransactionNeeded|eTraversalNeeded;
3657 }
chaviw8b3871a2017-11-01 17:41:01 -07003658 } else {
3659 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003660 flags |= eTransactionNeeded|eTraversalNeeded;
3661 }
3662 }
chaviw8b3871a2017-11-01 17:41:01 -07003663 }
3664 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003665 // NOTE: index needs to be calculated before we update the state
3666 const auto& p = layer->getParent();
3667 if (p == nullptr) {
3668 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3669 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3670 mCurrentState.layersSortedByZ.removeAt(idx);
3671 mCurrentState.layersSortedByZ.add(layer);
3672 // we need traversal (state changed)
3673 // AND transaction (list changed)
3674 flags |= eTransactionNeeded|eTraversalNeeded;
3675 }
3676 } else {
3677 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3678 flags |= eTransactionNeeded|eTraversalNeeded;
3679 }
chaviw8b3871a2017-11-01 17:41:01 -07003680 }
3681 }
3682 if (what & layer_state_t::eSizeChanged) {
3683 if (layer->setSize(s.w, s.h)) {
3684 flags |= eTraversalNeeded;
3685 }
3686 }
3687 if (what & layer_state_t::eAlphaChanged) {
3688 if (layer->setAlpha(s.alpha))
3689 flags |= eTraversalNeeded;
3690 }
3691 if (what & layer_state_t::eColorChanged) {
3692 if (layer->setColor(s.color))
3693 flags |= eTraversalNeeded;
3694 }
Peiyong Lind3788632018-09-18 16:01:31 -07003695 if (what & layer_state_t::eColorTransformChanged) {
3696 if (layer->setColorTransform(s.colorTransform)) {
3697 flags |= eTraversalNeeded;
3698 }
3699 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003700 if (what & layer_state_t::eBackgroundColorChanged) {
3701 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3702 flags |= eTraversalNeeded;
3703 }
3704 }
chaviw8b3871a2017-11-01 17:41:01 -07003705 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003706 // TODO: b/109894387
3707 //
3708 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3709 // rotation. To see the problem observe that if we have a square parent, and a child
3710 // of the same size, then we rotate the child 45 degrees around it's center, the child
3711 // must now be cropped to a non rectangular 8 sided region.
3712 //
3713 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3714 // private API, and the WindowManager only uses rotation in one case, which is on a top
3715 // level layer in which cropping is not an issue.
3716 //
3717 // However given that abuse of rotation matrices could lead to surfaces extending outside
3718 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3719 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3720 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003721 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003722 flags |= eTraversalNeeded;
3723 }
3724 if (what & layer_state_t::eTransparentRegionChanged) {
3725 if (layer->setTransparentRegionHint(s.transparentRegion))
3726 flags |= eTraversalNeeded;
3727 }
3728 if (what & layer_state_t::eFlagsChanged) {
3729 if (layer->setFlags(s.flags, s.mask))
3730 flags |= eTraversalNeeded;
3731 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003732 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003733 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003734 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003735 if (what & layer_state_t::eCornerRadiusChanged) {
3736 if (layer->setCornerRadius(s.cornerRadius))
3737 flags |= eTraversalNeeded;
3738 }
Lucas Dupin130e55c2020-05-26 16:11:18 -07003739 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003740 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3741 }
chaviw8b3871a2017-11-01 17:41:01 -07003742 if (what & layer_state_t::eLayerStackChanged) {
3743 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3744 // We only allow setting layer stacks for top level layers,
3745 // everything else inherits layer stack from its parent.
3746 if (layer->hasParent()) {
3747 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003748 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003749 } else if (idx < 0) {
3750 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003751 "that also does not appear in the top level layer list. Something"
3752 " has gone wrong.",
3753 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003754 } else if (layer->setLayerStack(s.layerStack)) {
3755 mCurrentState.layersSortedByZ.removeAt(idx);
3756 mCurrentState.layersSortedByZ.add(layer);
3757 // we need traversal (state changed)
3758 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07003759 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003760 }
3761 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003762 if (what & layer_state_t::eDeferTransaction_legacy) {
3763 if (s.barrierHandle_legacy != nullptr) {
3764 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3765 } else if (s.barrierGbp_legacy != nullptr) {
3766 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003767 if (authenticateSurfaceTextureLocked(gbp)) {
3768 const auto& otherLayer =
3769 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003770 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003771 } else {
3772 ALOGE("Attempt to defer transaction to to an"
3773 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003774 }
3775 }
chaviw8b3871a2017-11-01 17:41:01 -07003776 // We don't trigger a traversal here because if no other state is
3777 // changed, we don't want this to cause any more work
3778 }
chaviw8b3871a2017-11-01 17:41:01 -07003779 if (what & layer_state_t::eReparentChildren) {
3780 if (layer->reparentChildren(s.reparentHandle)) {
3781 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003782 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003783 }
chaviw8b3871a2017-11-01 17:41:01 -07003784 if (what & layer_state_t::eDetachChildren) {
3785 layer->detachChildren();
3786 }
3787 if (what & layer_state_t::eOverrideScalingModeChanged) {
3788 layer->setOverrideScalingMode(s.overrideScalingMode);
3789 // We don't trigger a traversal here because if no other state is
3790 // changed, we don't want this to cause any more work
3791 }
Marissa Wall61c58622018-07-18 10:12:20 -07003792 if (what & layer_state_t::eTransformChanged) {
3793 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3794 }
3795 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3796 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3797 flags |= eTraversalNeeded;
3798 }
3799 if (what & layer_state_t::eCropChanged) {
3800 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3801 }
Marissa Wall861616d2018-10-22 12:52:23 -07003802 if (what & layer_state_t::eFrameChanged) {
3803 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3804 }
Marissa Wall61c58622018-07-18 10:12:20 -07003805 if (what & layer_state_t::eAcquireFenceChanged) {
3806 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3807 }
3808 if (what & layer_state_t::eDataspaceChanged) {
3809 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3810 }
3811 if (what & layer_state_t::eHdrMetadataChanged) {
3812 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3813 }
3814 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3815 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3816 }
3817 if (what & layer_state_t::eApiChanged) {
3818 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3819 }
3820 if (what & layer_state_t::eSidebandStreamChanged) {
3821 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3822 }
Robert Carr720e5062018-07-30 17:45:14 -07003823 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003824 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003825 layer->setInputInfo(s.inputInfo);
3826 flags |= eTraversalNeeded;
3827 } else {
3828 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3829 }
Robert Carr720e5062018-07-30 17:45:14 -07003830 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003831 if (what & layer_state_t::eMetadataChanged) {
3832 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3833 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003834 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3835 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3836 flags |= eTraversalNeeded;
3837 }
3838 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003839 if (what & layer_state_t::eShadowRadiusChanged) {
3840 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3841 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003842 if (what & layer_state_t::eFrameRateSelectionPriority) {
3843 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3844 flags |= eTraversalNeeded;
3845 }
3846 }
Steven Thomas3172e202020-01-06 19:25:30 -08003847 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003848 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3849 "SurfaceFlinger::setClientStateLocked") &&
3850 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3851 Layer::FrameRate::convertCompatibility(
3852 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003853 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003854 }
Steven Thomas3172e202020-01-06 19:25:30 -08003855 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003856 if (what & layer_state_t::eFixedTransformHintChanged) {
3857 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
3858 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
3859 }
3860 }
Winson Chung7605fb42021-06-29 15:42:56 -07003861 if (what & layer_state_t::eTrustedOverlayChanged) {
3862 if (privileged) {
3863 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
3864 flags |= eTraversalNeeded;
3865 }
3866 } else {
3867 ALOGE("Attempt to set trusted overlay without permission ACCESS_SURFACE_FLINGER");
3868 }
3869 }
Vishnu Nair122c4d22022-01-27 16:20:46 +00003870 if (what & layer_state_t::eDropInputModeChanged) {
3871 if (privileged) {
3872 if (layer->setDropInputMode(s.dropInputMode)) {
3873 flags |= eTraversalNeeded;
3874 }
3875 } else {
3876 ALOGE("Attempt to update InputPolicyFlags without permission ACCESS_SURFACE_FLINGER");
3877 }
3878 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003879 // This has to happen after we reparent children because when we reparent to null we remove
3880 // child layers from current state and remove its relative z. If the children are reparented in
3881 // the same transaction, then we have to make sure we reparent the children first so we do not
3882 // lose its relative z order.
3883 if (what & layer_state_t::eReparent) {
3884 bool hadParent = layer->hasParent();
3885 if (layer->reparent(s.parentHandleForChild)) {
3886 if (!hadParent) {
3887 mCurrentState.layersSortedByZ.remove(layer);
3888 }
3889 flags |= eTransactionNeeded | eTraversalNeeded;
3890 }
3891 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003892 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003893 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3894 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003895 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3896 }
3897 }
Marissa Wall78b72202019-03-15 14:58:34 -07003898 bool bufferChanged = what & layer_state_t::eBufferChanged;
3899 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3900 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003901 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003902 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003903 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3904 if (success) {
3905 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3906 success = ClientCache::getInstance()
3907 .registerErasedRecipient(s.cachedBuffer,
3908 wp<ClientCache::ErasedRecipient>(this));
3909 if (!success) {
3910 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3911 }
3912 }
Marissa Wall78b72202019-03-15 14:58:34 -07003913 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003914 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003915 } else if (bufferChanged) {
3916 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003917 }
Marissa Wall78b72202019-03-15 14:58:34 -07003918 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003919 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3920 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003921 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003922 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003923 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003924 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3925 // Do not put anything that updates layer state or modifies flags after
3926 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003927 return flags;
3928}
3929
chaviw273171b2018-12-26 11:46:30 -08003930uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3931 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003932 if (inputWindowCommands.syncInputWindows) {
3933 flags |= eTraversalNeeded;
3934 }
3935
Vishnu Nairec0ab382019-02-13 15:32:56 -08003936 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003937 return flags;
3938}
3939
chaviwfe94a222019-08-21 13:52:59 -07003940status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3941 sp<IBinder>* outHandle) {
3942 if (!mirrorFromHandle) {
3943 return NAME_NOT_FOUND;
3944 }
3945
3946 sp<Layer> mirrorLayer;
3947 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003948 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003949
3950 {
3951 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003952 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003953 if (!mirrorFrom) {
3954 return NAME_NOT_FOUND;
3955 }
3956
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003957 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3958 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003959 if (result != NO_ERROR) {
3960 return result;
3961 }
3962
3963 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3964 }
3965
Vishnu Nair6213bd92020-05-08 17:42:25 -07003966 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false,
3967 nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07003968}
3969
Marissa Wall2d814fb2019-04-09 18:52:57 +00003970status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3971 uint32_t h, PixelFormat format, uint32_t flags,
3972 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003973 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003974 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3975 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003976 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003977 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003978 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003979 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003980 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003981
Robert Carrc0df3122019-04-11 13:18:21 -07003982 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3983 "Expected only one of parentLayer or parentHandle to be non-null. "
3984 "Programmer error?");
3985
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003986 status_t result = NO_ERROR;
3987
3988 sp<Layer> layer;
3989
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003990 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003991
Evan Roskya1f1e152019-01-24 16:17:46 -08003992 bool primaryDisplayOnly = false;
3993
3994 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3995 // TODO b/64227542
3996 if (metadata.has(METADATA_WINDOW_TYPE)) {
3997 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3998 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003999 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004000 primaryDisplayOnly = true;
4001 }
4002 }
4003
Mathias Agopian3165cc22012-08-08 19:42:09 -07004004 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004005 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004006 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
4007 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004008
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004009 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004010 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004011 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004012 std::move(metadata), handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004013 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004014 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004015 // check if buffer size is set for color layer.
4016 if (w > 0 || h > 0) {
4017 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4018 int(w), int(h));
4019 return BAD_VALUE;
4020 }
4021
Vishnu Nairfa247b12020-02-11 08:58:26 -08004022 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
4023 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004024 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004025 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004026 // check if buffer size is set for container layer.
4027 if (w > 0 || h > 0) {
4028 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4029 int(w), int(h));
4030 return BAD_VALUE;
4031 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004032 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
4033 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004034 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004035 default:
4036 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004037 break;
4038 }
4039
Dan Stoza7d89d062015-04-30 13:29:25 -07004040 if (result != NO_ERROR) {
4041 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004042 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004043
Evan Roskya1f1e152019-01-24 16:17:46 -08004044 if (primaryDisplayOnly) {
4045 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004046 }
4047
Robert Carrb89ea9d2018-12-10 13:01:14 -08004048 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004049 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004050 addToCurrentState, outTransformHint);
Dan Stoza7d89d062015-04-30 13:29:25 -07004051 if (result != NO_ERROR) {
4052 return result;
4053 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004054 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004055
4056 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004057 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004058}
4059
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004060std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
4061 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06004062
4063 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004064 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004065
Dan Stoza436ccf32018-06-21 12:10:12 -07004066 // Grab the state lock since we're accessing mCurrentState
4067 Mutex::Autolock lock(mStateLock);
4068
Cody Northropbc755282017-03-31 12:00:08 -06004069 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004070 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06004071 while (matchFound) {
4072 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08004073 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004074 if (layer->getName() == uniqueName) {
4075 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004076 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004077 }
4078 });
4079 }
4080
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004081 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004082 return uniqueName;
4083}
4084
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004085status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07004086 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004087 LayerMetadata metadata, PixelFormat& format,
4088 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004089 sp<IGraphicBufferProducer>* gbp,
4090 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004092 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004093 case PIXEL_FORMAT_TRANSPARENT:
4094 case PIXEL_FORMAT_TRANSLUCENT:
4095 format = PIXEL_FORMAT_RGBA_8888;
4096 break;
4097 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004098 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004099 break;
4100 }
4101
chaviwb4c6e582019-08-16 14:35:07 -07004102 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004103 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004104 args.textureName = getNewTexture();
4105 {
4106 // Grab the SF state lock during this since it's the only safe way to access
4107 // RenderEngine when creating a BufferLayerConsumer
4108 // TODO: Check if this lock is still needed here
4109 Mutex::Autolock lock(mStateLock);
4110 layer = getFactory().createBufferQueueLayer(args);
4111 }
4112
Marissa Wallfd668622018-05-10 10:21:13 -07004113 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004114 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004115 *handle = layer->getHandle();
4116 *gbp = layer->getProducer();
4117 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004119
Marissa Wallfd668622018-05-10 10:21:13 -07004120 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004121 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004122}
4123
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004124status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004125 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004126 LayerMetadata metadata, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004127 sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004128 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004129 args.textureName = getNewTexture();
4130 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07004131 *handle = layer->getHandle();
4132 *outLayer = layer;
4133
4134 return NO_ERROR;
4135}
4136
Vishnu Nairfa247b12020-02-11 08:58:26 -08004137status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4138 uint32_t h, uint32_t flags, LayerMetadata metadata,
4139 sp<IBinder>* handle, sp<Layer>* outLayer) {
4140 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004141 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004142 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004143 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004144}
4145
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004146status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004147 uint32_t w, uint32_t h, uint32_t flags,
4148 LayerMetadata metadata, sp<IBinder>* handle,
4149 sp<Layer>* outLayer) {
4150 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004151 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004152 *handle = (*outLayer)->getHandle();
4153 return NO_ERROR;
4154}
4155
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004156void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004157 mLayersPendingRemoval.add(layer);
4158 mLayersRemoved = true;
4159 setTransactionFlags(eTransactionNeeded);
4160}
4161
Robert Carr695d5282018-12-18 15:27:58 -08004162void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004163{
Robert Carr2e102c92018-10-23 12:11:15 -07004164 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004165 // If a layer has a parent, we allow it to out-live it's handle
4166 // with the idea that the parent holds a reference and will eventually
4167 // be cleaned up. However no one cleans up the top-level so we do so
4168 // here.
4169 if (layer->getParent() == nullptr) {
4170 mCurrentState.layersSortedByZ.remove(layer);
4171 }
4172 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004173
4174 auto it = mLayersByLocalBinderToken.begin();
4175 while (it != mLayersByLocalBinderToken.end()) {
4176 if (it->second == layer) {
4177 it = mLayersByLocalBinderToken.erase(it);
4178 } else {
4179 it++;
4180 }
4181 }
4182
Robert Carr695d5282018-12-18 15:27:58 -08004183 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004184}
4185
Mathias Agopianb60314a2012-04-10 22:09:54 -07004186// ---------------------------------------------------------------------------
4187
Andy McFadden13a082e2012-08-24 10:16:42 -07004188void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004189 const auto display = getDefaultDisplayDeviceLocked();
4190 if (!display) return;
4191
4192 const sp<IBinder> token = display->getDisplayToken().promote();
4193 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004194
Jesse Hall01e29052013-02-19 16:13:35 -08004195 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004196 Vector<ComposerState> state;
4197 Vector<DisplayState> displays;
4198 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004199 d.what = DisplayState::eDisplayProjectionChanged |
4200 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004201 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004202 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004203 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004204 d.frame.makeInvalid();
4205 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004206 d.width = 0;
4207 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004208 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004209 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4210 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004211
Peiyong Lin65248e02020-04-18 21:15:07 -07004212 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004213
Dominik Laskowski83b88212018-12-11 13:34:06 -08004214 const nsecs_t vsyncPeriod = getVsyncPeriod();
4215 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004216
Brian Andersond0010582017-03-07 13:20:31 -08004217 // Use phase of 0 since phase is not known.
4218 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004219 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004220 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004221}
4222
4223void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004224 // Async since we may be called from the main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004225 static_cast<void>(schedule([this]() MAIN_THREAD { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004226}
4227
Peiyong Lin65248e02020-04-18 21:15:07 -07004228void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004229 if (display->isVirtual()) {
4230 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004231 return;
4232 }
4233
Dominik Laskowski075d3172018-05-24 15:50:06 -07004234 const auto displayId = display->getId();
4235 LOG_ALWAYS_FATAL_IF(!displayId);
4236
Dominik Laskowski34157762018-10-31 13:07:19 -07004237 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004238
Peiyong Lin65248e02020-04-18 21:15:07 -07004239 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004240 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004241 return;
4242 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004243
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004244 display->setPowerMode(mode);
4245
Lloyd Pique4dccc412018-01-22 17:21:36 -08004246 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004247 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004248 }
4249
Peiyong Lin65248e02020-04-18 21:15:07 -07004250 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004251 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4252 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4253 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004254 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004255 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004256 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004257 mScheduler->onScreenAcquired(mAppConnectionHandle);
4258 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004259 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004260
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004261 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004262 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004263 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004264 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004265 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004266 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4267 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004268 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004269 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004270 mScheduler->disableHardwareVsync(true);
4271 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004272 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004273
Ady Abraham27c70212019-06-11 10:52:26 -07004274 // Make sure HWVsync is disabled before turning off the display
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004275 getHwComposer().setVsyncEnabled(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004276
Dominik Laskowski075d3172018-05-24 15:50:06 -07004277 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004278 mVisibleRegionsDirty = true;
4279 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004280 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004281 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004282 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004283 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004284 mScheduler->onScreenAcquired(mAppConnectionHandle);
4285 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004286 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004287 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004288 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004289 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004290 mScheduler->disableHardwareVsync(true);
4291 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004292 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004293 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004294 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004295 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004296 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004297 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004298
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004299 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004300 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004301 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004302 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004303 }
4304
Dominik Laskowski34157762018-10-31 13:07:19 -07004305 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004306}
4307
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004308void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004309 schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004310 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004311 if (!display) {
4312 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4313 displayToken.get());
4314 } else if (display->isVirtual()) {
4315 ALOGW("Attempt to set power mode %d for virtual display", mode);
4316 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004317 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004318 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004319 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004320}
4321
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004322status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004323 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004324
Mathias Agopianbd115332013-04-18 16:41:04 -07004325 IPCThreadState* ipc = IPCThreadState::self();
4326 const int pid = ipc->getCallingPid();
4327 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004328
Mathias Agopianbd115332013-04-18 16:41:04 -07004329 if ((uid != AID_SHELL) &&
4330 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004331 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4332 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004333 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004334 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004335 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004336 {"--dispsync"s,
4337 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004338 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004339 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4340 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4341 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4342 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4343 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4344 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004345 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004346 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4347 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004348
Dominik Laskowskic2867142019-01-21 11:33:38 -08004349 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004350
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004351 bool dumpLayers = true;
4352 {
4353 TimedLock lock(mStateLock, s2ns(1), __FUNCTION__);
4354 if (!lock.locked()) {
4355 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4356 strerror(-lock.status), lock.status);
4357 }
4358
4359 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4360 (it->second)(args, asProto, result);
4361 dumpLayers = false;
4362 } else if (!asProto) {
4363 dumpAllLocked(args, result);
4364 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004365 }
4366
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004367 if (dumpLayers) {
Dominik Laskowski46470112019-08-02 13:13:11 -07004368 const LayersProto layersProto = dumpProtoFromMainThread();
4369 if (asProto) {
4370 result.append(layersProto.SerializeAsString());
4371 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004372 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004373 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4374 result.append(LayerProtoParser::layerTreeToString(layerTree));
4375 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004376 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004377 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004378 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004379 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004380 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004381 return NO_ERROR;
4382}
4383
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004384status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4385 if (asProto && mTracing.isEnabled()) {
4386 mTracing.writeToFileAsync();
4387 }
4388
4389 return doDump(fd, DumpArgs(), asProto);
4390}
4391
Dominik Laskowskic2867142019-01-21 11:33:38 -08004392void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004393 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004394 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004395}
4396
Dominik Laskowskic2867142019-01-21 11:33:38 -08004397void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004398 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004399
Dominik Laskowskic2867142019-01-21 11:33:38 -08004400 if (args.size() > 1) {
4401 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004402 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004403 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004404 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004405 }
Robert Carr2047fae2016-11-28 14:09:09 -08004406 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004407 } else {
4408 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004409 }
4410}
4411
Dominik Laskowskic2867142019-01-21 11:33:38 -08004412void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004413 const bool clearAll = args.size() < 2;
4414 const auto name = clearAll ? String8() : String8(args[1]);
4415
Edgar Arriaga844fa672020-01-16 14:21:42 -08004416 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004417 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004418 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004419 }
Robert Carr2047fae2016-11-28 14:09:09 -08004420 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004421
Svetoslavd85084b2014-03-20 10:28:31 -07004422 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004423}
4424
Dominik Laskowskic2867142019-01-21 11:33:38 -08004425void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4426 mTimeStats->parseArgs(asProto, args, result);
4427}
4428
Jamie Gennis6547ff42013-07-16 20:12:42 -07004429// This should only be called from the main thread. Otherwise it would need
4430// the lock and should use mCurrentState rather than mDrawingState.
4431void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004432 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004433 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004434 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004435
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004436 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004437}
4438
Yiwei Zhang5434a782018-12-05 18:06:32 -08004439void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004440 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004441
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004442 if (isLayerTripleBufferingDisabled())
4443 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004444
Yiwei Zhang5434a782018-12-05 18:06:32 -08004445 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4446 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4447 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4448 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4449 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4450 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004451 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004452}
4453
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004454void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004455 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004456
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004457 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004458 result.append("\n");
4459
Ady Abraham9e16a482019-12-03 17:19:41 -08004460 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004461 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004462 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004463 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004464
Steven Thomasd4071902020-03-24 16:02:53 -07004465 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004466 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004467 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004468 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4469 policy.defaultConfig.value(), policy.primaryRange.min, policy.primaryRange.max,
4470 policy.appRequestRange.min, policy.appRequestRange.max);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004471 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4472 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004473 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4474 if (currentPolicy != policy) {
4475 StringAppendF(&result,
4476 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004477 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4478 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
4479 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
4480 currentPolicy.appRequestRange.max);
Ady Abraham07e54702020-04-16 15:05:37 -07004481 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004482
Ana Krulecc2870422019-01-29 19:00:58 -08004483 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004484 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004485}
4486
Yiwei Zhang5434a782018-12-05 18:06:32 -08004487void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4488 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004489 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4490 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004491 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004492 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004493 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004494 }
David Sodman4a36e932017-11-07 14:29:47 -08004495 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004496 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004497 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004498 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4499 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004500}
4501
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004502void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4503 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004504 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4505 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004506 for (const auto& segment : history) {
4507 if (!segment.usedThirdBuffer) {
4508 stats.twoBufferTime += segment.totalTime;
4509 }
4510 if (segment.occupancyAverage < 1.0f) {
4511 stats.doubleBufferedTime += segment.totalTime;
4512 } else if (segment.occupancyAverage < 2.0f) {
4513 stats.tripleBufferedTime += segment.totalTime;
4514 }
4515 ++stats.numSegments;
4516 stats.totalTime += segment.totalTime;
4517 }
4518}
4519
Yiwei Zhang5434a782018-12-05 18:06:32 -08004520void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4521 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004522
4523 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4524 const size_t count = currentLayers.size();
4525 for (size_t i=0 ; i<count ; i++) {
4526 currentLayers[i]->dumpFrameEvents(result);
4527 }
4528}
4529
Yiwei Zhang5434a782018-12-05 18:06:32 -08004530void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004531 result.append("Buffering stats:\n");
4532 result.append(" [Layer name] <Active time> <Two buffer> "
4533 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004534 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004535 typedef std::tuple<std::string, float, float, float> BufferTuple;
4536 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004537 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004538 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004539 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004540 if (stats.numSegments == 0) {
4541 continue;
4542 }
4543 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4544 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4545 stats.totalTime;
4546 float doubleBufferRatio = static_cast<float>(
4547 stats.doubleBufferedTime) / stats.totalTime;
4548 float tripleBufferRatio = static_cast<float>(
4549 stats.tripleBufferedTime) / stats.totalTime;
4550 sorted.insert({activeTime, {name, twoBufferRatio,
4551 doubleBufferRatio, tripleBufferRatio}});
4552 }
4553 for (const auto& sortedPair : sorted) {
4554 float activeTime = sortedPair.first;
4555 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004556 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4557 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004558 }
4559 result.append("\n");
4560}
4561
Yiwei Zhang5434a782018-12-05 18:06:32 -08004562void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004563 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004564 const auto displayId = display->getId();
4565 if (!displayId) {
4566 continue;
4567 }
4568 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004569 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004570 continue;
4571 }
4572
Yiwei Zhang5434a782018-12-05 18:06:32 -08004573 StringAppendF(&result,
4574 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4575 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004576 uint8_t port;
4577 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004578 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004579 result.append("no identification data\n");
4580 continue;
4581 }
4582
4583 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004584 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004585 continue;
4586 }
4587
4588 const auto edid = parseEdid(data);
4589 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004590 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004591 continue;
4592 }
4593
Yiwei Zhang5434a782018-12-05 18:06:32 -08004594 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004595 result.append(edid->displayName.data(), edid->displayName.length());
4596 result.append("\"\n");
4597 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004598}
4599
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004600void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4601 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004602 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004603 uint8_t port;
4604 DisplayIdentificationData data;
4605
4606 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4607 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4608 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4609 }
4610}
4611
Yiwei Zhang5434a782018-12-05 18:06:32 -08004612void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004613 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004614 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4615 StringAppendF(&result, "DisplayColorSetting: %s\n",
4616 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004617
4618 // TODO: print out if wide-color mode is active or not
4619
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004620 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004621 const auto displayId = display->getId();
4622 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004623 continue;
4624 }
4625
Yiwei Zhang5434a782018-12-05 18:06:32 -08004626 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004627 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004628 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004629 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004630 }
4631
Lloyd Pique32cbe282018-10-19 13:09:22 -07004632 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004633 StringAppendF(&result, " Current color mode: %s (%d)\n",
4634 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004635 }
4636 result.append("\n");
4637}
4638
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004639LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4640 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004641 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004642
chaviw1d044282017-09-27 12:19:28 -07004643 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004644 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004645 layer->writeToProto(layersProto, traceFlags, display.get());
chaviw08f3cb22020-01-13 13:17:21 -08004646 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004647
chaviw1d044282017-09-27 12:19:28 -07004648 return layersProto;
4649}
4650
Alec Mouri6b9e9912020-01-21 10:50:24 -08004651void SurfaceFlinger::dumpHwc(std::string& result) const {
4652 getHwComposer().dump(result);
4653}
4654
Vishnu Nair0f085c62019-08-30 08:49:12 -07004655void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4656 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4657 // it.
4658 LayerProto* rootProto = layersProto.add_layers();
4659 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4660 rootProto->set_id(offscreenRootLayerId);
4661 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004662 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004663
4664 for (Layer* offscreenLayer : mOffscreenLayers) {
4665 // Add layer as child of the fake root
4666 rootProto->add_children(offscreenLayer->sequence);
4667
4668 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004669 LayerProto* layerProto =
4670 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004671 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004672 }
4673}
4674
Vishnu Nair8406fd72019-07-30 11:29:31 -07004675LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004676 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004677}
4678
Vishnu Nair0f085c62019-08-30 08:49:12 -07004679void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4680 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004681 result.append(schedule([this] {
4682 std::string result;
4683 for (Layer* offscreenLayer : mOffscreenLayers) {
4684 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4685 [&](Layer* layer) {
4686 layer->dumpCallingUidPid(result);
4687 });
4688 }
4689 return result;
4690 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004691}
4692
Dominik Laskowskic2867142019-01-21 11:33:38 -08004693void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4694 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004695 Colorizer colorizer(colorize);
4696
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004697 // figure out if we're stuck somewhere
4698 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004699 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004700 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4701
4702 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004703 * Dump library configuration.
4704 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004705
4706 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004707 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004708 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004709 appendSfConfigString(result);
4710 appendUiConfigString(result);
4711 appendGuiConfigString(result);
4712 result.append("\n");
4713
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004714 result.append("\nDisplay identification data:\n");
4715 dumpDisplayIdentificationData(result);
4716
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004717 result.append("\nWide-Color information:\n");
4718 dumpWideColorInfo(result);
4719
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004720 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004721 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004722 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004723 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004724 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004725
Andy McFadden41d67d72014-04-25 16:58:34 -07004726 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004727 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004728 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004729 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004730 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004731
Dan Stozab90cf072015-03-05 11:05:59 -08004732 dumpStaticScreenStats(result);
4733 result.append("\n");
4734
Alec Mouri40189b02019-03-05 15:07:54 -08004735 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4736 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4737 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004738
Dan Stozae77c7662016-05-13 11:37:28 -07004739 dumpBufferingStats(result);
4740
Andy McFadden4803b742012-09-24 19:07:20 -07004741 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004742 * Dump the visible layer list
4743 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004744 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004745 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004746 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4747 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004748 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004749
Chia-I Wu2f884132018-09-13 15:17:58 -07004750 {
Lloyd Pique207def92019-02-28 16:09:52 -08004751 StringAppendF(&result, "Composition layers\n");
4752 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004753 auto* compositionState = layer->getCompositionState();
4754 if (!compositionState) return;
4755
4756 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4757 layer->getDebugName() ? layer->getDebugName()
4758 : "<unknown>");
4759 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004760 });
4761 }
4762
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004763 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004764 * Dump Display state
4765 */
4766
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004767 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004768 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004769 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004770 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004771 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004772 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004773 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004774
4775 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004776 * Dump CompositionEngine state
4777 */
4778
4779 mCompositionEngine->dump(result);
4780
4781 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004782 * Dump SurfaceFlinger global state
4783 */
4784
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004785 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004786 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004787 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004788
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004789 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004790
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004791 DebugEGLImageTracker::getInstance()->dump(result);
4792
Dominik Laskowski075d3172018-05-24 15:50:06 -07004793 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004794 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4795 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004796 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4797 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004798 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004799 StringAppendF(&result,
4800 " transaction-flags : %08x\n"
4801 " gpu_to_cpu_unsupported : %d\n",
4802 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004803
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004804 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004805 displayId && getHwComposer().isConnected(*displayId)) {
4806 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004807 StringAppendF(&result,
4808 " refresh-rate : %f fps\n"
4809 " x-dpi : %f\n"
4810 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004811 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4812 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004813 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004814
Yiwei Zhang5434a782018-12-05 18:06:32 -08004815 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004816
Dan Stozae22aec72016-08-01 13:20:59 -07004817 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004818 * Tracing state
4819 */
4820 mTracing.dump(result);
4821 result.append("\n");
4822
4823 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004824 * HWC layer minidump
4825 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004826 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004827 const auto displayId = display->getId();
4828 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004829 continue;
4830 }
4831
Yiwei Zhang5434a782018-12-05 18:06:32 -08004832 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004833 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004834
4835 const DisplayDevice& ref = *display;
4836 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07004837 result.append("\n");
4838 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004839
4840 /*
4841 * Dump HWComposer state
4842 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004843 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004844 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004845 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004846 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004847 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004848 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004849
4850 /*
4851 * Dump gralloc state
4852 */
4853 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4854 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004855
4856 /*
4857 * Dump VrFlinger state if in use.
4858 */
4859 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4860 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004861 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004862 result.append("\n");
4863 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004864
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004865 result.append(mTimeStats->miniDump());
4866 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004867}
4868
Chia-I Wu28f320b2018-05-03 11:02:56 -07004869void SurfaceFlinger::updateColorMatrixLocked() {
4870 mat4 colorMatrix;
4871 if (mGlobalSaturationFactor != 1.0f) {
4872 // Rec.709 luma coefficients
4873 float3 luminance{0.213f, 0.715f, 0.072f};
4874 luminance *= 1.0f - mGlobalSaturationFactor;
4875 mat4 saturationMatrix = mat4(
4876 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4877 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4878 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4879 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4880 );
4881 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4882 } else {
4883 colorMatrix = mClientColorMatrix * mDaltonizer();
4884 }
4885
4886 if (mCurrentState.colorMatrix != colorMatrix) {
4887 mCurrentState.colorMatrix = colorMatrix;
4888 mCurrentState.colorMatrixChanged = true;
4889 setTransactionFlags(eTransactionNeeded);
4890 }
4891}
4892
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004893status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004894#pragma clang diagnostic push
4895#pragma clang diagnostic error "-Wswitch-enum"
4896 switch (static_cast<ISurfaceComposerTag>(code)) {
4897 // These methods should at minimum make sure that the client requested
4898 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004899 case BOOT_FINISHED:
4900 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004901 case CREATE_DISPLAY:
4902 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004903 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004904 case GET_ANIMATION_FRAME_STATS:
4905 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004906 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004907 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004908 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004909 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4910 case SET_AUTO_LOW_LATENCY_MODE:
4911 case GET_GAME_CONTENT_TYPE_SUPPORT:
4912 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004913 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004914 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004915 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004916 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004917 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004918 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004919 case SET_GLOBAL_SHADOW_SETTINGS:
4920 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4921 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4922 // necessary permission dynamically. Don't use the permission cache for this check.
4923 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4924 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004925 IPCThreadState* ipc = IPCThreadState::self();
4926 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4927 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004928 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004929 }
Robert Carr1db73f62016-12-21 12:58:51 -08004930 return OK;
4931 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004932 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004933 IPCThreadState* ipc = IPCThreadState::self();
4934 const int pid = ipc->getCallingPid();
4935 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004936 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4937 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004938 return PERMISSION_DENIED;
4939 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004940 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004941 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004942 // Used by apps to hook Choreographer to SurfaceFlinger.
4943 case CREATE_DISPLAY_EVENT_CONNECTION:
4944 // The following calls are currently used by clients that do not
4945 // request necessary permissions. However, they do not expose any secret
4946 // information, so it is OK to pass them.
4947 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004948 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004949 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004950 case GET_PHYSICAL_DISPLAY_IDS:
4951 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004952 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004953 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004954 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004955 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004956 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004957 case GET_DISPLAY_STATS:
4958 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4959 // Calling setTransactionState is safe, because you need to have been
4960 // granted a reference to Client* and Handle* to do anything with it.
4961 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004962 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004963 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004964 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004965 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004966 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004967 // setFrameRate() is deliberately available for apps to call without any
4968 // special permissions.
4969 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004970 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4971 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004972 return OK;
4973 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004974 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004975 case CAPTURE_SCREEN:
4976 case ADD_REGION_SAMPLING_LISTENER:
4977 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004978 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004979 IPCThreadState* ipc = IPCThreadState::self();
4980 const int pid = ipc->getCallingPid();
4981 const int uid = ipc->getCallingUid();
4982 if ((uid != AID_GRAPHICS) &&
4983 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4984 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4985 return PERMISSION_DENIED;
4986 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004987 return OK;
4988 }
chaviw93df2ea2019-04-30 16:45:12 -07004989 case CAPTURE_SCREEN_BY_ID: {
4990 IPCThreadState* ipc = IPCThreadState::self();
4991 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004992 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004993 return OK;
4994 }
4995 return PERMISSION_DENIED;
4996 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004997 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004998
4999 // These codes are used for the IBinder protocol to either interrogate the recipient
5000 // side of the transaction for its canonical interface descriptor or to dump its state.
5001 // We let them pass by default.
5002 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5003 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5004 code == IBinder::SYSPROPS_TRANSACTION) {
5005 return OK;
5006 }
Ady Abraham07e54702020-04-16 15:05:37 -07005007 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005008 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07005009 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005010 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5011 return OK;
5012 }
5013 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5014 return PERMISSION_DENIED;
5015#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005016}
5017
Ana Krulec13be8ad2018-08-21 02:43:56 +00005018status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5019 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005020 status_t credentialCheck = CheckTransactCodeCredentials(code);
5021 if (credentialCheck != OK) {
5022 return credentialCheck;
5023 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005024
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005025 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5026 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005027 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005028 IPCThreadState* ipc = IPCThreadState::self();
5029 const int uid = ipc->getCallingUid();
5030 if (CC_UNLIKELY(uid != AID_SYSTEM
5031 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005032 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005033 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005034 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005035 return PERMISSION_DENIED;
5036 }
5037 int n;
5038 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005039 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005040 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005041 return NO_ERROR;
5042 case 1002: // SHOW_UPDATES
5043 n = data.readInt32();
5044 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005045 invalidateHwcGeometry();
5046 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005047 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005048 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005049 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005050 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005051 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005052 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005053 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005054 setTransactionFlags(
5055 eTransactionNeeded|
5056 eDisplayTransactionNeeded|
5057 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005058 return NO_ERROR;
5059 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005060 case 1006:{ // send empty update
5061 signalRefresh();
5062 return NO_ERROR;
5063 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005064 case 1008: // toggle use of hw composer
5065 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005066 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005067 invalidateHwcGeometry();
5068 repaintEverything();
5069 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005070 case 1009: // toggle use of transform hint
5071 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005072 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005073 invalidateHwcGeometry();
5074 repaintEverything();
5075 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005076 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005077 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005078 reply->writeInt32(0);
5079 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005080 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005081 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005082 return NO_ERROR;
5083 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005084 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005085 if (!display) {
5086 return NAME_NOT_FOUND;
5087 }
5088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005089 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005090 return NO_ERROR;
5091 }
5092 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005093 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005094 // daltonize
5095 n = data.readInt32();
5096 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005097 case 1:
5098 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5099 break;
5100 case 2:
5101 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5102 break;
5103 case 3:
5104 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5105 break;
5106 default:
5107 mDaltonizer.setType(ColorBlindnessType::None);
5108 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005109 }
5110 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005111 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005112 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005113 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005114 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005115
5116 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005117 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005118 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005119 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005120 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005121 // apply a color matrix
5122 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005123 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005124 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005125 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005126 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005127 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005128 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005129 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005130 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005131 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005132 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005133
5134 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5135 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005136 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005137 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5138 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5139 }
5140
Chia-I Wu28f320b2018-05-03 11:02:56 -07005141 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005142 return NO_ERROR;
5143 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005144 case 1016: { // Unused.
5145 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005146 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005147 case 1017: {
5148 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005149 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005150 return NO_ERROR;
5151 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005152 case 1018: { // Modify Choreographer's phase offset
5153 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005154 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005155 return NO_ERROR;
5156 }
5157 case 1019: { // Modify SurfaceFlinger's phase offset
5158 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005159 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005160 return NO_ERROR;
5161 }
Irvel468051e2016-06-13 16:44:44 -07005162 case 1020: { // Layer updates interceptor
5163 n = data.readInt32();
5164 if (n) {
5165 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005166 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005167 }
5168 else{
5169 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005170 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005171 }
5172 return NO_ERROR;
5173 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005174 case 1021: { // Disable HWC virtual displays
5175 n = data.readInt32();
5176 mUseHwcVirtualDisplays = !n;
5177 return NO_ERROR;
5178 }
Romain Guy0147a172017-06-01 13:53:56 -07005179 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005180 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005181 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005182
Chia-I Wu28f320b2018-05-03 11:02:56 -07005183 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005184 return NO_ERROR;
5185 }
Romain Guy54f154a2017-10-24 21:40:32 +01005186 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005187 int32_t colorMode;
5188
Chia-I Wu0d711262018-05-21 15:19:35 -07005189 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005190 if (data.readInt32(&colorMode) == NO_ERROR) {
5191 mForceColorMode = static_cast<ColorMode>(colorMode);
5192 }
Romain Guy54f154a2017-10-24 21:40:32 +01005193 invalidateHwcGeometry();
5194 repaintEverything();
5195 return NO_ERROR;
5196 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005197 // Deprecate, use 1030 to check whether the device is color managed.
5198 case 1024: {
5199 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005200 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005201 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005202 n = data.readInt32();
5203 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005204 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005205 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005206 reply->writeInt32(NO_ERROR);
5207 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005208 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005209 mTracingEnabledChanged = mTracing.disable();
5210 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005211 reply->writeInt32(mTracing.writeToFile());
5212 } else {
5213 reply->writeInt32(NO_ERROR);
5214 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005215 }
5216 return NO_ERROR;
5217 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005218 case 1026: { // Get layer tracing status
5219 reply->writeBool(mTracing.isEnabled());
5220 return NO_ERROR;
5221 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005222 // Is a DisplayColorSetting supported?
5223 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005224 const auto display = getDefaultDisplayDevice();
5225 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005226 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005227 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005228
5229 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5230 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005231 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005232 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005233 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005234 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005235 reply->writeBool(true);
5236 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005237 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005238 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005239 break;
5240 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005241 reply->writeBool(
5242 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005243 break;
5244 }
5245 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005246 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005247 // Is VrFlinger active?
5248 case 1028: {
5249 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005250 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005251 return NO_ERROR;
5252 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005253 // Set buffer size for SF tracing (value in KB)
5254 case 1029: {
5255 n = data.readInt32();
5256 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5257 ALOGW("Invalid buffer size: %d KB", n);
5258 reply->writeInt32(BAD_VALUE);
5259 return BAD_VALUE;
5260 }
5261
5262 ALOGD("Updating trace buffer to %d KB", n);
5263 mTracing.setBufferSize(n * 1024);
5264 reply->writeInt32(NO_ERROR);
5265 return NO_ERROR;
5266 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005267 // Is device color managed?
5268 case 1030: {
5269 reply->writeBool(useColorManagement);
5270 return NO_ERROR;
5271 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005272 // Override default composition data space
5273 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5274 // && adb shell stop zygote && adb shell start zygote
5275 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5276 // adb shell stop zygote && adb shell start zygote
5277 case 1031: {
5278 Mutex::Autolock _l(mStateLock);
5279 n = data.readInt32();
5280 if (n) {
5281 n = data.readInt32();
5282 if (n) {
5283 Dataspace dataspace = static_cast<Dataspace>(n);
5284 if (!validateCompositionDataspace(dataspace)) {
5285 return BAD_VALUE;
5286 }
5287 mDefaultCompositionDataspace = dataspace;
5288 }
5289 n = data.readInt32();
5290 if (n) {
5291 Dataspace dataspace = static_cast<Dataspace>(n);
5292 if (!validateCompositionDataspace(dataspace)) {
5293 return BAD_VALUE;
5294 }
5295 mWideColorGamutCompositionDataspace = dataspace;
5296 }
5297 } else {
5298 // restore composition data space.
5299 mDefaultCompositionDataspace = defaultCompositionDataspace;
5300 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5301 }
5302 return NO_ERROR;
5303 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005304 // Set trace flags
5305 case 1033: {
5306 n = data.readUint32();
5307 ALOGD("Updating trace flags to 0x%x", n);
5308 mTracing.setTraceFlags(n);
5309 reply->writeInt32(NO_ERROR);
5310 return NO_ERROR;
5311 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005312 case 1034: {
Dominik Laskowski20134642020-04-20 22:36:44 -07005313 switch (n = data.readInt32()) {
5314 case 0:
5315 case 1:
5316 enableRefreshRateOverlay(static_cast<bool>(n));
5317 break;
5318 default: {
5319 Mutex::Autolock lock(mStateLock);
5320 reply->writeBool(mRefreshRateOverlay != nullptr);
5321 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005322 }
5323 return NO_ERROR;
5324 }
Ady Abraham34392f72019-04-10 11:29:27 -07005325 case 1035: {
5326 n = data.readInt32();
5327 mDebugDisplayConfigSetByBackdoor = false;
5328 if (n >= 0) {
5329 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005330 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005331 if (result != NO_ERROR) {
5332 return result;
5333 }
5334 mDebugDisplayConfigSetByBackdoor = true;
5335 }
5336 return NO_ERROR;
5337 }
Ady Abraham07e54702020-04-16 15:05:37 -07005338 case 1036: {
5339 if (data.readInt32() > 0) {
5340 status_t result =
5341 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5342 if (result != NO_ERROR) {
5343 return result;
5344 }
5345 } else {
5346 mDebugFrameRateFlexibilityToken = nullptr;
5347 }
5348 return NO_ERROR;
5349 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005350 }
5351 }
5352 return err;
5353}
5354
Steven Thomas6d8110b2017-08-31 18:24:21 -07005355void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005356 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005357 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005358}
5359
Ana Krulec7d1d6832018-12-27 11:10:09 -08005360void SurfaceFlinger::repaintEverythingForHWC() {
5361 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005362 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005363 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005364}
5365
Ady Abrahama09852a2020-02-20 14:23:42 -08005366void SurfaceFlinger::kernelTimerChanged(bool expired) {
5367 static bool updateOverlay =
5368 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005369 if (!updateOverlay) return;
5370 if (Mutex::Autolock lock(mStateLock); !mRefreshRateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005371
5372 // Update the overlay on the main thread to avoid race conditions with
5373 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowski20134642020-04-20 22:36:44 -07005374 static_cast<void>(schedule([=] {
5375 const auto desiredActiveConfig = getDesiredActiveConfig();
5376 const auto& current = desiredActiveConfig
5377 ? mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId)
5378 : mRefreshRateConfigs->getCurrentRefreshRate();
5379 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5380
5381 if (current != min) {
Ana Krulecb9afd792020-06-11 13:16:15 -07005382 const bool timerExpired = mKernelIdleTimerEnabled && expired;
Ady Abrahama09852a2020-02-20 14:23:42 -08005383
Dominik Laskowski20134642020-04-20 22:36:44 -07005384 if (Mutex::Autolock lock(mStateLock); mRefreshRateOverlay) {
Ady Abrahama09852a2020-02-20 14:23:42 -08005385 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
Ady Abrahama09852a2020-02-20 14:23:42 -08005386 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005387 mEventQueue->invalidate();
Ady Abrahama09852a2020-02-20 14:23:42 -08005388 }
5389 }));
5390}
5391
Ana Krulecb9afd792020-06-11 13:16:15 -07005392void SurfaceFlinger::toggleKernelIdleTimer() {
5393 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
5394
5395 // If the support for kernel idle timer is disabled in SF code, don't do anything.
5396 if (!mSupportKernelIdleTimer) {
5397 return;
5398 }
5399 const KernelIdleTimerAction action = mRefreshRateConfigs->getIdleTimerAction();
5400
5401 switch (action) {
5402 case KernelIdleTimerAction::TurnOff:
5403 if (mKernelIdleTimerEnabled) {
5404 ATRACE_INT("KernelIdleTimer", 0);
5405 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "false");
5406 mKernelIdleTimerEnabled = false;
5407 }
5408 break;
5409 case KernelIdleTimerAction::TurnOn:
5410 if (!mKernelIdleTimerEnabled) {
5411 ATRACE_INT("KernelIdleTimer", 1);
5412 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "true");
5413 mKernelIdleTimerEnabled = true;
5414 }
5415 break;
5416 case KernelIdleTimerAction::NoChange:
5417 break;
5418 }
5419}
5420
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005421// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5422class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005423public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005424 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5425 ~WindowDisconnector() {
5426 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005427 }
5428
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005429private:
5430 ANativeWindow* mWindow;
5431 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005432};
5433
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005434status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005435 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005436 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5437 const Rect& sourceCrop, uint32_t reqWidth,
5438 uint32_t reqHeight, bool useIdentityTransform,
5439 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005440 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005441
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005442 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005443
Dominik Laskowski718f9602019-11-09 20:01:35 -08005444 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5445 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5446 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5447 renderAreaRotation = ui::Transform::ROT_0;
5448 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005449
Chia-I Wu20261cb2018-08-23 12:55:44 -07005450 sp<DisplayDevice> display;
5451 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005452 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005453
Chia-I Wu20261cb2018-08-23 12:55:44 -07005454 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005455 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005456
Chia-I Wucb023152018-08-28 12:57:23 -07005457 // set the requested width/height to the logical display viewport size
5458 // by default
5459 if (reqWidth == 0 || reqHeight == 0) {
5460 reqWidth = uint32_t(display->getViewport().width());
5461 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005462 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005463 }
5464
Peiyong Lin0e003c92018-09-17 11:09:51 -07005465 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005466 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005467 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5468 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005469 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005470 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005471}
5472
chaviw93df2ea2019-04-30 16:45:12 -07005473static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5474 switch (colorMode) {
5475 case ColorMode::DISPLAY_P3:
5476 case ColorMode::BT2100_PQ:
5477 case ColorMode::BT2100_HLG:
5478 case ColorMode::DISPLAY_BT2020:
5479 return Dataspace::DISPLAY_P3;
5480 default:
5481 return Dataspace::V0_SRGB;
5482 }
5483}
5484
Martin Liu4a322352020-03-24 21:30:38 +08005485status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5486 static constexpr int kFifoPriority = 2;
5487 static constexpr int kOtherPriority = 0;
5488
5489 struct sched_param param = {0};
5490 int sched_policy;
5491 if (enabled) {
5492 sched_policy = SCHED_FIFO;
5493 param.sched_priority = kFifoPriority;
5494 } else {
5495 sched_policy = SCHED_OTHER;
5496 param.sched_priority = kOtherPriority;
5497 }
5498
5499 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5500 return -errno;
5501 }
5502 return NO_ERROR;
5503}
5504
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005505sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005506 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5507 if (displayToken) {
5508 return getDisplayDeviceLocked(displayToken);
5509 }
5510 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5511 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005512 return getDisplayByLayerStack(displayOrLayerStack);
5513}
5514
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005515sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005516 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005517 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005518 return display;
5519 }
5520 }
5521 return nullptr;
5522}
5523
5524status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5525 sp<GraphicBuffer>* outBuffer) {
5526 sp<DisplayDevice> display;
5527 uint32_t width;
5528 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005529 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005530 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005531 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005532 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5533 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005534 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005535 }
5536
5537 width = uint32_t(display->getViewport().width());
5538 height = uint32_t(display->getViewport().height());
5539
Dominik Laskowski718f9602019-11-09 20:01:35 -08005540 const auto orientation = display->getOrientation();
5541 captureOrientation = ui::Transform::toRotationFlags(orientation);
5542
5543 switch (captureOrientation) {
5544 case ui::Transform::ROT_90:
5545 captureOrientation = ui::Transform::ROT_270;
5546 break;
5547
5548 case ui::Transform::ROT_270:
5549 captureOrientation = ui::Transform::ROT_90;
5550 break;
5551
5552 case ui::Transform::ROT_INVALID:
5553 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5554 captureOrientation = ui::Transform::ROT_0;
5555 break;
5556
5557 default:
5558 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005559 }
chaviw93df2ea2019-04-30 16:45:12 -07005560 *outDataspace =
5561 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5562 }
5563
5564 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5565 false /* captureSecureLayers */);
5566
5567 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5568 std::placeholders::_1);
5569 bool ignored = false;
5570 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5571 false /* useIdentityTransform */,
5572 ignored /* outCapturedSecureLayers */);
5573}
5574
Robert Carr866455f2019-04-02 16:28:26 -07005575status_t SurfaceFlinger::captureLayers(
5576 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5577 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5578 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5579 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005580 ATRACE_CALL();
5581
5582 class LayerRenderArea : public RenderArea {
5583 public:
Robert Carr578038f2018-03-09 12:25:24 -08005584 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005585 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005586 bool childrenOnly, const Rect& displayViewport)
5587 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005588 mLayer(layer),
5589 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005590 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005591 mFlinger(flinger),
5592 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005593 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005594 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005595 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005596 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005597 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005598 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005599 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005600 }
chaviwa76b2712017-09-20 12:02:26 -07005601 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005602 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005603 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005604 Rect getSourceCrop() const override {
5605 if (mCrop.isEmpty()) {
5606 return getBounds();
5607 } else {
5608 return mCrop;
5609 }
5610 }
Robert Carr578038f2018-03-09 12:25:24 -08005611 class ReparentForDrawing {
5612 public:
5613 const sp<Layer>& oldParent;
5614 const sp<Layer>& newParent;
5615
Vishnu Nair4351ad52019-02-11 14:13:02 -08005616 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5617 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005618 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005619 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005620 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5621 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005622 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005623 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005624 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005625 };
5626
5627 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005628 const Rect sourceCrop = getSourceCrop();
5629 // no need to check rotation because there is none
5630 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5631 sourceCrop.height() != getReqHeight();
5632
Robert Carr578038f2018-03-09 12:25:24 -08005633 if (!mChildrenOnly) {
5634 mTransform = mLayer->getTransform().inverse();
5635 drawLayers();
5636 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005637 uint32_t w = static_cast<uint32_t>(getWidth());
5638 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005639 // In the "childrenOnly" case we reparent the children to a screenshot
5640 // layer which has no properties set and which does not draw.
5641 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005642 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5643 "Screenshot Parent"s, w, h, 0,
5644 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005645
Vishnu Nair4351ad52019-02-11 14:13:02 -08005646 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005647 drawLayers();
5648 }
5649 }
chaviwa76b2712017-09-20 12:02:26 -07005650
chaviwa76b2712017-09-20 12:02:26 -07005651 private:
chaviw7206d492017-11-10 16:16:12 -08005652 const sp<Layer> mLayer;
5653 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005654
Peiyong Linefefaac2018-08-17 12:27:51 -07005655 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005656 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005657
5658 SurfaceFlinger* mFlinger;
5659 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005660 };
5661
Robert Carrc0df3122019-04-11 13:18:21 -07005662 int reqWidth = 0;
5663 int reqHeight = 0;
5664 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005665 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005666 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005667 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005668 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005669 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005670
Alec Mouri9a02eda2020-04-21 17:39:34 -07005671 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005672 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5673 ALOGE("captureLayers called with an invalid or removed parent");
5674 return NAME_NOT_FOUND;
5675 }
5676
5677 const int uid = IPCThreadState::self()->getCallingUid();
5678 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5679 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5680 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5681 return PERMISSION_DENIED;
5682 }
5683
Vishnu Nairefc42e22019-12-03 17:36:12 -08005684 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005685 if (sourceCrop.width() <= 0) {
5686 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005687 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005688 }
5689
5690 if (sourceCrop.height() <= 0) {
5691 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005692 crop.bottom = parentSourceBounds.getHeight();
5693 }
5694
5695 if (crop.isEmpty() || frameScale <= 0.0f) {
5696 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5697 // crop was not specified, or an invalid frame scale was provided.
5698 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005699 }
5700 reqWidth = crop.width() * frameScale;
5701 reqHeight = crop.height() * frameScale;
5702
5703 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005704 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005705 if (excludeLayer != nullptr) {
5706 excludeLayers.emplace(excludeLayer);
5707 } else {
5708 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5709 return NAME_NOT_FOUND;
5710 }
5711 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005712
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005713 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005714 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005715 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005716 }
5717
5718 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005719 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005720
Chia-I Wu20261cb2018-08-23 12:55:44 -07005721 // really small crop or frameScale
5722 if (reqWidth <= 0) {
5723 reqWidth = 1;
5724 }
5725 if (reqHeight <= 0) {
5726 reqHeight = 1;
5727 }
5728
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005729 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5730 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005731 auto traverseLayers = [parent, childrenOnly,
5732 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005733 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5734 if (!layer->isVisible()) {
5735 return;
Robert Carr578038f2018-03-09 12:25:24 -08005736 } else if (childrenOnly && layer == parent.get()) {
5737 return;
chaviwa76b2712017-09-20 12:02:26 -07005738 }
Robert Carr866455f2019-04-02 16:28:26 -07005739
5740 sp<Layer> p = layer;
5741 while (p != nullptr) {
5742 if (excludeLayers.count(p) != 0) {
5743 return;
5744 }
5745 p = p->getParent();
5746 }
5747
chaviwa76b2712017-09-20 12:02:26 -07005748 visitor(layer);
5749 });
5750 };
Robert Carr108b2c72019-04-02 16:32:58 -07005751
5752 bool outCapturedSecureLayers = false;
5753 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5754 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005755}
5756
5757status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5758 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005759 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005760 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005761 bool useIdentityTransform,
5762 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005763 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005764
Peiyong Lin0e003c92018-09-17 11:09:51 -07005765 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005766 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5767 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005768 *outBuffer =
5769 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5770 static_cast<android_pixel_format>(reqPixelFormat), 1,
5771 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005772
Robert Carr108b2c72019-04-02 16:32:58 -07005773 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005774 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005775}
5776
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005777status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5778 TraverseLayersFunction traverseLayers,
5779 const sp<GraphicBuffer>& buffer,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005780 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005781 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005782 const int uid = IPCThreadState::self()->getCallingUid();
5783 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5784
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005785 status_t result;
5786 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005787
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005788 do {
5789 std::tie(result, syncFd) =
5790 schedule([&] {
5791 if (mRefreshPending) {
5792 ATRACE_NAME("Skipping screenshot for now");
5793 return std::make_pair(EAGAIN, -1);
5794 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005795
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005796 status_t result = NO_ERROR;
5797 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005798
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005799 Mutex::Autolock lock(mStateLock);
5800 renderArea.render([&] {
5801 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5802 useIdentityTransform, forSystem, &fd,
5803 regionSampling, outCapturedSecureLayers);
5804 });
5805
5806 return std::make_pair(result, fd);
5807 }).get();
5808 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005809
5810 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005811 sync_wait(syncFd, -1);
5812 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005813 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005814
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005815 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005816}
5817
chaviwa76b2712017-09-20 12:02:26 -07005818void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005819 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005820 ANativeWindowBuffer* buffer, bool useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005821 bool regionSampling, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005822 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005823
chaviwa76b2712017-09-20 12:02:26 -07005824 const auto reqWidth = renderArea.getReqWidth();
5825 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005826 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005827 const auto transform = renderArea.getTransform();
5828 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005829 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005830
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005831 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005832 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005833
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005834 // assume that bounds are never offset, and that they are the same as the
5835 // buffer bounds.
5836 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005837 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005838 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005839
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005840 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5841 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005842
chaviw50da5042018-04-09 13:49:37 -07005843 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005844
Vishnu Nair9b079a22020-01-21 14:36:08 -08005845 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005846 fillLayer.source.buffer.buffer = nullptr;
5847 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005848 fillLayer.geometry.boundaries =
5849 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005850 fillLayer.alpha = half(alpha);
5851 clientCompositionLayers.push_back(fillLayer);
5852
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005853 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08005854 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005855 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005856 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005857 const bool supportProtectedContent = false;
5858 Region clip(renderArea.getBounds());
5859 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5860 clip,
5861 useIdentityTransform,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005862 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07005863 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005864 renderArea.isSecure(),
5865 supportProtectedContent,
5866 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005867 displayViewport,
5868 clientCompositionDisplay.outputDataspace,
5869 true, /* realContentIsVisible */
5870 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005871 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005872 std::vector<compositionengine::LayerFE::LayerSettings> results =
5873 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005874 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005875 for (auto& settings : results) {
5876 settings.geometry.positionTransform =
5877 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupinf11eba52020-04-20 18:42:31 -07005878 // There's no need to process blurs when we're executing region sampling,
5879 // we're just trying to understand what we're drawing, and doing so without
5880 // blurs is already a pretty good approximation.
5881 if (regionSampling) {
5882 settings.backgroundBlurRadius = 0;
5883 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005884 }
Yichi Chen40773d92020-04-01 10:10:18 +08005885 clientCompositionLayers.insert(clientCompositionLayers.end(),
5886 std::make_move_iterator(results.begin()),
5887 std::make_move_iterator(results.end()));
5888 renderedLayers.push_back(layer);
5889 }
chaviwa76b2712017-09-20 12:02:26 -07005890 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005891
Yichi Chen40773d92020-04-01 10:10:18 +08005892 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5893 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005894 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005895 clientCompositionLayerPointers.begin(),
5896 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005897
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005898 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005899 // Use an empty fence for the buffer fence, since we just created the buffer so
5900 // there is no need for synchronization with the GPU.
5901 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005902 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005903 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005904 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005905 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005906
5907 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005908
5909 if (*outSyncFd >= 0) {
5910 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5911 for (auto* layer : renderedLayers) {
5912 layer->onLayerDisplayed(releaseFence);
5913 }
5914 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005915}
5916
chaviwa76b2712017-09-20 12:02:26 -07005917status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5918 TraverseLayersFunction traverseLayers,
5919 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005920 bool useIdentityTransform, bool forSystem,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005921 int* outSyncFd, bool regionSampling,
5922 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005923 ATRACE_CALL();
5924
chaviwa76b2712017-09-20 12:02:26 -07005925 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005926 outCapturedSecureLayers =
5927 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005928 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005929
Robert Carr03480e22018-01-04 16:02:06 -08005930 // We allow the system server to take screenshots of secure layers for
5931 // use in situations like the Screen-rotation animation and place
5932 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005933 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005934 ALOGW("FB is protected: PERMISSION_DENIED");
5935 return PERMISSION_DENIED;
5936 }
Lucas Dupinf11eba52020-04-20 18:42:31 -07005937 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5938 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005939 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005940}
5941
chaviw95ef3c42019-02-14 10:55:09 -08005942void SurfaceFlinger::setInputWindowsFinished() {
5943 Mutex::Autolock _l(mStateLock);
5944
5945 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005946
chaviw95ef3c42019-02-14 10:55:09 -08005947 mTransactionCV.broadcast();
5948}
chaviw5f21a5e2019-02-14 10:00:34 -08005949
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005950// ---------------------------------------------------------------------------
5951
Edgar Arriaga844fa672020-01-16 14:21:42 -08005952void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5953 layersSortedByZ.traverse(visitor);
5954}
5955
Dan Stoza412903f2017-04-27 13:42:17 -07005956void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5957 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005958}
5959
Dan Stoza412903f2017-04-27 13:42:17 -07005960void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5961 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005962}
5963
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005964void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005965 const LayerVector::Visitor& visitor) {
5966 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005967 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005968 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005969 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005970 continue;
5971 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005972 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005973 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005974 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005975 return;
5976 }
chaviwa76b2712017-09-20 12:02:26 -07005977 if (!layer->isVisible()) {
5978 return;
5979 }
5980 visitor(layer);
5981 });
5982 }
5983}
5984
Steven Thomasd4071902020-03-24 16:02:53 -07005985status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5986 const sp<DisplayDevice>& display,
5987 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005988 Mutex::Autolock lock(mStateLock);
5989
Steven Thomasd4071902020-03-24 16:02:53 -07005990 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5991 "Can only set override policy on the primary display");
5992 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5993
Dominik Laskowski22488f62019-03-28 09:53:04 -07005994 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005995 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5996 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5997 // it should go thru setDesiredActiveConfig, similar to primary display.
5998 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5999 const auto displayId = display->getId();
6000 LOG_ALWAYS_FATAL_IF(!displayId);
6001
Peiyong Line9d809e2020-04-14 13:10:48 -07006002 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08006003 constraints.desiredTimeNanos = systemTime();
6004 constraints.seamlessRequired = false;
6005
Peiyong Line9d809e2020-04-14 13:10:48 -07006006 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07006007 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
6008 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006009 constraints, &timeline) < 0) {
6010 return BAD_VALUE;
6011 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08006012 if (timeline.refreshRequired) {
6013 repaintEverythingForHWC();
6014 }
6015
Steven Thomasd4071902020-03-24 16:02:53 -07006016 display->setActiveConfig(policy->defaultConfig);
6017 const nsecs_t vsyncPeriod = getHwComposer()
6018 .getConfigs(*displayId)[policy->defaultConfig.value()]
6019 ->getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006020 mScheduler->onNonPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6021 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006022 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08006023 }
6024
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006025 if (mDebugDisplayConfigSetByBackdoor) {
6026 // ignore this request as config is overridden by backdoor
6027 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006028 }
6029
Steven Thomasd4071902020-03-24 16:02:53 -07006030 status_t setPolicyResult = overridePolicy
6031 ? mRefreshRateConfigs->setOverridePolicy(policy)
6032 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
6033 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006034 return BAD_VALUE;
6035 }
Steven Thomasd4071902020-03-24 16:02:53 -07006036 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006037 return NO_ERROR;
6038 }
Steven Thomasd4071902020-03-24 16:02:53 -07006039 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006040
Steven Thomasf734df42020-04-13 21:09:28 -07006041 ALOGV("Setting desired display config specs: defaultConfig: %d primaryRange: [%.0f %.0f]"
6042 " expandedRange: [%.0f %.0f]",
6043 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
6044 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
6045 currentPolicy.appRequestRange.max);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006046
Ana Krulecb9afd792020-06-11 13:16:15 -07006047 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6048 // be depending in this callback.
Alec Mouri60aee1c2019-10-28 16:18:59 -07006049 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07006050 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
6051 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006052 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6053 display->getActiveConfig(), vsyncPeriod);
Ana Krulecb9afd792020-06-11 13:16:15 -07006054 toggleKernelIdleTimer();
Ady Abraham838de062019-02-04 10:24:03 -08006055
Ana Krulec3f6a2062020-01-23 15:48:01 -08006056 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08006057 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08006058 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
6059 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07006060 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08006061 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07006062 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006063
Ady Abrahamabc27602020-04-08 17:20:29 -07006064 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
6065 ALOGV("switching to Scheduler preferred config %d",
6066 preferredRefreshRate.getConfigId().value());
6067 setDesiredActiveConfig(
6068 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006069 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07006070 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
6071 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006072 }
6073
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006074 return NO_ERROR;
6075}
6076
Ana Krulec0782b882019-10-15 17:34:54 -07006077status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Steven Thomasf734df42020-04-13 21:09:28 -07006078 int32_t defaultConfig,
6079 float primaryRefreshRateMin,
6080 float primaryRefreshRateMax,
6081 float appRequestRefreshRateMin,
6082 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006083 ATRACE_CALL();
6084
6085 if (!displayToken) {
6086 return BAD_VALUE;
6087 }
6088
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006089 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006090 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006091 if (!display) {
6092 ALOGE("Attempt to set desired display configs for invalid display token %p",
6093 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006094 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006095 } else if (display->isVirtual()) {
6096 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006097 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006098 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006099 using Policy = scheduler::RefreshRateConfigs::Policy;
Steven Thomasf734df42020-04-13 21:09:28 -07006100 const Policy policy{HwcConfigIndexType(defaultConfig),
6101 {primaryRefreshRateMin, primaryRefreshRateMax},
6102 {appRequestRefreshRateMin, appRequestRefreshRateMax}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006103 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006104
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006105 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
6106 }
6107 });
6108
6109 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006110}
6111
6112status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006113 int32_t* outDefaultConfig,
Steven Thomasf734df42020-04-13 21:09:28 -07006114 float* outPrimaryRefreshRateMin,
6115 float* outPrimaryRefreshRateMax,
6116 float* outAppRequestRefreshRateMin,
6117 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006118 ATRACE_CALL();
6119
Steven Thomasf734df42020-04-13 21:09:28 -07006120 if (!displayToken || !outDefaultConfig || !outPrimaryRefreshRateMin ||
6121 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006122 return BAD_VALUE;
6123 }
6124
6125 Mutex::Autolock lock(mStateLock);
6126 const auto display = getDisplayDeviceLocked(displayToken);
6127 if (!display) {
6128 return NAME_NOT_FOUND;
6129 }
6130
6131 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006132 scheduler::RefreshRateConfigs::Policy policy =
6133 mRefreshRateConfigs->getDisplayManagerPolicy();
6134 *outDefaultConfig = policy.defaultConfig.value();
Steven Thomasf734df42020-04-13 21:09:28 -07006135 *outPrimaryRefreshRateMin = policy.primaryRange.min;
6136 *outPrimaryRefreshRateMax = policy.primaryRange.max;
6137 *outAppRequestRefreshRateMin = policy.appRequestRange.min;
6138 *outAppRequestRefreshRateMax = policy.appRequestRange.max;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006139 return NO_ERROR;
6140 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006141 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006142 } else {
6143 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006144 LOG_FATAL_IF(!displayId);
6145
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006146 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6147 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
Steven Thomasf734df42020-04-13 21:09:28 -07006148 *outPrimaryRefreshRateMin = 1e9f / vsyncPeriod;
6149 *outPrimaryRefreshRateMax = 1e9f / vsyncPeriod;
6150 *outAppRequestRefreshRateMin = 1e9f / vsyncPeriod;
6151 *outAppRequestRefreshRateMax = 1e9f / vsyncPeriod;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006152 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006153 }
Ana Krulec0782b882019-10-15 17:34:54 -07006154}
6155
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006156void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006157 mFlinger->setInputWindowsFinished();
6158}
6159
Alec Mouri9a02eda2020-04-21 17:39:34 -07006160wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6161 Mutex::Autolock _l(mStateLock);
6162 return fromHandleLocked(handle);
6163}
6164
6165wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006166 BBinder* b = nullptr;
6167 if (handle) {
6168 b = handle->localBinder();
6169 }
Robert Carrc0df3122019-04-11 13:18:21 -07006170 if (b == nullptr) {
6171 return nullptr;
6172 }
6173 auto it = mLayersByLocalBinderToken.find(b);
6174 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006175 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006176 }
6177 return nullptr;
6178}
6179
Dominik Laskowski75848362019-11-11 17:57:20 -08006180void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006181 mNumLayers++;
6182 mScheduler->registerLayer(layer);
6183}
6184
6185void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6186 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006187 removeFromOffscreenLayers(layer);
6188}
6189
6190// WARNING: ONLY CALL THIS FROM LAYER DTOR
6191// Here we add children in the current state to offscreen layers and remove the
6192// layer itself from the offscreen layer list. Since
6193// this is the dtor, it is safe to access the current state. This keeps us
6194// from dangling children layers such that they are not reachable from the
6195// Drawing state nor the offscreen layer list
6196// See b/141111965
6197void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6198 for (auto& child : layer->getCurrentChildren()) {
6199 mOffscreenLayers.emplace(child.get());
6200 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006201 mOffscreenLayers.erase(layer);
6202}
6203
Alec Mouri4545a8a2019-08-08 20:05:32 -07006204void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6205 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6206}
6207
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006208status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6209 float lightPosY, float lightPosZ,
6210 float lightRadius) {
6211 Mutex::Autolock _l(mStateLock);
6212 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6213 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6214 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6215 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6216 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6217
6218 // these values are overridden when calculating the shadow settings for a layer.
6219 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6220 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006221 return NO_ERROR;
6222}
6223
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006224const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6225 const {
6226 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6227 // on the work to remove the table in that bug rather than adding more to
6228 // it.
6229 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6230 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6231 // supported, and exposed via the
6232 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6233 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6234 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6235 };
6236 return genericLayerMetadataKeyMap;
6237}
6238
Steven Thomas62a4cf82020-01-31 12:04:03 -08006239status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6240 int8_t compatibility) {
6241 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6242 return BAD_VALUE;
6243 }
6244
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006245 static_cast<void>(schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006246 Mutex::Autolock lock(mStateLock);
6247 if (authenticateSurfaceTextureLocked(surface)) {
6248 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6249 if (layer->setFrameRate(
6250 Layer::FrameRate(frameRate,
6251 Layer::FrameRate::convertCompatibility(compatibility)))) {
6252 setTransactionFlags(eTraversalNeeded);
6253 }
6254 } else {
6255 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6256 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006257 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006258 return NO_ERROR;
6259 }));
6260
Steven Thomas62a4cf82020-01-31 12:04:03 -08006261 return NO_ERROR;
6262}
6263
Steven Thomasd4071902020-03-24 16:02:53 -07006264status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6265 if (!outToken) {
6266 return BAD_VALUE;
6267 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006268
6269 auto future = schedule([this] {
6270 status_t result = NO_ERROR;
6271 sp<IBinder> token;
6272
Steven Thomasd4071902020-03-24 16:02:53 -07006273 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006274 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Steven Thomasd4071902020-03-24 16:02:53 -07006275
6276 // This is a little racy, but not in a way that hurts anything. As we grab the
6277 // defaultConfig from the display manager policy, we could be setting a new display
6278 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6279 // matter for the override policy though, since we set allowGroupSwitching to true, so
6280 // it's not a problem.
6281 scheduler::RefreshRateConfigs::Policy overridePolicy;
6282 overridePolicy.defaultConfig =
6283 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6284 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006285 constexpr bool kOverridePolicy = true;
6286 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006287 }
6288
6289 if (result == NO_ERROR) {
6290 mFrameRateFlexibilityTokenCount++;
6291 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6292 // below, is something to consider carefully. The lifetime of the
6293 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6294 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6295 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6296 // in this case, for two reasons:
6297 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6298 // the program exits is via a crash. So we won't have a situation where the
6299 // SurfaceFlinger object is dead but the process is still up.
6300 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6301 // if condition 1 were changed, the problem would only show up when running CTS tests,
6302 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006303 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006304 [this]() { onFrameRateFlexibilityTokenReleased(); });
6305 ALOGD("Frame rate flexibility token acquired. count=%d",
6306 mFrameRateFlexibilityTokenCount);
6307 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006308
6309 return std::make_pair(result, token);
6310 });
6311
6312 status_t result;
6313 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006314 return result;
6315}
6316
6317void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006318 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006319 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6320 "Failed tracking frame rate flexibility tokens");
6321 mFrameRateFlexibilityTokenCount--;
6322 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6323 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006324 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006325 constexpr bool kOverridePolicy = true;
6326 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006327 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6328 }
6329 }));
6330}
6331
Dominik Laskowski20134642020-04-20 22:36:44 -07006332void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
6333 static_cast<void>(schedule([=] {
6334 std::unique_ptr<RefreshRateOverlay> overlay;
6335 if (enable) {
6336 overlay = std::make_unique<RefreshRateOverlay>(*this);
6337 }
6338
6339 {
6340 Mutex::Autolock lock(mStateLock);
6341
6342 // Destroy the layer of the current overlay, if any, outside the lock.
6343 mRefreshRateOverlay.swap(overlay);
6344 if (!mRefreshRateOverlay) return;
6345
6346 if (const auto display = getDefaultDisplayDeviceLocked()) {
6347 mRefreshRateOverlay->setViewport(display->getSize());
6348 }
6349
6350 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
6351 }
6352 }));
6353}
6354
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006355} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006356
Mathias Agopian3f844832013-08-07 21:24:32 -07006357#if defined(__gl_h_)
6358#error "don't include gl/gl.h in this file"
6359#endif
6360
6361#if defined(__gl2_h_)
6362#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006363#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006364
6365// TODO(b/129481165): remove the #pragma below and fix conversion issues
6366#pragma clang diagnostic pop // ignored "-Wconversion"