blob: 06261756ab0ff65d27f33cee4a36c7222051350b [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>
Alec Mouri989ddbe2020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000059#include <hidl/ServiceManagement.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;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800269int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100270uint32_t SurfaceFlinger::maxGraphicsWidth;
271uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600272bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800273ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700274bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700275bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700276Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
277ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
278Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
279ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800280bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700281
Kalle Raitaa099a242017-01-11 11:17:29 -0800282std::string getHwcServiceName() {
283 char value[PROPERTY_VALUE_MAX] = {};
284 property_get("debug.sf.hwc_service_name", value, "default");
285 ALOGI("Using HWComposer service: '%s'", value);
286 return std::string(value);
287}
288
289bool useTrebleTestingOverride() {
290 char value[PROPERTY_VALUE_MAX] = {};
291 property_get("debug.sf.treble_testing_override", value, "false");
292 ALOGI("Treble testing override: '%s'", value);
293 return std::string(value) == "true";
294}
295
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800296std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
297 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800298 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700299 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800300 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700301 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800302 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700303 return std::string("Enhanced");
304 default:
305 return std::string("Unknown ") +
306 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800307 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800308}
309
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700310SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800311
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700312SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
313 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700314 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700315 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700316 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700317 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700318 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800319 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
320 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800321
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700322SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800323 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800324
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900327 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700328
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900329 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700330
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900331 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800332
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900333 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800334
Brian Lindahla13f2d52020-03-05 11:54:17 +0100335 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
336 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
337
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900338 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700339
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900340 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600341
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 mDefaultCompositionDataspace =
343 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700344 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
345 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900346 defaultCompositionDataspace = mDefaultCompositionDataspace;
347 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
348 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
349 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
350 wideColorGamutCompositionPixelFormat =
351 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700352
Yichi Chenda901bf2019-06-28 14:58:27 +0800353 mColorSpaceAgnosticDataspace =
354 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
355
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900356 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800357
Dominik Laskowski718f9602019-11-09 20:01:35 -0800358 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
359 switch (primary_display_orientation(Values::ORIENTATION_0)) {
360 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800361 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800362 case Values::ORIENTATION_90:
363 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800364 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800365 case Values::ORIENTATION_180:
366 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800367 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800368 case Values::ORIENTATION_270:
369 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800370 break;
371 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800372 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800373
Sundong Ahn85131bd2019-02-18 15:51:53 +0900374 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376 // debugging stuff...
377 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700378
Mathias Agopianb4b17302013-03-20 18:36:41 -0700379 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700380 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700381
Alec Mouri989ddbe2020-02-06 09:26:19 -0800382 property_get("ro.build.type", value, "user");
383 mIsUserBuild = strcmp(value, "user") == 0;
384
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385 property_get("debug.sf.showupdates", value, "0");
386 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700387
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700388 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000389
390 // DDMS debugging deprecated (b/120782499)
391 property_get("debug.sf.ddms", value, "0");
392 int debugDdms = atoi(value);
393 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700394
395 property_get("debug.sf.disable_backpressure", value, "0");
396 mPropagateBackpressure = !atoi(value);
397 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700398
Ady Abrahamadb9a992019-09-19 21:21:55 +0000399 property_get("debug.sf.enable_gl_backpressure", value, "0");
400 mPropagateBackpressureClientComposition = atoi(value);
401 ALOGI_IF(mPropagateBackpressureClientComposition,
402 "Enabling backpressure propagation for Client Composition");
403
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800404 property_get("debug.sf.enable_hwc_vds", value, "0");
405 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800406 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800407
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800408 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800409 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800410 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700411
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800412 property_get("ro.surface_flinger.supports_background_blur", value, "0");
413 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700414 mSupportsBlur = supportsBlurs;
415 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800416 property_get("ro.sf.blurs_are_expensive", value, "0");
417 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800418
Ady Abraham0a525092020-03-03 12:51:24 -0800419 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700420 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
421 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
422
Dan Stozaec460082018-12-17 15:35:09 -0800423 property_get("debug.sf.luma_sampling", value, "1");
424 mLumaSampling = atoi(value);
425
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800426 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800427 mDisableClientCompositionCache = atoi(value);
428
Romain Guy11d63f42017-07-20 12:47:14 -0700429 // We should be reading 'persist.sys.sf.color_saturation' here
430 // but since /data may be encrypted, we need to wait until after vold
431 // comes online to attempt to read the property. The property is
432 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800433
434 if (useTrebleTestingOverride()) {
435 // Without the override SurfaceFlinger cannot connect to HIDL
436 // services that are not listed in the manifests. Considered
437 // deriving the setting from the set service name, but it
438 // would be brittle if the name that's not 'default' is used
439 // for production purposes later on.
Steven Moreland7c8af942020-07-08 18:35:51 +0000440 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800441 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800442
443 useFrameRateApi = use_frame_rate_api(true);
Ana Krulecb9afd792020-06-11 13:16:15 -0700444
445 mKernelIdleTimerEnabled = mSupportKernelIdleTimer = sysprop::support_kernel_idle_timer(false);
446 base::SetProperty(KERNEL_IDLE_TIMER_PROP, mKernelIdleTimerEnabled ? "true" : "false");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447}
448
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700449SurfaceFlinger::~SurfaceFlinger() = default;
450
451void SurfaceFlinger::onFirstRef() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800452 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800453}
454
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700455void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800456 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700457 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800458
Andy McFadden13a082e2012-08-24 10:16:42 -0700459 // restore initial conditions (default device unblank, etc)
460 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800461
462 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700463 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800464}
465
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700466void SurfaceFlinger::run() {
467 while (true) {
468 mEventQueue->waitMessage();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800469 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700470}
471
472template <typename F, typename T>
473inline std::future<T> SurfaceFlinger::schedule(F&& f) {
474 auto [task, future] = makeTask(std::move(f));
475 mEventQueue->postMessage(std::move(task));
476 return std::move(future);
Robert Carr1db73f62016-12-21 12:58:51 -0800477}
478
479sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700480 const sp<Client> client = new Client(this);
481 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800482}
483
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700484sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485 class DisplayToken : public BBinder {
486 sp<SurfaceFlinger> flinger;
487 virtual ~DisplayToken() {
488 // no more references, this display must be terminated
489 Mutex::Autolock _l(flinger->mStateLock);
490 flinger->mCurrentState.displays.removeItem(this);
491 flinger->setTransactionFlags(eDisplayTransactionNeeded);
492 }
493 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700494 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 : flinger(flinger) {
496 }
497 };
498
499 sp<BBinder> token = new DisplayToken(this);
500
501 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502 // Display ID is assigned when virtual display is allocated by HWC.
503 DisplayDeviceState state;
504 state.isSecure = secure;
505 state.displayName = displayName;
506 mCurrentState.displays.add(token, state);
507 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508 return token;
509}
510
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700511void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700512 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700513
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700514 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700515 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700516 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700517 return;
518 }
519
Dominik Laskowski075d3172018-05-24 15:50:06 -0700520 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700521 if (state.physical) {
522 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700523 return;
524 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700525 mInterceptor->saveDisplayDeletion(state.sequenceId);
526 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700527 setTransactionFlags(eDisplayTransactionNeeded);
528}
529
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800530std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
531 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700532
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800533 const auto internalDisplayId = getInternalDisplayIdLocked();
534 if (!internalDisplayId) {
535 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700536 }
537
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800538 std::vector<PhysicalDisplayId> displayIds;
539 displayIds.reserve(mPhysicalDisplayTokens.size());
540 displayIds.push_back(internalDisplayId->value);
541
542 for (const auto& [id, token] : mPhysicalDisplayTokens) {
543 if (id != *internalDisplayId) {
544 displayIds.push_back(id.value);
545 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700546 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700547
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800548 return displayIds;
549}
550
551sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
552 Mutex::Autolock lock(mStateLock);
553 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700554}
555
Ady Abraham37965d42018-11-01 13:43:32 -0700556status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
557 if (!outGetColorManagement) {
558 return BAD_VALUE;
559 }
560 *outGetColorManagement = useColorManagement;
561 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700562}
563
Lloyd Pique441d5042018-10-18 16:49:51 -0700564HWComposer& SurfaceFlinger::getHwComposer() const {
565 return mCompositionEngine->getHwComposer();
566}
567
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700568renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
569 return mCompositionEngine->getRenderEngine();
570}
571
Lloyd Pique70d91362018-10-18 16:02:55 -0700572compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
573 return *mCompositionEngine.get();
574}
575
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800576void SurfaceFlinger::bootFinished()
577{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700578 if (mBootFinished == true) {
579 ALOGE("Extra call to bootFinished");
580 return;
581 }
582 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700583 if (mStartPropertySetThread->join() != NO_ERROR) {
584 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800585 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800586 const nsecs_t now = systemTime();
587 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000588 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700589
Mikael Pessa90092f42019-08-26 17:22:04 -0700590 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000591 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700592
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700593 // wait patiently for the window manager death
594 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700595 mWindowManager = defaultServiceManager()->getService(name);
596 if (mWindowManager != 0) {
597 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700598 }
599
600 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700601 // formerly we would just kill the process, but we now ask it to exit so it
602 // can choose where to stop the animation.
603 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700604
605 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
606 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
607 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700608
Denis Hsu58fbf9f2020-06-17 10:17:30 +0800609 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
610
Chavi Weingarten60f3ab22020-12-09 00:36:11 +0000611 static_cast<void>(schedule([=] {
Denis Hsu58fbf9f2020-06-17 10:17:30 +0800612 if (input == nullptr) {
613 ALOGE("Failed to link to input service");
614 } else {
615 mInputFlinger = interface_cast<IInputFlinger>(input);
616 }
617
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800618 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700619 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800620 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800621
Ady Abraham8a82ba62020-01-17 12:43:17 -0800622 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700623 enableRefreshRateOverlay(true);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800624 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800625 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800626}
627
Dan Stoza436ccf32018-06-21 12:10:12 -0700628uint32_t SurfaceFlinger::getNewTexture() {
629 {
630 std::lock_guard lock(mTexturePoolMutex);
631 if (!mTexturePool.empty()) {
632 uint32_t name = mTexturePool.back();
633 mTexturePool.pop_back();
634 ATRACE_INT("TexturePoolSize", mTexturePool.size());
635 return name;
636 }
637
638 // The pool was too small, so increase it for the future
639 ++mTexturePoolSize;
640 }
641
642 // The pool was empty, so we need to get a new texture name directly using a
643 // blocking call to the main thread
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700644 return schedule([this] {
645 uint32_t name = 0;
646 getRenderEngine().genTextures(1, &name);
647 return name;
648 })
649 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700650}
651
Mathias Agopian3f844832013-08-07 21:24:32 -0700652void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700653 std::lock_guard lock(mTexturePoolMutex);
654 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
655 // to actually delete this or not based on mTexturePoolSize
656 mTexturePool.push_back(texture);
657 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700658}
659
Wei Wangf9b05ee2017-07-19 20:59:39 -0700660// Do not call property_set on main thread which will be blocked by init
661// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700662void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700663 ALOGI( "SurfaceFlinger's main thread ready to run. "
664 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700665 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800666
Steven Thomasb02664d2017-07-26 18:48:28 -0700667 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700668 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800669 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700670 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
671 renderengine::RenderEngineCreationArgs::Builder()
672 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
673 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
674 .setUseColorManagerment(useColorManagement)
675 .setEnableProtectedContext(enable_protected_contents(false))
676 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700677 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700678 .setContextPriority(useContextPriority
679 ? renderengine::RenderEngine::ContextPriority::HIGH
680 : renderengine::RenderEngine::ContextPriority::MEDIUM)
681 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800682 mCompositionEngine->setTimeStats(mTimeStats);
Lloyd Pique441d5042018-10-18 16:49:51 -0700683 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800684 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800685 // Process any initial hotplug and resulting display changes.
686 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700687 const auto display = getDefaultDisplayDeviceLocked();
688 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700689 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700690 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800691
Mathias Agopian92a979a2012-08-02 18:32:23 -0700692 // initialize our drawing state
693 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700694
Andy McFadden13a082e2012-08-24 10:16:42 -0700695 // set initial conditions (e.g. unblank default device)
696 initializeDisplays();
697
Steven Thomas137d4bc2019-07-25 16:55:14 -0700698 char primeShaderCache[PROPERTY_VALUE_MAX];
699 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
700 if (atoi(primeShaderCache)) {
701 getRenderEngine().primeCache();
702 }
Dan Stoza4e637772016-07-28 13:31:51 -0700703
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700705
706 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700707 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700708 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709
710 if (mStartPropertySetThread->Start() != NO_ERROR) {
711 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800713
Dan Stoza9e56aa02015-11-02 13:00:03 -0800714 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700715}
716
Romain Guy11d63f42017-07-20 12:47:14 -0700717void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700718 Mutex::Autolock _l(mStateLock);
719
Romain Guy11d63f42017-07-20 12:47:14 -0700720 char value[PROPERTY_VALUE_MAX];
721
722 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800723 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700724 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800725 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100726
727 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700728 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800729
730 property_get("persist.sys.sf.color_mode", value, "0");
731 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700732
733 property_get("persist.sys.sf.disable_blurs", value, "0");
734 bool disableBlurs = atoi(value);
735 mDisableBlurs = disableBlurs;
736 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700737}
738
Mathias Agopiana67e4182012-06-19 17:26:12 -0700739void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800740 // Start boot animation service by setting a property mailbox
741 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800743 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 if (mStartPropertySetThread->join() != NO_ERROR) {
745 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800746 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700747}
748
Mathias Agopian875d8e12013-06-07 15:35:48 -0700749size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700750 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700754 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800757// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800758
Jamie Gennis582270d2011-08-17 18:19:00 -0700759bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800760 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800761 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800762 return authenticateSurfaceTextureLocked(bufferProducer);
763}
764
765bool SurfaceFlinger::authenticateSurfaceTextureLocked(
766 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800767 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800768 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800769}
770
Brian Anderson6b376712017-04-04 10:51:39 -0700771status_t SurfaceFlinger::getSupportedFrameTimestamps(
772 std::vector<FrameEvent>* outSupported) const {
773 *outSupported = {
774 FrameEvent::REQUESTED_PRESENT,
775 FrameEvent::ACQUIRE,
776 FrameEvent::LATCH,
777 FrameEvent::FIRST_REFRESH_START,
778 FrameEvent::LAST_REFRESH_START,
779 FrameEvent::GPU_COMPOSITION_DONE,
780 FrameEvent::DEQUEUE_READY,
781 FrameEvent::RELEASE,
782 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700783 ConditionalLock _l(mStateLock,
784 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700785 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700786 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
787 }
788 return NO_ERROR;
789}
790
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800791status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
792 if (!displayToken || !state) {
793 return BAD_VALUE;
794 }
795
796 Mutex::Autolock lock(mStateLock);
797
798 const auto display = getDisplayDeviceLocked(displayToken);
799 if (!display) {
800 return NAME_NOT_FOUND;
801 }
802
803 state->layerStack = display->getLayerStack();
804 state->orientation = display->getOrientation();
805
806 const Rect viewport = display->getViewport();
807 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
808
809 return NO_ERROR;
810}
811
812status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
813 if (!displayToken || !info) {
814 return BAD_VALUE;
815 }
816
817 Mutex::Autolock lock(mStateLock);
818
819 const auto display = getDisplayDeviceLocked(displayToken);
820 if (!display) {
821 return NAME_NOT_FOUND;
822 }
823
Dominik Laskowski55c85402020-01-21 16:25:47 -0800824 if (const auto connectionType = display->getConnectionType())
825 info->connectionType = *connectionType;
826 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800827 return INVALID_OPERATION;
828 }
829
830 if (mEmulatedDisplayDensity) {
831 info->density = mEmulatedDisplayDensity;
832 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800833 info->density = info->connectionType == DisplayConnectionType::Internal
834 ? mInternalDisplayDensity
835 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800836 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700837 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800838
839 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200840 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800841
842 return NO_ERROR;
843}
844
Dominik Laskowski22488f62019-03-28 09:53:04 -0700845status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800846 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700847 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 return BAD_VALUE;
849 }
850
Dominik Laskowski22488f62019-03-28 09:53:04 -0700851 Mutex::Autolock lock(mStateLock);
852
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800853 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700854 if (!displayId) {
855 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700856 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700857
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800858 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700859
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700861
Dominik Laskowski075d3172018-05-24 15:50:06 -0700862 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800863 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700864
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800865 auto width = hwConfig->getWidth();
866 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700867
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800868 auto xDpi = hwConfig->getDpiX();
869 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700870
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800871 if (isInternal &&
872 (internalDisplayOrientation == ui::ROTATION_90 ||
873 internalDisplayOrientation == ui::ROTATION_270)) {
874 std::swap(width, height);
875 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 }
877
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800878 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800879
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800880 if (mEmulatedDisplayDensity) {
881 config.xDpi = mEmulatedDisplayDensity;
882 config.yDpi = mEmulatedDisplayDensity;
883 } else {
884 config.xDpi = xDpi;
885 config.yDpi = yDpi;
886 }
887
888 const nsecs_t period = hwConfig->getVsyncPeriod();
889 config.refreshRate = 1e9f / period;
890
891 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
892 config.appVsyncOffset = offsets.late.app;
893 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800894 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800895
Andy McFadden91b2ca82014-06-13 14:04:23 -0700896 // This is how far in advance a buffer must be queued for
897 // presentation at a given time. If you want a buffer to appear
898 // on the screen at time N, you must submit the buffer before
899 // (N - presentationDeadline).
900 //
901 // Normally it's one full refresh period (to give SF a chance to
902 // latch the buffer), but this can be reduced by configuring a
903 // DispSync offset. Any additional delays introduced by the hardware
904 // composer or panel must be accounted for here.
905 //
906 // We add an additional 1ms to allow for processing time and
907 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800908 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700909
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800910 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700911 }
912
Dan Stoza7f7da322014-05-02 15:26:25 -0700913 return NO_ERROR;
914}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700915
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700916status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
917 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700918 return BAD_VALUE;
919 }
920
Ana Krulecc2870422019-01-29 19:00:58 -0800921 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return NO_ERROR;
923}
924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700926 int activeConfig;
927 bool isPrimary;
928
929 {
930 Mutex::Autolock lock(mStateLock);
931
932 if (const auto display = getDisplayDeviceLocked(displayToken)) {
933 activeConfig = display->getActiveConfig().value();
934 isPrimary = display->isPrimary();
935 } else {
936 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
937 return NAME_NOT_FOUND;
938 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800939 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700940
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700941 if (isPrimary) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700942 if (const auto config = getDesiredActiveConfig()) {
943 return config->configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700944 }
Steven Thomasc9098452019-09-30 17:15:05 -0700945 }
Ady Abraham2139f732019-11-13 18:56:40 -0800946
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700947 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700948}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700949
Ady Abraham03b02dd2019-03-21 15:40:11 -0700950void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800951 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800952 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700953 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800954
Ady Abrahamb838aed2019-02-12 15:30:16 -0800955 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800956 if (mDesiredActiveConfigChanged) {
957 // If a config change is pending, just cache the latest request in
958 // mDesiredActiveConfig
959 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
960 mDesiredActiveConfig = info;
961 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
962 } else {
963 // Check is we are already at the desired config
964 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700965 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800966 return;
967 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800968
Ady Abraham59db0a32020-03-02 18:04:20 -0800969 // Initiate a config change.
970 mDesiredActiveConfigChanged = true;
971 mDesiredActiveConfig = info;
972
Ady Abrahamb838aed2019-02-12 15:30:16 -0800973 // This will trigger HWC refresh without resetting the idle timer.
974 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700975 // Start receiving vsync samples now, so that we can detect a period
976 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700977 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700978 // As we called to set period, we will call to onRefreshRateChangeCompleted once
979 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700980 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800981
Ady Abrahamabc27602020-04-08 17:20:29 -0700982 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800983 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -0700984 mScheduler->setConfigChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700986
987 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800988 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700989 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990}
991
992status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
993 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800994
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100995 if (!displayToken) {
996 return BAD_VALUE;
997 }
Ady Abraham838de062019-02-04 10:24:03 -0800998
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700999 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001000 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001001 if (!display) {
1002 ALOGE("Attempt to set allowed display configs for invalid display token %p",
1003 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001004 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001005 } else if (display->isVirtual()) {
1006 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001007 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001008 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001009 const HwcConfigIndexType config(mode);
1010 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
Steven Thomasf734df42020-04-13 21:09:28 -07001011 const scheduler::RefreshRateConfigs::Policy policy{config, {fps, fps}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001012 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001013
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001014 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1015 }
1016 });
1017
1018 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001019}
1020
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001021void SurfaceFlinger::setActiveConfigInternal() {
1022 ATRACE_CALL();
1023
Dominik Laskowski22488f62019-03-28 09:53:04 -07001024 const auto display = getDefaultDisplayDeviceLocked();
1025 if (!display) {
1026 return;
1027 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001028
Alec Mouri8de697e2020-03-19 10:52:01 -07001029 auto& oldRefreshRate =
1030 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1031
Dominik Laskowski22488f62019-03-28 09:53:04 -07001032 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001033 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001034 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001035 display->setActiveConfig(mUpcomingActiveConfig.configId);
1036
Ady Abraham2e1dd892020-03-05 13:48:36 -08001037 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001038 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001039 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001040 mTimeStats->incrementRefreshRateSwitches();
1041 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001042 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001043 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001044 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001045
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001046 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001047 const nsecs_t vsyncPeriod =
1048 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001049 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001050 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
1051 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001052 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001053}
1054
Ady Abraham53852a52019-05-28 18:07:44 -07001055void SurfaceFlinger::desiredActiveConfigChangeDone() {
1056 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1057 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1058 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001059
Ady Abraham2e1dd892020-03-05 13:48:36 -08001060 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001061 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001062 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1063 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001064 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001065 mScheduler->setConfigChangePending(false);
Ady Abraham53852a52019-05-28 18:07:44 -07001066}
1067
Ady Abraham27cbed72020-04-10 12:56:59 -07001068void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001069 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001070 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001071 // Store the local variable to release the lock.
Dominik Laskowski20134642020-04-20 22:36:44 -07001072 const auto desiredActiveConfig = getDesiredActiveConfig();
Ady Abraham27cbed72020-04-10 12:56:59 -07001073 if (!desiredActiveConfig) {
1074 // No desired active config pending to be applied
1075 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001076 }
1077
Ady Abraham2e1dd892020-03-05 13:48:36 -08001078 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001079 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001080 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1081 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001082 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001083 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001084 // display is not valid or we are already in the requested mode
1085 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001086 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001087 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001088 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001089
Ady Abraham838de062019-02-04 10:24:03 -08001090 // Desired active config was set, it is different than the config currently in use, however
1091 // allowed configs might have change by the time we process the refresh.
1092 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001093 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001094 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001095 return;
Ady Abraham838de062019-02-04 10:24:03 -08001096 }
Alec Mouri7f015182019-07-11 13:56:22 -07001097
Ady Abraham27cbed72020-04-10 12:56:59 -07001098 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001099 const auto displayId = display->getId();
1100 LOG_ALWAYS_FATAL_IF(!displayId);
1101
Ady Abrahamabc27602020-04-08 17:20:29 -07001102 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001103
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001104 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001105 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001106 constraints.desiredTimeNanos = systemTime();
1107 constraints.seamlessRequired = false;
1108
Peiyong Line9d809e2020-04-14 13:10:48 -07001109 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001110 auto status =
1111 getHwComposer().setActiveConfigWithConstraints(*displayId,
1112 mUpcomingActiveConfig.configId.value(),
1113 constraints, &outTimeline);
1114 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001115 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1116 // to be sent. We just log the error in this case.
1117 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001118 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001119 }
1120
1121 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1122 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001123 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001124}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1127 Vector<ColorMode>* outColorModes) {
1128 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001129 return BAD_VALUE;
1130 }
1131
Peiyong Lina52f0292018-03-14 17:26:31 -07001132 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001133 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001134 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001135 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1136
1137 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1138 if (!displayId) {
1139 return NAME_NOT_FOUND;
1140 }
1141
Dominik Laskowski075d3172018-05-24 15:50:06 -07001142 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001143 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001144 }
Michael Wright28f24d02016-07-12 13:30:53 -07001145 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001146
1147 // If it's built-in display and the configuration claims it's not wide color capable,
1148 // filter out all wide color modes. The typical reason why this happens is that the
1149 // hardware is not good enough to support GPU composition of wide color, and thus the
1150 // OEMs choose to disable this capability.
1151 if (isInternalDisplay && !hasWideColorDisplay) {
1152 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1153 isWideColorMode);
1154 } else {
1155 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1156 }
Michael Wright28f24d02016-07-12 13:30:53 -07001157
1158 return NO_ERROR;
1159}
1160
Daniel Solomon42d04562019-01-20 21:03:19 -08001161status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1162 ui::DisplayPrimaries &primaries) {
1163 if (!displayToken) {
1164 return BAD_VALUE;
1165 }
1166
1167 // Currently we only support this API for a single internal display.
1168 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001169 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001170 }
1171
1172 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1173 return NO_ERROR;
1174}
1175
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001176ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001177 Mutex::Autolock lock(mStateLock);
1178
1179 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001180 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001181 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001182 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001183}
1184
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001185status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001186 schedule([=]() MAIN_THREAD {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001187 Vector<ColorMode> modes;
1188 getDisplayColorModes(displayToken, &modes);
1189 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1190 if (mode < ColorMode::NATIVE || !exists) {
1191 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1192 decodeColorMode(mode).c_str(), mode, displayToken.get());
1193 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001194 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001195 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001196 if (!display) {
1197 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1198 decodeColorMode(mode).c_str(), mode, displayToken.get());
1199 } else if (display->isVirtual()) {
1200 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1201 decodeColorMode(mode).c_str(), mode);
1202 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001203 display->getCompositionDisplay()->setColorProfile(
1204 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1205 RenderIntent::COLORIMETRIC,
1206 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001207 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001208 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001209
Michael Wright28f24d02016-07-12 13:30:53 -07001210 return NO_ERROR;
1211}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001212
Galia Peycheva5492cb52019-10-30 14:13:16 +01001213status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1214 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001215 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001216 return BAD_VALUE;
1217 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001218
1219 Mutex::Autolock lock(mStateLock);
1220
Galia Peycheva5492cb52019-10-30 14:13:16 +01001221 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1222 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001223 return NAME_NOT_FOUND;
1224 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001225 *outSupport =
1226 getHwComposer().hasDisplayCapability(*displayId,
1227 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001228 return NO_ERROR;
1229}
1230
1231void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001232 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001233 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1234 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1235 } else {
1236 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1237 }
1238 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001239}
1240
1241status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1242 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001243 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001244 return BAD_VALUE;
1245 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001246
1247 Mutex::Autolock lock(mStateLock);
1248
Galia Peycheva5492cb52019-10-30 14:13:16 +01001249 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1250 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001251 return NAME_NOT_FOUND;
1252 }
1253
Peiyong Line9d809e2020-04-14 13:10:48 -07001254 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001255 getHwComposer().getSupportedContentTypes(*displayId, &types);
1256
1257 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001258 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001259 return NO_ERROR;
1260}
1261
1262void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001263 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001264 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001265 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001266 getHwComposer().setContentType(*displayId, type);
1267 } else {
1268 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1269 }
1270 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001271}
1272
Svetoslavd85084b2014-03-20 10:28:31 -07001273status_t SurfaceFlinger::clearAnimationFrameStats() {
1274 Mutex::Autolock _l(mStateLock);
1275 mAnimFrameTracker.clearStats();
1276 return NO_ERROR;
1277}
1278
1279status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1280 Mutex::Autolock _l(mStateLock);
1281 mAnimFrameTracker.getStats(outStats);
1282 return NO_ERROR;
1283}
1284
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001285status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1286 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001287 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001288
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001289 const auto display = getDisplayDeviceLocked(displayToken);
1290 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001291 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1292 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001293 }
1294
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001295 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001296 // meaning the luminance information is already queried from
1297 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001298 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001299 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1300 capabilities.getDesiredMaxLuminance(),
1301 capabilities.getDesiredMaxAverageLuminance(),
1302 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001303
1304 return NO_ERROR;
1305}
1306
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001307std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1308 const DisplayDevice& display) const {
1309 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1310 // avoid repetitive HAL IPC and EDID parsing.
1311 const auto displayId = display.getId();
1312 LOG_FATAL_IF(!displayId);
1313
1314 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1315 LOG_FATAL_IF(!hwcDisplayId);
1316
1317 uint8_t port;
1318 DisplayIdentificationData data;
1319 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1320 ALOGV("%s: No identification data.", __FUNCTION__);
1321 return {};
1322 }
1323
1324 const auto info = parseDisplayIdentificationData(port, data);
1325 if (!info) {
1326 return {};
1327 }
1328 return info->deviceProductInfo;
1329}
1330
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001331status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1332 ui::PixelFormat* outFormat,
1333 ui::Dataspace* outDataspace,
1334 uint8_t* outComponentMask) const {
1335 if (!outFormat || !outDataspace || !outComponentMask) {
1336 return BAD_VALUE;
1337 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001338
1339 Mutex::Autolock lock(mStateLock);
1340
1341 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1342 if (!displayId) {
1343 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001344 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001345
1346 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001347 outDataspace, outComponentMask);
1348}
1349
Kevin DuBois74e53772018-11-19 10:52:38 -08001350status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1351 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001352 uint64_t maxFrames) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001353 return schedule([=]() MAIN_THREAD -> status_t {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001354 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1355 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1356 componentMask,
1357 maxFrames);
1358 } else {
1359 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1360 return NAME_NOT_FOUND;
1361 }
1362 })
1363 .get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001364}
1365
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001366status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1367 uint64_t maxFrames, uint64_t timestamp,
1368 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001369 Mutex::Autolock lock(mStateLock);
1370
1371 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1372 if (!displayId) {
1373 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001374 }
1375
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001376 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001377}
1378
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001379status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1380 if (!outSupported) {
1381 return BAD_VALUE;
1382 }
1383 *outSupported = getRenderEngine().supportsProtectedContent();
1384 return NO_ERROR;
1385}
1386
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001387status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1388 bool* outIsWideColorDisplay) const {
1389 if (!displayToken || !outIsWideColorDisplay) {
1390 return BAD_VALUE;
1391 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001392
1393 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001394 const auto display = getDisplayDeviceLocked(displayToken);
1395 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001396 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001397 }
Peiyong Linff84a152019-05-17 18:36:19 -07001398
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001399 *outIsWideColorDisplay =
1400 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001401 return NO_ERROR;
1402}
1403
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001404status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001405 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001406 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001407
Dominik Laskowski6505f792019-09-18 11:10:05 -07001408 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1409 mEventQueue->setEventConnection(
1410 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001411 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001412 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001413
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001414 return NO_ERROR;
1415}
1416
1417status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001418 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001419 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001420}
1421
Vishnu Nair43bccf82020-06-05 10:53:37 -07001422status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001423 outLayers->clear();
Vishnu Nair43bccf82020-06-05 10:53:37 -07001424 schedule([=] {
1425 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
1426 mDrawingState.traverseInZOrder([&](Layer* layer) {
1427 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1428 });
1429 }).wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001430 return NO_ERROR;
1431}
1432
Peiyong Linc6780972018-10-28 15:24:08 -07001433status_t SurfaceFlinger::getCompositionPreference(
1434 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1435 Dataspace* outWideColorGamutDataspace,
1436 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001437 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001438 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001439 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001440 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001441 return NO_ERROR;
1442}
1443
Dan Stozaec460082018-12-17 15:35:09 -08001444status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1445 const sp<IBinder>& stopLayerHandle,
1446 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001447 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001448 return BAD_VALUE;
1449 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001450
1451 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1452 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001453 return NO_ERROR;
1454}
1455
Dan Stozaec460082018-12-17 15:35:09 -08001456status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001457 if (!listener) {
1458 return BAD_VALUE;
1459 }
Dan Stozaec460082018-12-17 15:35:09 -08001460 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001461 return NO_ERROR;
1462}
Dan Gittik57e63c52019-01-18 16:37:54 +00001463
1464status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1465 bool* outSupport) const {
1466 if (!displayToken || !outSupport) {
1467 return BAD_VALUE;
1468 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001469
1470 Mutex::Autolock lock(mStateLock);
1471
Dan Gittik57e63c52019-01-18 16:37:54 +00001472 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1473 if (!displayId) {
1474 return NAME_NOT_FOUND;
1475 }
1476 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001477 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001478 return NO_ERROR;
1479}
1480
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001481status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001482 if (!displayToken) {
1483 return BAD_VALUE;
1484 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001485
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001486 return promise::chain(schedule([=]() MAIN_THREAD {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001487 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1488 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1489 } else {
1490 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001491 return promise::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001492 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001493 }))
1494 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001495 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001496}
1497
Ady Abraham8532d012019-05-08 14:50:56 -07001498status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1499 PowerHint powerHint = static_cast<PowerHint>(hintId);
1500
1501 if (powerHint == PowerHint::INTERACTION) {
1502 mScheduler->notifyTouchEvent();
1503 }
1504
1505 return NO_ERROR;
1506}
1507
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001508// ----------------------------------------------------------------------------
1509
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001510sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001511 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001512 const auto& handle =
1513 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001514
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001515 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001516}
1517
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001518void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001519 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001520 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001521 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001522}
1523
1524void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001525 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001526 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001527 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001528}
1529
1530void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001531 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001532 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001533}
1534
Ady Abrahamf69d11d2020-07-24 11:09:55 -07001535nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001536 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001537 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1538 return 0;
1539 }
1540
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001541 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001542}
1543
Peiyong Line9d809e2020-04-14 13:10:48 -07001544void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001545 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001546 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001547 ATRACE_NAME("SF onVsync");
1548
Steven Thomas3cfac282017-02-06 12:29:30 -08001549 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001551 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001552 return;
1553 }
1554
Dominik Laskowski075d3172018-05-24 15:50:06 -07001555 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001556 return;
1557 }
1558
Dominik Laskowski075d3172018-05-24 15:50:06 -07001559 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001560 // For now, we don't do anything with external display vsyncs.
1561 return;
1562 }
1563
Alec Mourif8e689c2019-05-20 18:32:22 -07001564 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001565 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001566 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001567 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001568 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001569}
1570
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001571void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001572 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1573 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001574}
1575
Ady Abraham2139f732019-11-13 18:56:40 -08001576bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001577 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001578}
1579
Ady Abraham2139f732019-11-13 18:56:40 -08001580void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1581 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001582 const auto display = getDefaultDisplayDeviceLocked();
1583 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001584 return;
1585 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001586 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001587
Ana Krulec7d1d6832018-12-27 11:10:09 -08001588 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001589 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001590 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001591 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001592 return;
1593 }
1594
Ady Abrahamabc27602020-04-08 17:20:29 -07001595 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001596}
1597
Peiyong Line9d809e2020-04-14 13:10:48 -07001598void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001599 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001600 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001601 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001602
Lloyd Piqueba04e622017-12-14 17:11:26 -08001603 // Ignore events that do not have the right sequenceId.
1604 if (sequenceId != getBE().mComposerSequenceId) {
1605 return;
1606 }
1607
Steven Thomasb02664d2017-07-26 18:48:28 -07001608 // Only lock if we're not on the main thread. This function is normally
1609 // called on a hwbinder thread, but for the primary display it's called on
1610 // the main thread with the state lock already held, so don't attempt to
1611 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001612 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001613
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001614 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001615
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001616 if (std::this_thread::get_id() == mMainThreadId) {
1617 // Process all pending hot plug events immediately if we are on the main thread.
1618 processDisplayHotplugEventsLocked();
1619 }
1620
Lloyd Piqueba04e622017-12-14 17:11:26 -08001621 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001622}
1623
Ady Abraham7159f572019-10-11 11:10:18 -07001624void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001625 int32_t sequenceId, hal::HWDisplayId /*display*/,
1626 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001627 Mutex::Autolock lock(mStateLock);
1628 if (sequenceId != getBE().mComposerSequenceId) {
1629 return;
1630 }
1631 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001632}
1633
Peiyong Line9d809e2020-04-14 13:10:48 -07001634void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001635 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1636 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1637}
1638
Peiyong Line9d809e2020-04-14 13:10:48 -07001639void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001640 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001641 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001642 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001643 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001644 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001645}
1646
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001647void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001648 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001649
1650 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1651 // display power state.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001652 static_cast<void>(schedule([=]() MAIN_THREAD { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001653}
1654
1655void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1656 ATRACE_CALL();
1657
Peiyong Line9d809e2020-04-14 13:10:48 -07001658 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001659
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001660 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001661 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1662 if (display && display->isPoweredOn()) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02001663 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001664 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001665 }
Mathias Agopian86303202012-07-24 22:46:10 -07001666}
1667
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001668sp<Fence> SurfaceFlinger::previousFrameFence() {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001669 // We are storing the last 2 present fences. If sf's phase offset is to be
1670 // woken up before the actual vsync but targeting the next vsync, we need to check
1671 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001672 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1673 : mPreviousPresentFences[1];
1674}
1675
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001676bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001677 ATRACE_CALL();
1678 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001679
Ady Abraham11579302019-09-19 12:35:58 -07001680 if (fence == Fence::NO_FENCE) {
1681 return false;
1682 }
1683
Dan Stoza59083052020-04-28 10:13:20 -07001684 const status_t status = fence->wait(graceTimeMs);
1685 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1686 // which calls wait(0) again internally
1687 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001688}
1689
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001690nsecs_t SurfaceFlinger::previousFramePresentTime() {
Alec Mouri6d414b52020-03-17 11:18:05 -07001691 const sp<Fence>& fence = previousFrameFence();
1692
1693 if (fence == Fence::NO_FENCE) {
1694 return Fence::SIGNAL_TIME_INVALID;
1695 }
1696
1697 return fence->getSignalTime();
1698}
1699
Ady Abraham5facfb12020-04-22 15:18:31 -07001700nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001701 DisplayStatInfo stats;
1702 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001703 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001704 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001705 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001706}
1707
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001708void SurfaceFlinger::onMessageReceived(int32_t what, nsecs_t expectedVSyncTime) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001709 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001710 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001711 case MessageQueue::INVALIDATE: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001712 onMessageInvalidate(expectedVSyncTime);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001713 break;
1714 }
1715 case MessageQueue::REFRESH: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001716 onMessageRefresh();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001717 break;
1718 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001719 }
1720}
1721
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001722void SurfaceFlinger::onMessageInvalidate(nsecs_t expectedVSyncTime) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001723 ATRACE_CALL();
1724
1725 const nsecs_t frameStart = systemTime();
1726 // calculate the expected present time once and use the cached
1727 // value throughout this frame to make sure all layers are
1728 // seeing this same value.
1729 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
1730 mExpectedPresentTime = expectedVSyncTime;
1731
1732 // When Backpressure propagation is enabled we want to give a small grace period
1733 // for the present fence to fire instead of just giving up on this frame to handle cases
1734 // where present fence is just about to get signaled.
1735 const int graceTimeForPresentFenceMs =
1736 (mPropagateBackpressure &&
1737 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1738 ? 1
1739 : 0;
1740
1741 // Pending frames may trigger backpressure propagation.
1742 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1743 previousFramePending(graceTimeForPresentFenceMs)};
1744
1745 // Frame missed counts for metrics tracking.
1746 // A frame is missed if the prior frame is still pending. If no longer pending,
1747 // then we still count the frame as missed if the predicted present time
1748 // was further in the past than when the fence actually fired.
1749
1750 // Add some slop to correct for drift. This should generally be
1751 // smaller than a typical frame duration, but should not be so small
1752 // that it reports reasonable drift as a missed frame.
1753 DisplayStatInfo stats;
1754 mScheduler->getDisplayStatInfo(&stats);
1755 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1756 const nsecs_t previousPresentTime = previousFramePresentTime();
1757 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
1758 framePending ||
1759 (previousPresentTime >= 0 &&
1760 (lastExpectedPresentTime <
1761 previousPresentTime - frameMissedSlop))};
1762 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
1763 mHadDeviceComposition && frameMissed};
1764 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
1765 mHadClientComposition && frameMissed};
1766
1767 if (frameMissed) {
1768 mFrameMissedCount++;
1769 mTimeStats->incrementMissedFrames();
1770 if (mMissedFrameJankCount == 0) {
1771 mMissedFrameJankStart = systemTime();
1772 }
1773 mMissedFrameJankCount++;
1774 }
1775
1776 if (hwcFrameMissed) {
1777 mHwcFrameMissedCount++;
1778 }
1779
1780 if (gpuFrameMissed) {
1781 mGpuFrameMissedCount++;
1782 }
1783
1784 // If we are in the middle of a config change and the fence hasn't
1785 // fired yet just wait for the next invalidate
1786 if (mSetActiveConfigPending) {
1787 if (framePending) {
1788 mEventQueue->invalidate();
1789 return;
1790 }
1791
1792 // We received the present fence from the HWC, so we assume it successfully updated
1793 // the config, hence we update SF.
1794 mSetActiveConfigPending = false;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001795 ON_MAIN_THREAD(setActiveConfigInternal());
Dan Stoza28d46a52020-04-28 09:54:54 -07001796 }
1797
1798 if (framePending && mPropagateBackpressure) {
1799 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
1800 signalLayerUpdate();
1801 return;
1802 }
1803 }
1804
1805 // Our jank window is always at least 100ms since we missed a
1806 // frame...
1807 static constexpr nsecs_t kMinJankyDuration =
1808 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1809 // ...but if it's larger than 1s then we missed the trace cutoff.
1810 static constexpr nsecs_t kMaxJankyDuration =
1811 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001812 nsecs_t jankDurationToUpload = -1;
Dan Stoza28d46a52020-04-28 09:54:54 -07001813 // If we're in a user build then don't push any atoms
1814 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001815 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dan Stoza28d46a52020-04-28 09:54:54 -07001816 // Only report jank when the display is on, as displays in DOZE
1817 // power mode may operate at a different frame rate than is
1818 // reported in their config, which causes noticeable (but less
1819 // severe) jank.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001820 if (display && display->getPowerMode() == hal::PowerMode::ON) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001821 const nsecs_t currentTime = systemTime();
1822 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1823 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001824 jankDurationToUpload = jankDuration;
Dan Stoza28d46a52020-04-28 09:54:54 -07001825 }
1826
1827 // We either reported a jank event or we missed the trace
1828 // window, so clear counters here.
1829 if (jankDuration > kMinJankyDuration) {
1830 mMissedFrameJankCount = 0;
1831 mMissedFrameJankStart = 0;
1832 }
1833 }
1834 }
1835
Dan Stoza28d46a52020-04-28 09:54:54 -07001836 if (mTracingEnabledChanged) {
1837 mTracingEnabled = mTracing.isEnabled();
1838 mTracingEnabledChanged = false;
1839 }
1840
1841 bool refreshNeeded;
1842 {
1843 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1844
1845 refreshNeeded = handleMessageTransaction();
1846 refreshNeeded |= handleMessageInvalidate();
1847 if (mTracingEnabled) {
1848 mAddCompositionStateToTrace =
1849 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1850 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1851 mTracing.notifyLocked("visibleRegionsDirty");
1852 }
1853 }
1854 }
1855
1856 // Layers need to get updated (in the previous line) before we can use them for
1857 // choosing the refresh rate.
1858 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1859 // and may eventually call to ~Layer() if it holds the last reference
1860 {
1861 Mutex::Autolock _l(mStateLock);
1862 mScheduler->chooseRefreshRateForContent();
1863 }
1864
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001865 ON_MAIN_THREAD(performSetActiveConfig());
Dan Stoza28d46a52020-04-28 09:54:54 -07001866
1867 updateCursorAsync();
1868 updateInputFlinger();
1869
1870 refreshNeeded |= mRepaintEverything;
1871 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001872 mLastJankDuration = jankDurationToUpload;
Dan Stoza28d46a52020-04-28 09:54:54 -07001873 // Signal a refresh if a transaction modified the window state,
1874 // a new buffer was latched, or if HWC has requested a full
1875 // repaint
1876 if (mFrameStartTime <= 0) {
1877 // We should only use the time of the first invalidate
1878 // message that signals a refresh as the beginning of the
1879 // frame. Otherwise the real frame time will be
1880 // underestimated.
1881 mFrameStartTime = frameStart;
1882 }
1883 signalRefresh();
1884 }
1885}
1886
Dan Stoza6b9454d2014-11-07 16:00:59 -08001887bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001888 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001889 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001890
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001891 bool flushedATransaction = flushTransactionQueues();
1892
Valerie Hau47826a72020-06-15 12:34:40 -07001893 bool runHandleTransaction =
1894 (transactionFlags && (transactionFlags != eTransactionFlushNeeded)) ||
Robert Carr6417d2e2020-06-24 15:26:32 -07001895 flushedATransaction ||
1896 mForceTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001897
1898 if (runHandleTransaction) {
1899 handleTransaction(eTransactionMask);
1900 } else {
1901 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001902 }
1903
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001904 if (transactionFlushNeeded()) {
1905 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001906 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001907
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001908 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001909}
1910
Dan Stoza28d46a52020-04-28 09:54:54 -07001911void SurfaceFlinger::onMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001912 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001913
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001914 mRefreshPending = false;
1915
Lloyd Piqueab039b52019-02-13 14:22:42 -08001916 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001917 const auto& displays = ON_MAIN_THREAD(mDisplays);
1918 refreshArgs.outputs.reserve(displays.size());
1919 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08001920 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1921 }
1922 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001923 if (auto layerFE = layer->getCompositionEngineLayerFE())
1924 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001925 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001926 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1927 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001928 if (auto layerFE = layer->getCompositionEngineLayerFE())
1929 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001930 }
1931
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001932 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001933 refreshArgs.outputColorSetting = useColorManagement
1934 ? mDisplayColorSetting
1935 : compositionengine::OutputColorSetting::kUnmanaged;
1936 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1937 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001938
1939 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1940 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001941 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02001942 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001943
1944 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1945 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1946 mDrawingState.colorMatrixChanged = false;
1947 }
1948
1949 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1950
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001951 if (mDebugRegion != 0) {
1952 refreshArgs.devOptFlashDirtyRegionsDelay =
1953 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1954 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001955
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001956 mGeometryInvalid = false;
1957
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001958 // Store the present time just before calling to the composition engine so we could notify
1959 // the scheduler.
1960 const auto presentTime = systemTime();
1961
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001962 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001963 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1964 // Reset the frame start time now that we've recorded this frame.
1965 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001966
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001967 mScheduler->onDisplayRefreshed(presentTime);
1968
David Sodmanfa9b2af2017-12-24 13:28:59 -08001969 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001970 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001971
Alec Mouri8f7a0102020-04-15 12:11:10 -07001972 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
1973
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001974 mHadClientComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
1975 const auto& state = pair.second->getCompositionDisplay()->getState();
1976 return state.usesClientComposition && !state.reusedClientComposition;
1977 });
1978 mHadDeviceComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
1979 const auto& state = pair.second->getCompositionDisplay()->getState();
1980 return state.usesDeviceComposition;
1981 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001982 mReusedClientComposition =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001983 std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
1984 const auto& state = pair.second->getCompositionDisplay()->getState();
1985 return state.reusedClientComposition;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001986 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001987
Alec Mouri8f7a0102020-04-15 12:11:10 -07001988 // Only report a strategy change if we move in and out of composition with hw overlays
1989 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
1990 mTimeStats->incrementCompositionStrategyChanges();
1991 }
1992
Yichi Chen28dee2c2020-07-06 21:24:14 +08001993 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
1994 mVSyncModulator->onRefreshed(mHadClientComposition || mReusedClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001995
David Sodman7e4ae112018-02-09 15:02:28 -08001996 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001997 if (mVisibleRegionsDirty) {
1998 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07001999 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002000 mTracing.notify("visibleRegionsDirty");
2001 }
2002 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002003
2004 if (mCompositionEngine->needsAnotherUpdate()) {
2005 signalLayerUpdate();
2006 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002008
David Sodmanfa9b2af2017-12-24 13:28:59 -08002009bool SurfaceFlinger::handleMessageInvalidate() {
2010 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002011 bool refreshNeeded = handlePageFlip();
2012
Vishnu Nair4351ad52019-02-11 14:13:02 -08002013 if (mVisibleRegionsDirty) {
2014 computeLayerBounds();
2015 }
2016
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002017 for (auto& layer : mLayersPendingRefresh) {
2018 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002019 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002020 invalidateLayerStack(layer, visibleReg);
2021 }
2022 mLayersPendingRefresh.clear();
2023 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002024}
2025
Ana Krulece588e312018-09-18 12:32:24 -07002026void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2027 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002028 // Update queue of past composite+present times and determine the
2029 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002030 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002031 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002032 while (!getBE().mCompositePresentTimes.empty()) {
2033 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002034 // Cached values should have been updated before calling this method,
2035 // which helps avoid duplicate syscalls.
2036 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2037 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2038 break;
2039 }
2040 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002041 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002042 }
2043
2044 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002045 while (getBE().mCompositePresentTimes.size() > 16) {
2046 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002047 }
2048
Ana Krulece588e312018-09-18 12:32:24 -07002049 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002050}
2051
Ana Krulece588e312018-09-18 12:32:24 -07002052void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2053 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002054 // Integer division and modulo round toward 0 not -inf, so we need to
2055 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002056 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2057 ? (stats.vsyncPeriod -
2058 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2059 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002060
Ady Abraham9e16a482019-12-03 17:19:41 -08002061 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002062 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002063 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002064 }
2065
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002066 // Snap the latency to a value that removes scheduling jitter from the
2067 // composition and present times, which often have >1ms of jitter.
2068 // Reducing jitter is important if an app attempts to extrapolate
2069 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002070 // Snapping also allows an app to precisely calculate
2071 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002072 nsecs_t bias = stats.vsyncPeriod / 2;
2073 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2074 nsecs_t snappedCompositeToPresentLatency =
2075 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002076
David Sodman99974d22017-11-28 12:04:33 -08002077 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002078 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2079 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002080 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002081}
2082
David Sodman2b406362017-12-15 13:33:47 -08002083void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002084{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002085 ATRACE_CALL();
2086 ALOGV("postComposition");
2087
Brian Andersonf6386862016-10-31 16:34:13 -07002088 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002089 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002090 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002091 }
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002092
2093 const auto* display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002094
David Sodman73beded2017-11-15 11:56:06 -08002095 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002096 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002097 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002098 glCompositionDoneFenceTime =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002099 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002100 ->getRenderSurface()
2101 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002102 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002103 } else {
2104 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2105 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002106
David Sodman73beded2017-11-15 11:56:06 -08002107 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002108 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002109 mPreviousPresentFences[0] =
2110 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Ady Abrahambe0f9482019-04-24 15:41:53 -07002111 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002112 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002113
Ana Krulece588e312018-09-18 12:32:24 -07002114 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002115 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002116
Lloyd Piqueab039b52019-02-13 14:22:42 -08002117 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2118 // be sampled a little later than when we started doing work for this frame,
2119 // but that should be okay since updateCompositorTiming has snapping logic.
2120 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2121 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002122 CompositorTiming compositorTiming;
2123 {
David Sodman99974d22017-11-28 12:04:33 -08002124 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2125 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002126 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002127
Edgar Arriaga844fa672020-01-16 14:21:42 -08002128 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002129 const bool frameLatched = layer->onPostComposition(display, glCompositionDoneFenceTime,
2130 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002131 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002132 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002133 }
Robert Carr2047fae2016-11-28 14:09:09 -08002134 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002135
Valerie Hau4b678442020-04-14 10:50:42 -07002136 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2137 mTransactionCompletedThread.sendCallbacks();
2138
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002139 if (display && display->isPrimary() && display->getPowerMode() == hal::PowerMode::ON &&
2140 presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002141 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002142 }
2143
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002144 const bool isDisplayConnected = display && getHwComposer().isConnected(*display->getId());
2145
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002146 if (!hasSyncFramework) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002147 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002148 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002149 }
2150 }
2151
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002152 if (mAnimCompositionPending) {
2153 mAnimCompositionPending = false;
2154
Brian Anderson4e606e32017-03-16 15:34:57 -07002155 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002156 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002157 std::move(presentFenceTime));
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002158 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002159 // The HWC doesn't support present fences, so use the refresh
2160 // timestamp instead.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002161 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002162 mAnimFrameTracker.setActualPresentTime(presentTime);
2163 }
2164 mAnimFrameTracker.advanceFrame();
2165 }
Dan Stozab90cf072015-03-05 11:05:59 -08002166
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002167 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002168 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002169 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002170 }
2171
Vishnu Nair9b079a22020-01-21 14:36:08 -08002172 if (mReusedClientComposition) {
2173 mTimeStats->incrementClientCompositionReusedFrames();
2174 }
2175
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002176 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002177
Alec Mouri717bcb62020-02-10 17:07:19 -08002178 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2179 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2180 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2181
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002182 if (mLastJankDuration > 0) {
2183 ATRACE_NAME("Jank detected");
2184 const int32_t jankyDurationMillis = mLastJankDuration / (1000 * 1000);
2185 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED, jankyDurationMillis,
2186 mMissedFrameJankCount);
2187 mLastJankDuration = -1;
2188 }
2189
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002190 if (isDisplayConnected && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002191 return;
2192 }
2193
2194 nsecs_t currentTime = systemTime();
2195 if (mHasPoweredOff) {
2196 mHasPoweredOff = false;
2197 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002198 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002199 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002200 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2201 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002202 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002203 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002204 }
David Sodman4a36e932017-11-07 14:29:47 -08002205 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002206 }
David Sodman4a36e932017-11-07 14:29:47 -08002207 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002208
Alec Mouri4dde1782019-09-30 17:27:13 -07002209 // Cleanup any outstanding resources due to rendering a prior frame.
2210 getRenderEngine().cleanupPostRender();
2211
Dan Stoza436ccf32018-06-21 12:10:12 -07002212 {
2213 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002214 if (mTexturePool.size() < mTexturePoolSize) {
2215 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002216 const size_t offset = mTexturePool.size();
2217 mTexturePool.resize(mTexturePoolSize);
2218 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2219 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002220 } else if (mTexturePool.size() > mTexturePoolSize) {
2221 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2222 const size_t offset = mTexturePoolSize;
2223 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2224 mTexturePool.resize(mTexturePoolSize);
2225 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002226 }
2227 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002228
Kevin DuBois413287f2019-02-25 08:46:47 -08002229 if (mLumaSampling && mRegionSamplingThread) {
2230 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002231 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002232
2233 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2234 // side-effect of getTotalSize(), so we check that again here
2235 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002236 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002237 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2238 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002239}
2240
Lloyd Pique7eebe692020-04-22 22:40:06 -07002241FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2242 return displayDevice.getViewport().toFloatRect();
2243}
2244
Vishnu Nair4351ad52019-02-11 14:13:02 -08002245void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002246 for (const auto& pair : ON_MAIN_THREAD(mDisplays)) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08002247 const auto& displayDevice = pair.second;
2248 const auto display = displayDevice->getCompositionDisplay();
2249 for (const auto& layer : mDrawingState.layersSortedByZ) {
2250 // only consider the layers on the given layer stack
2251 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002252 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002253 }
2254
Lloyd Pique7eebe692020-04-22 22:40:06 -07002255 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002256 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002257 }
2258 }
2259}
2260
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002261void SurfaceFlinger::postFrame() {
2262 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002263 if (display && getHwComposer().isConnected(*display->getId())) {
2264 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002265 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2266 logFrameStats();
2267 }
2268 }
2269}
2270
Mathias Agopian87baae12012-07-31 12:38:26 -07002271void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002272{
Mathias Agopian841cde52012-03-01 15:44:37 -08002273 ATRACE_CALL();
2274
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002275 // here we keep a copy of the drawing state (that is the state that's
2276 // going to be overwritten by handleTransactionLocked()) outside of
2277 // mStateLock so that the side-effects of the State assignment
2278 // don't happen with mStateLock held (which can cause deadlocks).
2279 State drawingState(mDrawingState);
2280
Mathias Agopianca4d3602011-05-19 15:38:14 -07002281 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002282 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002283
Mathias Agopianca4d3602011-05-19 15:38:14 -07002284 // Here we're guaranteed that some transaction flags are set
2285 // so we can call handleTransactionLocked() unconditionally.
2286 // We call getTransactionFlags(), which will also clear the flags,
2287 // with mStateLock held to guarantee that mCurrentState won't change
2288 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002289
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002290 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002291 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002292 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002293
Mathias Agopianca4d3602011-05-19 15:38:14 -07002294 mDebugInTransaction = 0;
2295 invalidateHwcGeometry();
2296 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002297}
2298
Lloyd Piqueba04e622017-12-14 17:11:26 -08002299void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2300 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002301 const std::optional<DisplayIdentificationInfo> info =
2302 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002303
Dominik Laskowski075d3172018-05-24 15:50:06 -07002304 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002305 continue;
2306 }
2307
Dominik Laskowski55c85402020-01-21 16:25:47 -08002308 const DisplayId displayId = info->id;
2309 const auto it = mPhysicalDisplayTokens.find(displayId);
2310
Peiyong Line9d809e2020-04-14 13:10:48 -07002311 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002312 if (it == mPhysicalDisplayTokens.end()) {
2313 ALOGV("Creating display %s", to_string(displayId).c_str());
2314
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002315 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002316 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002317 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002318
Dominik Laskowski075d3172018-05-24 15:50:06 -07002319 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002320 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2321 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002322 state.isSecure = true; // All physical displays are currently considered secure.
2323 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002324
2325 sp<IBinder> token = new BBinder();
2326 mCurrentState.displays.add(token, state);
2327 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2328
Dominik Laskowski075d3172018-05-24 15:50:06 -07002329 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002330 } else {
2331 ALOGV("Recreating display %s", to_string(displayId).c_str());
2332
2333 const auto token = it->second;
2334 auto& state = mCurrentState.displays.editValueFor(token);
2335 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002336 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002337 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002338 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002339
Dominik Laskowski55c85402020-01-21 16:25:47 -08002340 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002341 if (index >= 0) {
2342 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2343 mInterceptor->saveDisplayDeletion(state.sequenceId);
2344 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002345 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002346 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002347 }
2348
2349 processDisplayChangesLocked();
2350 }
2351
2352 mPendingHotplugEvents.clear();
2353}
2354
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002355void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002356 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2357 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002358}
2359
Lloyd Pique99d3da52018-01-22 17:48:03 -08002360sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002361 const wp<IBinder>& displayToken,
2362 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002363 const DisplayDeviceState& state,
2364 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002365 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002366 auto displayId = compositionDisplay->getDisplayId();
2367 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002368 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002369 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002370 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002371 creationArgs.hasWideColorGamut = false;
2372 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002373
Dominik Laskowski55c85402020-01-21 16:25:47 -08002374 if (const auto& physical = state.physical) {
2375 creationArgs.connectionType = physical->type;
2376 }
2377
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002378 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002379 creationArgs.isPrimary = isInternalDisplay;
2380
2381 if (useColorManagement && displayId) {
2382 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002383 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002384 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002385 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002386 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002387
Dominik Laskowski7e045462018-05-30 13:02:02 -07002388 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002389 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002390 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002391 }
tangrobin6753a022018-08-10 10:58:54 +08002392 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393
Dominik Laskowski075d3172018-05-24 15:50:06 -07002394 if (displayId) {
2395 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002396 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002397 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002398 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002399
Lloyd Pique90c115d2018-09-18 21:39:42 -07002400 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002401 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002402 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002403
Lloyd Pique99d3da52018-01-22 17:48:03 -08002404 // Make sure that composition can never be stalled by a virtual display
2405 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002406 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002407 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002408 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2409 }
2410
Dominik Laskowski718f9602019-11-09 20:01:35 -08002411 creationArgs.physicalOrientation =
2412 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002413
Lloyd Pique99d3da52018-01-22 17:48:03 -08002414 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002415 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002416
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002417 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002418
2419 if (maxFrameBufferAcquiredBuffers >= 3) {
2420 nativeWindowSurface->preallocateBuffers();
2421 }
2422
2423 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002424 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002425 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002426 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002427 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002428 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002429 display->getCompositionDisplay()->setColorProfile(
2430 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2431 RenderIntent::COLORIMETRIC,
2432 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 if (!state.isVirtual()) {
2434 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002435 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2436 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002437 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002438
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002439 display->setLayerStack(state.layerStack);
2440 display->setProjection(state.orientation, state.viewport, state.frame);
2441 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002442
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002443 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002444}
2445
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002446void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2447 const DisplayDeviceState& state) {
2448 int width = 0;
2449 int height = 0;
2450 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2451 if (state.physical) {
2452 const auto& activeConfig =
2453 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2454 width = activeConfig->getWidth();
2455 height = activeConfig->getHeight();
2456 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2457 } else if (state.surface != nullptr) {
2458 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2459 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2460 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2461 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2462 int intPixelFormat;
2463 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2464 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2465 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2466 } else {
2467 // Virtual displays without a surface are dormant:
2468 // they have external state (layer stack, projection,
2469 // etc.) but no internal state (i.e. a DisplayDevice).
2470 return;
2471 }
2472
2473 compositionengine::DisplayCreationArgsBuilder builder;
2474 if (const auto& physical = state.physical) {
2475 builder.setPhysical({physical->id, physical->type});
2476 }
2477 builder.setPixels(ui::Size(width, height));
2478 builder.setPixelFormat(pixelFormat);
2479 builder.setIsSecure(state.isSecure);
2480 builder.setLayerStackId(state.layerStack);
2481 builder.setPowerAdvisor(&mPowerAdvisor);
Alec Mouri64f03f52020-09-09 18:57:07 -07002482 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002483 builder.setName(state.displayName);
2484 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2485
2486 sp<compositionengine::DisplaySurface> displaySurface;
2487 sp<IGraphicBufferProducer> producer;
2488 sp<IGraphicBufferProducer> bqProducer;
2489 sp<IGraphicBufferConsumer> bqConsumer;
2490 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2491
2492 std::optional<DisplayId> displayId = compositionDisplay->getId();
2493
2494 if (state.isVirtual()) {
2495 sp<VirtualDisplaySurface> vds =
2496 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2497 bqConsumer, state.displayName);
2498
2499 displaySurface = vds;
2500 producer = vds;
2501 } else {
2502 ALOGE_IF(state.surface != nullptr,
2503 "adding a supported display, but rendering "
2504 "surface is provided (%p), ignoring it",
2505 state.surface.get());
2506
2507 LOG_ALWAYS_FATAL_IF(!displayId);
2508 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2509 maxGraphicsWidth, maxGraphicsHeight);
2510 producer = bqProducer;
2511 }
2512
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002513 LOG_FATAL_IF(!displaySurface);
2514 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2515 displaySurface, producer);
2516 mDisplays.emplace(displayToken, display);
2517 if (!state.isVirtual()) {
2518 LOG_FATAL_IF(!displayId);
2519 dispatchDisplayHotplugEvent(displayId->value, true);
2520 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002521
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002522 if (display->isPrimary()) {
2523 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002524 }
2525}
2526
2527void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2528 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2529 // Save display ID before disconnecting.
2530 const auto displayId = display->getId();
2531 display->disconnect();
2532
2533 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002534 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002535 dispatchDisplayHotplugEvent(displayId->value, false);
2536 }
2537 }
2538
2539 mDisplays.erase(displayToken);
2540}
2541
2542void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2543 const DisplayDeviceState& currentState,
2544 const DisplayDeviceState& drawingState) {
2545 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2546 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002547 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002548 // changing the surface is like destroying and recreating the DisplayDevice
2549 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2550 display->disconnect();
2551 }
2552 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002553 if (const auto& physical = currentState.physical) {
2554 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2555 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002556 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002557 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002558 const auto display = getDisplayDeviceLocked(displayToken);
2559 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002560 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002561 return;
2562 }
2563
2564 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2565 if (currentState.layerStack != drawingState.layerStack) {
2566 display->setLayerStack(currentState.layerStack);
2567 }
2568 if ((currentState.orientation != drawingState.orientation) ||
2569 (currentState.viewport != drawingState.viewport) ||
2570 (currentState.frame != drawingState.frame)) {
2571 display->setProjection(currentState.orientation, currentState.viewport,
2572 currentState.frame);
2573 }
2574 if (currentState.width != drawingState.width ||
2575 currentState.height != drawingState.height) {
2576 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07002577
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002578 if (display->isPrimary()) {
2579 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2580 }
Dominik Laskowski20134642020-04-20 22:36:44 -07002581
2582 if (mRefreshRateOverlay) {
2583 mRefreshRateOverlay->setViewport(display->getSize());
2584 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002585 }
2586 }
2587}
2588
Lloyd Pique347200f2017-12-14 17:00:15 -08002589void SurfaceFlinger::processDisplayChangesLocked() {
2590 // here we take advantage of Vector's copy-on-write semantics to
2591 // improve performance by skipping the transaction entirely when
2592 // know that the lists are identical
2593 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2594 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2595 if (!curr.isIdenticalTo(draw)) {
2596 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002597
2598 // find the displays that were removed
2599 // (ie: in drawing state but not in current state)
2600 // also handle displays that changed
2601 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002602 for (size_t i = 0; i < draw.size(); i++) {
2603 const wp<IBinder>& displayToken = draw.keyAt(i);
2604 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002605 if (j < 0) {
2606 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002607 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002608 } else {
2609 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002610 const DisplayDeviceState& currentState = curr[j];
2611 const DisplayDeviceState& drawingState = draw[i];
2612 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002613 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002614 }
2615
2616 // find displays that were added
2617 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002618 for (size_t i = 0; i < curr.size(); i++) {
2619 const wp<IBinder>& displayToken = curr.keyAt(i);
2620 if (draw.indexOfKey(displayToken) < 0) {
2621 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002622 }
2623 }
2624 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002625
2626 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002627}
2628
Mathias Agopian87baae12012-07-31 12:38:26 -07002629void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002630{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002631 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2632
Dan Stoza7dde5992015-05-22 09:51:44 -07002633 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002634 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002635 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002636 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002637
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638 /*
2639 * Traversal of the children
2640 * (perform the transaction for each of them if needed)
2641 */
2642
Valerie Haud50e7412020-06-16 17:58:14 -07002643 if ((transactionFlags & eTraversalNeeded) || mForceTraversal) {
2644 mForceTraversal = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002645 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002647 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648
2649 const uint32_t flags = layer->doTransaction(0);
2650 if (flags & Layer::eVisibleRegion)
2651 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002652
2653 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002654 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002655 }
Robert Carr2047fae2016-11-28 14:09:09 -08002656 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657 }
2658
2659 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002660 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661 */
2662
Mathias Agopiane57f2922012-08-09 16:29:12 -07002663 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002664 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002665 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002666 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667
Vishnu Nair6213bd92020-05-08 17:42:25 -07002668 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002669 // The transform hint might have changed for some layers
2670 // (either because a display has changed, or because a layer
2671 // as changed).
2672 //
2673 // Walk through all the layers in currentLayers,
2674 // and update their transform hint.
2675 //
2676 // If a layer is visible only on a single display, then that
2677 // display is used to calculate the hint, otherwise we use the
2678 // default display.
2679 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002680 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002681 // the hint is set before we acquire a buffer from the surface texture.
2682 //
2683 // NOTE: layer transactions have taken place already, so we use their
2684 // drawing state. However, SurfaceFlinger's own transaction has not
2685 // happened yet, so we must use the current state layer list
2686 // (soon to become the drawing state list).
2687 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002688 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002689 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002690 bool first = true;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002691 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08002692 // NOTE: we rely on the fact that layers are sorted by
2693 // layerStack first (so we don't have to traverse the list
2694 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002695 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002696 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002697 currentlayerStack = layerStack;
2698 // figure out if this layerstack is mirrored
2699 // (more than one display) if so, pick the default display,
2700 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002701 hintDisplay = nullptr;
2702 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002703 if (display->getCompositionDisplay()
2704 ->belongsInOutput(layer->getLayerStack(),
2705 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002706 if (hintDisplay) {
2707 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002708 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002709 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002710 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002711 }
2712 }
2713 }
2714 }
Chet Haase91d25932013-04-11 15:24:55 -07002715
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002716 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002717 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2718 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002719
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002720 // could be null when this layer is using a layerStack
2721 // that is not visible on any display. Also can occur at
2722 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002723 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002724 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002725
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002726 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002727 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002728 if (hintDisplay) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002729 layer->updateTransformHint(hintDisplay->getTransformHint());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002730 }
Robert Carr2047fae2016-11-28 14:09:09 -08002731
2732 first = false;
2733 });
Mathias Agopian84300952012-11-21 16:02:13 -08002734 }
2735
Mathias Agopian3559b072012-08-15 13:46:03 -07002736 /*
2737 * Perform our own transaction if needed
2738 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002739
2740 if (mLayersAdded) {
2741 mLayersAdded = false;
2742 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002743 mVisibleRegionsDirty = true;
2744 }
2745
2746 // some layers might have been removed, so
2747 // we need to update the regions they're exposing.
2748 if (mLayersRemoved) {
2749 mLayersRemoved = false;
2750 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002751 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002752 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002753 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002754 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002755 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002756 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002757 }
Robert Carr2047fae2016-11-28 14:09:09 -08002758 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759 }
2760
Vishnu Nairec0ab382019-02-13 15:32:56 -08002761 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002763}
2764
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002765void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002766 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002767 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002768 return;
2769 }
2770
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002771 if (mVisibleRegionsDirty || mInputInfoChanged) {
2772 mInputInfoChanged = false;
2773 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002774 } else if (mInputWindowCommands.syncInputWindows) {
2775 // If the caller requested to sync input windows, but there are no
2776 // changes to input windows, notify immediately.
2777 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002778 }
2779
Arthur Hung6cbb9752019-09-05 16:38:18 +08002780 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002781}
2782
2783void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002784 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002785
2786 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Robert Carredd13602020-04-13 17:24:34 -07002787 if (layer->needsInputInfo()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002788 // When calculating the screen bounds we ignore the transparent region since it may
2789 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002790 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002791 }
2792 });
chaviw291d88a2019-02-14 10:33:58 -08002793
2794 mInputFlinger->setInputWindows(inputHandles,
2795 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2796 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002797}
2798
Vishnu Nairec0ab382019-02-13 15:32:56 -08002799void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002800 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002801 mPendingInputWindowCommands.clear();
2802}
2803
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002804void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002805 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002806 for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002807 if (display->getId()) {
2808 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002809 }
2810 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002811
2812 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002813}
2814
Ady Abraham2139f732019-11-13 18:56:40 -08002815void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002816 Scheduler::ConfigEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08002817 // If this is called from the main thread mStateLock must be locked before
2818 // Currently the only way to call this function from the main thread is from
2819 // Sheduler::chooseRefreshRateForContent
2820
2821 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002822 changeRefreshRateLocked(refreshRate, event);
2823}
2824
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002825void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2826 if (mScheduler) {
2827 // In practice it's not allowed to hotplug in/out the primary display once it's been
2828 // connected during startup, but some tests do it, so just warn and return.
2829 ALOGW("Can't re-init scheduler");
2830 return;
2831 }
2832
Ady Abraham2139f732019-11-13 18:56:40 -08002833 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002834 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002835 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002836 primaryDisplayId),
2837 currentConfig);
2838 mRefreshRateStats =
2839 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002840 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002841 mRefreshRateStats->setConfigMode(currentConfig);
2842
Ady Abraham9e16a482019-12-03 17:19:41 -08002843 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2844
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002845 // start the EventThread
2846 mScheduler =
2847 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002848 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002849 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002850 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002851 impl::EventThread::InterceptVSyncsCallback());
2852 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002853 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002854 [this](nsecs_t timestamp) {
2855 mInterceptor->saveVSyncEvent(timestamp);
2856 });
2857
2858 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2859 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002860 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002861
2862 mRegionSamplingThread =
2863 new RegionSamplingThread(*this, *mScheduler,
2864 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002865 // Dispatch a config change request for the primary display on scheduler
2866 // initialization, so that the EventThreads always contain a reference to a
2867 // prior configuration.
2868 //
2869 // This is a bit hacky, but this avoids a back-pointer into the main SF
2870 // classes from EventThread, and there should be no run-time binder cost
2871 // anyway since there are no connected apps at this point.
2872 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002873 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07002874 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, primaryDisplayId.value,
2875 currentConfig, vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002876}
2877
Mathias Agopian4fec8732012-06-29 14:12:52 -07002878void SurfaceFlinger::commitTransaction()
2879{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002880 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002881 mTransactionPending = false;
2882 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002883 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884}
2885
Lloyd Pique58e24a32019-08-01 15:50:14 -07002886void SurfaceFlinger::commitTransactionLocked() {
2887 if (!mLayersPendingRemoval.isEmpty()) {
2888 // Notify removed layers now that they can't be drawn from
2889 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002890 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002891
2892 // Ensure any buffers set to display on any children are released.
2893 if (l->isRemovedFromCurrentState()) {
2894 l->latchAndReleaseBuffer();
2895 }
2896
2897 // If the layer has been removed and has no parent, then it will not be reachable
2898 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2899 // ensure we can copy its current to drawing state.
2900 if (!l->getParent()) {
2901 mOffscreenLayers.emplace(l.get());
2902 }
2903 }
2904 mLayersPendingRemoval.clear();
2905 }
2906
2907 // If this transaction is part of a window animation then the next frame
2908 // we composite should be considered an animation as well.
2909 mAnimCompositionPending = mAnimTransactionPending;
2910
2911 mDrawingState = mCurrentState;
2912 // clear the "changed" flags in current state
2913 mCurrentState.colorMatrixChanged = false;
2914
Edgar Arriaga844fa672020-01-16 14:21:42 -08002915 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002916 layer->commitChildList();
2917
2918 // If the layer can be reached when traversing mDrawingState, then the layer is no
2919 // longer offscreen. Remove the layer from the offscreenLayer set.
2920 if (mOffscreenLayers.count(layer)) {
2921 mOffscreenLayers.erase(layer);
2922 }
2923 });
2924
2925 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002926 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002927}
2928
chaviw74d90ad2019-04-26 14:45:26 -07002929void SurfaceFlinger::commitOffscreenLayers() {
2930 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002931 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002932 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2933 if (!trFlags) return;
2934
2935 layer->doTransaction(0);
2936 layer->commitChildList();
2937 });
2938 }
2939}
2940
Chia-I Wuab0c3192017-08-01 11:29:00 -07002941void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002942 for (const auto& [token, displayDevice] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002943 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002944 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002945 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002946 }
2947 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002948}
2949
Dan Stoza6b9454d2014-11-07 16:00:59 -08002950bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002951{
Ady Abraham09bd3922019-04-08 10:44:56 -07002952 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002953 ALOGV("handlePageFlip");
2954
Brian Andersond6927fb2016-07-23 23:37:30 -07002955 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956
Mathias Agopian4fec8732012-06-29 14:12:52 -07002957 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002958 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002959 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002960
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002961 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2962
Eric Penner51c59cd2014-07-28 19:51:58 -07002963 // Store the set of layers that need updates. This set must not change as
2964 // buffers are being latched, as this could result in a deadlock.
2965 // Example: Two producers share the same command stream and:
2966 // 1.) Layer 0 is latched
2967 // 2.) Layer 0 gets a new frame
2968 // 2.) Layer 1 gets a new frame
2969 // 3.) Layer 1 is latched.
2970 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2971 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002972 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002973 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002974 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002975 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002976 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002977 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002978 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002979 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002980 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002981 } else {
2982 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002983 }
Robert Carr2047fae2016-11-28 14:09:09 -08002984 });
2985
chaviw49a108c2019-08-12 11:23:06 -07002986 // The client can continue submitting buffers for offscreen layers, but they will not
2987 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2988 // layers to ensure dequeueBuffer doesn't block indefinitely.
2989 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002990 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002991 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2992 }
2993
Lloyd Piquef2c79392018-12-20 16:23:33 -08002994 if (!mLayersWithQueuedFrames.empty()) {
2995 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2996 // writes to Layer current state. See also b/119481871
2997 Mutex::Autolock lock(mStateLock);
2998
2999 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003000 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003001 mLayersPendingRefresh.push_back(layer);
3002 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003003 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003004 if (layer->isBufferLatched()) {
3005 newDataLatched = true;
3006 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003007 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003008 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003009
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003010 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003011
3012 // If we will need to wake up at some time in the future to deal with a
3013 // queued frame that shouldn't be displayed during this vsync period, wake
3014 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003015 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003016 signalLayerUpdate();
3017 }
3018
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003019 // enter boot animation on first buffer latch
3020 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3021 ALOGI("Enter boot animation");
3022 mBootStage = BootStage::BOOTANIMATION;
3023 }
3024
Edgar Arriaga844fa672020-01-16 14:21:42 -08003025 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003026
Dan Stoza6b9454d2014-11-07 16:00:59 -08003027 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003028 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003029}
3030
Mathias Agopianad456f92011-01-13 17:53:01 -08003031void SurfaceFlinger::invalidateHwcGeometry()
3032{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003033 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003034}
3035
Robert Carrc0df3122019-04-11 13:18:21 -07003036status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3037 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3038 const sp<IBinder>& parentHandle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003039 const sp<Layer>& parentLayer, bool addToCurrentState,
3040 uint32_t* outTransformHint) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003041 // add this layer to the current state list
3042 {
3043 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003044 sp<Layer> parent;
3045 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003046 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003047 if (parent == nullptr) {
3048 return NAME_NOT_FOUND;
3049 }
3050 } else {
3051 parent = parentLayer;
3052 }
3053
Ady Abraham0a525092020-03-03 12:51:24 -08003054 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003055 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003056 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003057 return NO_MEMORY;
3058 }
Robert Carrc0df3122019-04-11 13:18:21 -07003059
3060 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3061
Robert Carrb89ea9d2018-12-10 13:01:14 -08003062 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003063 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003064 } else if (parent == nullptr) {
3065 lbc->onRemovedFromCurrentState();
3066 } else if (parent->isRemovedFromCurrentState()) {
3067 parent->addChild(lbc);
3068 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003069 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003070 parent->addChild(lbc);
3071 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003072
Yiwei Zhang243b3782018-05-15 17:40:04 -07003073 if (gbc != nullptr) {
3074 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3075 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3076 mMaxGraphicBufferProducerListSize,
3077 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3078 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003079 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003080 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003081
3082 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07003083 lbc->updateTransformHint(display->getTransformHint());
Vishnu Nair6213bd92020-05-08 17:42:25 -07003084 }
3085 if (outTransformHint) {
3086 *outTransformHint = lbc->getTransformHint();
3087 }
3088
Robert Carr1f0a16a2016-10-24 16:27:39 -07003089 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003090 }
3091
Mathias Agopian96f08192010-06-02 23:28:45 -07003092 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003093 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003094
Dan Stoza7d89d062015-04-30 13:29:25 -07003095 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003096}
3097
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003098void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3099 static_cast<void>(schedule([=] {
3100 Mutex::Autolock lock(mStateLock);
3101 mGraphicBufferProducerList.erase(binder);
3102 }));
3103}
3104
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003105uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003106 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003107}
3108
Mathias Agopian3f844832013-08-07 21:24:32 -07003109uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003110 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111}
3112
Mathias Agopian3f844832013-08-07 21:24:32 -07003113uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ady Abrahambf1349c2020-06-12 14:26:18 -07003114 return setTransactionFlags(flags, Scheduler::TransactionStart::Normal);
Dan Stoza84d619e2018-03-28 17:07:36 -07003115}
3116
3117uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003118 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003119 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003120 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003122 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123 }
3124 return old;
3125}
3126
Valerie Haud50e7412020-06-16 17:58:14 -07003127void SurfaceFlinger::setTraversalNeeded() {
3128 mForceTraversal = true;
Robert Carr7ec777d2020-05-29 12:02:51 -07003129}
3130
Marissa Wall713b63f2018-10-17 15:42:43 -07003131bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003132 // to prevent onHandleDestroyed from being called while the lock is held,
3133 // we must keep a copy of the transactions (specifically the composer
3134 // states) around outside the scope of the lock
3135 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003136 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003137 {
3138 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003139
Valerie Haufce31b82019-04-30 16:41:14 -07003140 auto it = mTransactionQueues.begin();
3141 while (it != mTransactionQueues.end()) {
3142 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003143
Valerie Haufce31b82019-04-30 16:41:14 -07003144 while (!transactionQueue.empty()) {
3145 const auto& transaction = transactionQueue.front();
3146 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3147 transaction.states)) {
3148 setTransactionFlags(eTransactionFlushNeeded);
3149 break;
3150 }
3151 transactions.push_back(transaction);
3152 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3153 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003154 transaction.buffer, transaction.postTime,
3155 transaction.privileged, transaction.hasListenerCallbacks,
3156 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003157 transactionQueue.pop();
3158 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003159 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003160
Valerie Haufce31b82019-04-30 16:41:14 -07003161 if (transactionQueue.empty()) {
3162 it = mTransactionQueues.erase(it);
3163 mTransactionCV.broadcast();
3164 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003165 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003166 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003167 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003168 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003169 return flushedATransaction;
3170}
3171
3172bool SurfaceFlinger::transactionFlushNeeded() {
3173 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003174}
3175
chaviwca27f252018-02-06 16:46:39 -08003176
Marissa Wall17b4e452018-12-26 16:32:34 -08003177bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3178 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003179
3180 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003181 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3182 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3183 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3184 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3185 return false;
3186 }
3187
Marissa Wall713b63f2018-10-17 15:42:43 -07003188 for (const ComposerState& state : states) {
3189 const layer_state_t& s = state.state;
3190 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3191 continue;
3192 }
3193 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003194 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003195 }
3196 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003197 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003198}
3199
Valerie Hau9dab9732019-08-20 09:29:25 -07003200void SurfaceFlinger::setTransactionState(
3201 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3202 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3203 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3204 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003205 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003206
Valerie Haubc6ddb12019-03-08 11:10:15 -08003207 const int64_t postTime = systemTime();
3208
Robert Carr14167e02019-02-13 13:50:55 -08003209 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3210
Mathias Agopian698c0872011-06-28 19:09:31 -07003211 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003212
Marissa Wall713b63f2018-10-17 15:42:43 -07003213 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003214 auto itr = mTransactionQueues.find(applyToken);
3215 // if this is an animation frame, wait until prior animation frame has
3216 // been applied by SF
3217 if (flags & eAnimation) {
3218 while (itr != mTransactionQueues.end()) {
3219 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3220 if (CC_UNLIKELY(err != NO_ERROR)) {
3221 ALOGW_IF(err == TIMED_OUT,
3222 "setTransactionState timed out "
3223 "waiting for animation frame to apply");
3224 break;
3225 }
3226 itr = mTransactionQueues.find(applyToken);
3227 }
3228 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003229
Ady Abraham5facfb12020-04-22 15:18:31 -07003230 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003231 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003232 if (!pendingTransactions) {
3233 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3234 }
3235
3236 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003237 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003238 uncacheBuffer, postTime, privileged,
3239 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003240 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003241 return;
3242 }
3243
Valerie Haubc6ddb12019-03-08 11:10:15 -08003244 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003245 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3246 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003247}
3248
Valerie Hau9dab9732019-08-20 09:29:25 -07003249void SurfaceFlinger::applyTransactionState(
3250 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3251 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3252 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3253 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3254 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003255 uint32_t transactionFlags = 0;
3256
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003257 if (flags & eAnimation) {
3258 // For window updates that are part of an animation we must wait for
3259 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003260 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003261 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003262 if (CC_UNLIKELY(err != NO_ERROR)) {
3263 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003264 // caller after a few seconds.
3265 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3266 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003267 mAnimTransactionPending = false;
3268 break;
3269 }
3270 }
3271 }
3272
chaviwca27f252018-02-06 16:46:39 -08003273 for (const DisplayState& display : displays) {
3274 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003275 }
3276
Valerie Hau9dab9732019-08-20 09:29:25 -07003277 // start and end registration for listeners w/ no surface so they can get their callback. Note
3278 // that listeners with SurfaceControls will start registration during setClientStateLocked
3279 // below.
3280 for (const auto& listener : listenerCallbacks) {
3281 mTransactionCompletedThread.startRegistration(listener);
3282 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003283 }
3284
Valerie Hau9dab9732019-08-20 09:29:25 -07003285 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003286 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003287 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003288 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3289 listenerCallbacksWithSurfaces);
Ady Abraham5def7332020-05-29 16:13:47 -07003290 if ((flags & eAnimation) && state.state.surface) {
3291 if (const auto layer = fromHandleLocked(state.state.surface).promote(); layer) {
3292 mScheduler->recordLayerHistory(layer.get(), desiredPresentTime,
3293 LayerHistory::LayerUpdateType::AnimationTX);
3294 }
3295 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07003296 }
3297
Valerie Hau9dab9732019-08-20 09:29:25 -07003298 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003299 mTransactionCompletedThread.endRegistration(listenerCallback);
3300 }
3301
Marissa Walle2ffb422018-10-12 11:33:52 -07003302 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003303 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003304 mTransactionCompletedThread.sendCallbacks();
3305 }
3306 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003307
chaviw273171b2018-12-26 11:46:30 -08003308 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3309
Marissa Wall947d34e2019-03-29 14:03:53 -07003310 if (uncacheBuffer.isValid()) {
3311 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003312 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003313 }
3314
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003315 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3316 // anyway. This can be used as a flush mechanism for previous async transactions.
3317 // Empty animation transaction can be used to simulate back-pressure, so also force a
3318 // transaction for empty animation transactions.
3319 if (transactionFlags == 0 &&
3320 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003321 transactionFlags = eTransactionNeeded;
3322 }
3323
Marissa Wall06255332019-03-27 13:48:27 -07003324 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3325 // so we don't have to wake up again next frame to preform an uneeded traversal.
3326 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3327 transactionFlags = transactionFlags & (~eTraversalNeeded);
Valerie Haud50e7412020-06-16 17:58:14 -07003328 mForceTraversal = true;
Marissa Wall06255332019-03-27 13:48:27 -07003329 }
3330
Ady Abrahambf1349c2020-06-12 14:26:18 -07003331 const auto transactionStart = [](uint32_t flags) {
3332 if (flags & eEarlyWakeup) {
3333 return Scheduler::TransactionStart::Early;
3334 }
3335 if (flags & eExplicitEarlyWakeupEnd) {
3336 return Scheduler::TransactionStart::EarlyEnd;
3337 }
3338 if (flags & eExplicitEarlyWakeupStart) {
3339 return Scheduler::TransactionStart::EarlyStart;
3340 }
3341 return Scheduler::TransactionStart::Normal;
3342 }(flags);
3343
Mathias Agopian386aa982011-11-07 21:58:03 -08003344 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003345 if (mInterceptor->isEnabled()) {
3346 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003347 }
Irvel468051e2016-06-13 16:44:44 -07003348
Ady Abrahambf1349c2020-06-12 14:26:18 -07003349 // TODO(b/159125966): Remove eEarlyWakeup completly as no client should use this flag
3350 if (flags & eEarlyWakeup) {
3351 ALOGW("eEarlyWakeup is deprecated. Use eExplicitEarlyWakeup[Start|End]");
3352 }
3353
3354 if (!privileged && (flags & (eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd))) {
3355 ALOGE("Only WindowManager is allowed to use eExplicitEarlyWakeup[Start|End] flags");
3356 flags &= ~(eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd);
3357 }
3358
Mathias Agopian386aa982011-11-07 21:58:03 -08003359 // this triggers the transaction
Ady Abrahambf1349c2020-06-12 14:26:18 -07003360 setTransactionFlags(transactionFlags, transactionStart);
Mathias Agopian386aa982011-11-07 21:58:03 -08003361
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003362 if (flags & eAnimation) {
3363 mAnimTransactionPending = true;
3364 }
Robert Carr238f4a22020-04-29 13:04:02 -07003365
3366 // if this is a synchronous transaction, wait for it to take effect
3367 // before returning.
3368 const bool synchronous = flags & eSynchronous;
3369 const bool syncInput = inputWindowCommands.syncInputWindows;
3370 if (!synchronous && !syncInput) {
3371 return;
3372 }
3373
3374 if (synchronous) {
3375 mTransactionPending = true;
3376 }
3377 if (syncInput) {
chaviw4fe36852019-04-15 16:25:49 -07003378 mPendingSyncInputWindows = true;
3379 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003380
Robert Carr238f4a22020-04-29 13:04:02 -07003381
Valerie Hau0779ded2019-03-19 12:43:04 -07003382 // applyTransactionState can be called by either the main SF thread or by
3383 // another process through setTransactionState. While a given process may wish
3384 // to wait on synchronous transactions, the main SF thread should never
3385 // be blocked. Therefore, we only wait if isMainThread is false.
3386 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003387 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3388 if (CC_UNLIKELY(err != NO_ERROR)) {
3389 // just in case something goes wrong in SF, return to the
3390 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003391 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3392 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003393 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003394 break;
3395 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003396 }
Ady Abrahambf1349c2020-06-12 14:26:18 -07003397 } else {
3398 // even if a transaction is not needed, we need to update VsyncModulator
3399 // about explicit early indications
3400 if (transactionStart == Scheduler::TransactionStart::EarlyStart ||
3401 transactionStart == Scheduler::TransactionStart::EarlyEnd) {
3402 mVSyncModulator->setTransactionStart(transactionStart);
3403 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003404 }
3405}
3406
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003407uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3408 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3409 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003410
Mathias Agopiane57f2922012-08-09 16:29:12 -07003411 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003412 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3413
3414 const uint32_t what = s.what;
3415 if (what & DisplayState::eSurfaceChanged) {
3416 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3417 state.surface = s.surface;
3418 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003419 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003420 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003421 if (what & DisplayState::eLayerStackChanged) {
3422 if (state.layerStack != s.layerStack) {
3423 state.layerStack = s.layerStack;
3424 flags |= eDisplayTransactionNeeded;
3425 }
3426 }
3427 if (what & DisplayState::eDisplayProjectionChanged) {
3428 if (state.orientation != s.orientation) {
3429 state.orientation = s.orientation;
3430 flags |= eDisplayTransactionNeeded;
3431 }
3432 if (state.frame != s.frame) {
3433 state.frame = s.frame;
3434 flags |= eDisplayTransactionNeeded;
3435 }
3436 if (state.viewport != s.viewport) {
3437 state.viewport = s.viewport;
3438 flags |= eDisplayTransactionNeeded;
3439 }
3440 }
3441 if (what & DisplayState::eDisplaySizeChanged) {
3442 if (state.width != s.width) {
3443 state.width = s.width;
3444 flags |= eDisplayTransactionNeeded;
3445 }
3446 if (state.height != s.height) {
3447 state.height = s.height;
3448 flags |= eDisplayTransactionNeeded;
3449 }
3450 }
3451
Mathias Agopiane57f2922012-08-09 16:29:12 -07003452 return flags;
3453}
3454
Steven Thomasd4071902020-03-24 16:02:53 -07003455bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003456 IPCThreadState* ipc = IPCThreadState::self();
3457 const int pid = ipc->getCallingPid();
3458 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003459 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003460 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3461 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003462 return false;
3463 }
3464 return true;
3465}
3466
Marissa Wall3dad52d2019-03-22 14:03:19 -07003467uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003468 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3469 bool privileged,
3470 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003471 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003472
Valerie Hau9dab9732019-08-20 09:29:25 -07003473 for (auto& listener : s.listeners) {
3474 // note that startRegistration will not re-register if the listener has
3475 // already be registered for a prior surface control
3476 mTransactionCompletedThread.startRegistration(listener);
3477 listenerCallbacks.insert(listener);
3478 }
3479
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003480 sp<Layer> layer = nullptr;
3481 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003482 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003483 } else {
3484 // The client may provide us a null handle. Treat it as if the layer was removed.
3485 ALOGW("Attempt to set client state with a null layer handle");
3486 }
chaviw8b3871a2017-11-01 17:41:01 -07003487 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003488 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003489 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003490 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003491 }
chaviw8b3871a2017-11-01 17:41:01 -07003492 return 0;
3493 }
3494
chaviw8b3871a2017-11-01 17:41:01 -07003495 uint32_t flags = 0;
3496
Garfield Tan8a3083e2018-12-03 13:21:07 -08003497 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003498
3499 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3500 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003501 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003502 layer->pushPendingState();
3503 }
3504
Valerie Hau871d6352020-01-29 08:44:02 -08003505 // Only set by BLAST adapter layers
3506 if (what & layer_state_t::eProducerDisconnect) {
3507 layer->onDisconnect();
3508 }
3509
chaviw8b3871a2017-11-01 17:41:01 -07003510 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003511 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003512 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003513 }
chaviw8b3871a2017-11-01 17:41:01 -07003514 }
3515 if (what & layer_state_t::eLayerChanged) {
3516 // NOTE: index needs to be calculated before we update the state
3517 const auto& p = layer->getParent();
3518 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003519 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003520 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003521 mCurrentState.layersSortedByZ.removeAt(idx);
3522 mCurrentState.layersSortedByZ.add(layer);
3523 // we need traversal (state changed)
3524 // AND transaction (list changed)
3525 flags |= eTransactionNeeded|eTraversalNeeded;
3526 }
chaviw8b3871a2017-11-01 17:41:01 -07003527 } else {
3528 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003529 flags |= eTransactionNeeded|eTraversalNeeded;
3530 }
3531 }
chaviw8b3871a2017-11-01 17:41:01 -07003532 }
3533 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003534 // NOTE: index needs to be calculated before we update the state
3535 const auto& p = layer->getParent();
3536 if (p == nullptr) {
3537 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3538 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3539 mCurrentState.layersSortedByZ.removeAt(idx);
3540 mCurrentState.layersSortedByZ.add(layer);
3541 // we need traversal (state changed)
3542 // AND transaction (list changed)
3543 flags |= eTransactionNeeded|eTraversalNeeded;
3544 }
3545 } else {
3546 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3547 flags |= eTransactionNeeded|eTraversalNeeded;
3548 }
chaviw8b3871a2017-11-01 17:41:01 -07003549 }
3550 }
3551 if (what & layer_state_t::eSizeChanged) {
3552 if (layer->setSize(s.w, s.h)) {
3553 flags |= eTraversalNeeded;
3554 }
3555 }
3556 if (what & layer_state_t::eAlphaChanged) {
3557 if (layer->setAlpha(s.alpha))
3558 flags |= eTraversalNeeded;
3559 }
3560 if (what & layer_state_t::eColorChanged) {
3561 if (layer->setColor(s.color))
3562 flags |= eTraversalNeeded;
3563 }
Peiyong Lind3788632018-09-18 16:01:31 -07003564 if (what & layer_state_t::eColorTransformChanged) {
3565 if (layer->setColorTransform(s.colorTransform)) {
3566 flags |= eTraversalNeeded;
3567 }
3568 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003569 if (what & layer_state_t::eBackgroundColorChanged) {
3570 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3571 flags |= eTraversalNeeded;
3572 }
3573 }
chaviw8b3871a2017-11-01 17:41:01 -07003574 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003575 // TODO: b/109894387
3576 //
3577 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3578 // rotation. To see the problem observe that if we have a square parent, and a child
3579 // of the same size, then we rotate the child 45 degrees around it's center, the child
3580 // must now be cropped to a non rectangular 8 sided region.
3581 //
3582 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3583 // private API, and the WindowManager only uses rotation in one case, which is on a top
3584 // level layer in which cropping is not an issue.
3585 //
3586 // However given that abuse of rotation matrices could lead to surfaces extending outside
3587 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3588 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3589 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003590 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003591 flags |= eTraversalNeeded;
3592 }
3593 if (what & layer_state_t::eTransparentRegionChanged) {
3594 if (layer->setTransparentRegionHint(s.transparentRegion))
3595 flags |= eTraversalNeeded;
3596 }
3597 if (what & layer_state_t::eFlagsChanged) {
3598 if (layer->setFlags(s.flags, s.mask))
3599 flags |= eTraversalNeeded;
3600 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003601 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003602 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003603 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003604 if (what & layer_state_t::eCornerRadiusChanged) {
3605 if (layer->setCornerRadius(s.cornerRadius))
3606 flags |= eTraversalNeeded;
3607 }
Lucas Dupin130e55c2020-05-26 16:11:18 -07003608 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003609 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3610 }
chaviw8b3871a2017-11-01 17:41:01 -07003611 if (what & layer_state_t::eLayerStackChanged) {
3612 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3613 // We only allow setting layer stacks for top level layers,
3614 // everything else inherits layer stack from its parent.
3615 if (layer->hasParent()) {
3616 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003617 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003618 } else if (idx < 0) {
3619 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003620 "that also does not appear in the top level layer list. Something"
3621 " has gone wrong.",
3622 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003623 } else if (layer->setLayerStack(s.layerStack)) {
3624 mCurrentState.layersSortedByZ.removeAt(idx);
3625 mCurrentState.layersSortedByZ.add(layer);
3626 // we need traversal (state changed)
3627 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07003628 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003629 }
3630 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003631 if (what & layer_state_t::eDeferTransaction_legacy) {
3632 if (s.barrierHandle_legacy != nullptr) {
3633 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3634 } else if (s.barrierGbp_legacy != nullptr) {
3635 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003636 if (authenticateSurfaceTextureLocked(gbp)) {
3637 const auto& otherLayer =
3638 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003639 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003640 } else {
3641 ALOGE("Attempt to defer transaction to to an"
3642 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003643 }
3644 }
chaviw8b3871a2017-11-01 17:41:01 -07003645 // We don't trigger a traversal here because if no other state is
3646 // changed, we don't want this to cause any more work
3647 }
chaviw8b3871a2017-11-01 17:41:01 -07003648 if (what & layer_state_t::eReparentChildren) {
3649 if (layer->reparentChildren(s.reparentHandle)) {
3650 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003651 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003652 }
chaviw8b3871a2017-11-01 17:41:01 -07003653 if (what & layer_state_t::eDetachChildren) {
3654 layer->detachChildren();
3655 }
3656 if (what & layer_state_t::eOverrideScalingModeChanged) {
3657 layer->setOverrideScalingMode(s.overrideScalingMode);
3658 // We don't trigger a traversal here because if no other state is
3659 // changed, we don't want this to cause any more work
3660 }
Marissa Wall61c58622018-07-18 10:12:20 -07003661 if (what & layer_state_t::eTransformChanged) {
3662 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3663 }
3664 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3665 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3666 flags |= eTraversalNeeded;
3667 }
3668 if (what & layer_state_t::eCropChanged) {
3669 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3670 }
Marissa Wall861616d2018-10-22 12:52:23 -07003671 if (what & layer_state_t::eFrameChanged) {
3672 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3673 }
Marissa Wall61c58622018-07-18 10:12:20 -07003674 if (what & layer_state_t::eAcquireFenceChanged) {
3675 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3676 }
3677 if (what & layer_state_t::eDataspaceChanged) {
3678 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3679 }
3680 if (what & layer_state_t::eHdrMetadataChanged) {
3681 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3682 }
3683 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3684 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3685 }
3686 if (what & layer_state_t::eApiChanged) {
3687 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3688 }
3689 if (what & layer_state_t::eSidebandStreamChanged) {
3690 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3691 }
Robert Carr720e5062018-07-30 17:45:14 -07003692 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003693 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003694 layer->setInputInfo(s.inputInfo);
3695 flags |= eTraversalNeeded;
3696 } else {
3697 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3698 }
Robert Carr720e5062018-07-30 17:45:14 -07003699 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003700 if (what & layer_state_t::eMetadataChanged) {
3701 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3702 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003703 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3704 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3705 flags |= eTraversalNeeded;
3706 }
3707 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003708 if (what & layer_state_t::eShadowRadiusChanged) {
3709 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3710 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003711 if (what & layer_state_t::eFrameRateSelectionPriority) {
3712 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3713 flags |= eTraversalNeeded;
3714 }
3715 }
Steven Thomas3172e202020-01-06 19:25:30 -08003716 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003717 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3718 "SurfaceFlinger::setClientStateLocked") &&
3719 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3720 Layer::FrameRate::convertCompatibility(
3721 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003722 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003723 }
Steven Thomas3172e202020-01-06 19:25:30 -08003724 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003725 if (what & layer_state_t::eFixedTransformHintChanged) {
3726 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
3727 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
3728 }
3729 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003730 // This has to happen after we reparent children because when we reparent to null we remove
3731 // child layers from current state and remove its relative z. If the children are reparented in
3732 // the same transaction, then we have to make sure we reparent the children first so we do not
3733 // lose its relative z order.
3734 if (what & layer_state_t::eReparent) {
3735 bool hadParent = layer->hasParent();
3736 if (layer->reparent(s.parentHandleForChild)) {
3737 if (!hadParent) {
3738 mCurrentState.layersSortedByZ.remove(layer);
3739 }
3740 flags |= eTransactionNeeded | eTraversalNeeded;
3741 }
3742 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003743 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003744 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3745 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003746 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3747 }
3748 }
Marissa Wall78b72202019-03-15 14:58:34 -07003749 bool bufferChanged = what & layer_state_t::eBufferChanged;
3750 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3751 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003752 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003753 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003754 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3755 if (success) {
3756 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3757 success = ClientCache::getInstance()
3758 .registerErasedRecipient(s.cachedBuffer,
3759 wp<ClientCache::ErasedRecipient>(this));
3760 if (!success) {
3761 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3762 }
3763 }
Marissa Wall78b72202019-03-15 14:58:34 -07003764 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003765 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003766 } else if (bufferChanged) {
3767 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003768 }
Marissa Wall78b72202019-03-15 14:58:34 -07003769 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003770 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3771 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003772 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003773 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003774 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003775 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3776 // Do not put anything that updates layer state or modifies flags after
3777 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003778 return flags;
3779}
3780
chaviw273171b2018-12-26 11:46:30 -08003781uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3782 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003783 if (inputWindowCommands.syncInputWindows) {
3784 flags |= eTraversalNeeded;
3785 }
3786
Vishnu Nairec0ab382019-02-13 15:32:56 -08003787 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003788 return flags;
3789}
3790
chaviwfe94a222019-08-21 13:52:59 -07003791status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3792 sp<IBinder>* outHandle) {
3793 if (!mirrorFromHandle) {
3794 return NAME_NOT_FOUND;
3795 }
3796
3797 sp<Layer> mirrorLayer;
3798 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003799 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003800
3801 {
3802 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003803 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003804 if (!mirrorFrom) {
3805 return NAME_NOT_FOUND;
3806 }
3807
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003808 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3809 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003810 if (result != NO_ERROR) {
3811 return result;
3812 }
3813
3814 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3815 }
3816
Vishnu Nair6213bd92020-05-08 17:42:25 -07003817 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false,
3818 nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07003819}
3820
Marissa Wall2d814fb2019-04-09 18:52:57 +00003821status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3822 uint32_t h, PixelFormat format, uint32_t flags,
3823 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003824 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003825 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3826 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003827 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003828 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003829 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003830 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003831 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003832
Robert Carrc0df3122019-04-11 13:18:21 -07003833 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3834 "Expected only one of parentLayer or parentHandle to be non-null. "
3835 "Programmer error?");
3836
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003837 status_t result = NO_ERROR;
3838
3839 sp<Layer> layer;
3840
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003841 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003842
Evan Roskya1f1e152019-01-24 16:17:46 -08003843 bool primaryDisplayOnly = false;
3844
3845 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3846 // TODO b/64227542
3847 if (metadata.has(METADATA_WINDOW_TYPE)) {
3848 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3849 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003850 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003851 primaryDisplayOnly = true;
3852 }
3853 }
3854
Mathias Agopian3165cc22012-08-08 19:42:09 -07003855 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003856 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003857 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3858 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003859
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003860 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003861 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003862 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003863 std::move(metadata), handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003864 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003865 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003866 // check if buffer size is set for color layer.
3867 if (w > 0 || h > 0) {
3868 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3869 int(w), int(h));
3870 return BAD_VALUE;
3871 }
3872
Vishnu Nairfa247b12020-02-11 08:58:26 -08003873 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3874 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003875 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003876 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003877 // check if buffer size is set for container layer.
3878 if (w > 0 || h > 0) {
3879 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3880 int(w), int(h));
3881 return BAD_VALUE;
3882 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003883 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3884 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003885 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003886 default:
3887 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003888 break;
3889 }
3890
Dan Stoza7d89d062015-04-30 13:29:25 -07003891 if (result != NO_ERROR) {
3892 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003893 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003894
Evan Roskya1f1e152019-01-24 16:17:46 -08003895 if (primaryDisplayOnly) {
3896 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003897 }
3898
Robert Carrb89ea9d2018-12-10 13:01:14 -08003899 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003900 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003901 addToCurrentState, outTransformHint);
Dan Stoza7d89d062015-04-30 13:29:25 -07003902 if (result != NO_ERROR) {
3903 return result;
3904 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003905 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003906
3907 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003908 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003909}
3910
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003911std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3912 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003913
3914 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003915 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003916
Dan Stoza436ccf32018-06-21 12:10:12 -07003917 // Grab the state lock since we're accessing mCurrentState
3918 Mutex::Autolock lock(mStateLock);
3919
Cody Northropbc755282017-03-31 12:00:08 -06003920 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003921 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003922 while (matchFound) {
3923 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003924 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003925 if (layer->getName() == uniqueName) {
3926 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003927 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003928 }
3929 });
3930 }
3931
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003932 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003933 return uniqueName;
3934}
3935
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003936status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003937 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003938 LayerMetadata metadata, PixelFormat& format,
3939 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003940 sp<IGraphicBufferProducer>* gbp,
3941 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003942 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003943 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003944 case PIXEL_FORMAT_TRANSPARENT:
3945 case PIXEL_FORMAT_TRANSLUCENT:
3946 format = PIXEL_FORMAT_RGBA_8888;
3947 break;
3948 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003949 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003950 break;
3951 }
3952
chaviwb4c6e582019-08-16 14:35:07 -07003953 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003954 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003955 args.textureName = getNewTexture();
3956 {
3957 // Grab the SF state lock during this since it's the only safe way to access
3958 // RenderEngine when creating a BufferLayerConsumer
3959 // TODO: Check if this lock is still needed here
3960 Mutex::Autolock lock(mStateLock);
3961 layer = getFactory().createBufferQueueLayer(args);
3962 }
3963
Marissa Wallfd668622018-05-10 10:21:13 -07003964 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003965 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003966 *handle = layer->getHandle();
3967 *gbp = layer->getProducer();
3968 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003969 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003970
Marissa Wallfd668622018-05-10 10:21:13 -07003971 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003972 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003973}
3974
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003975status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003976 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003977 LayerMetadata metadata, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003978 sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003979 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003980 args.textureName = getNewTexture();
3981 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07003982 *handle = layer->getHandle();
3983 *outLayer = layer;
3984
3985 return NO_ERROR;
3986}
3987
Vishnu Nairfa247b12020-02-11 08:58:26 -08003988status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3989 uint32_t h, uint32_t flags, LayerMetadata metadata,
3990 sp<IBinder>* handle, sp<Layer>* outLayer) {
3991 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003992 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003993 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003994 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003995}
3996
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003997status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003998 uint32_t w, uint32_t h, uint32_t flags,
3999 LayerMetadata metadata, sp<IBinder>* handle,
4000 sp<Layer>* outLayer) {
4001 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004002 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004003 *handle = (*outLayer)->getHandle();
4004 return NO_ERROR;
4005}
4006
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004007void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004008 mLayersPendingRemoval.add(layer);
4009 mLayersRemoved = true;
4010 setTransactionFlags(eTransactionNeeded);
4011}
4012
Robert Carr695d5282018-12-18 15:27:58 -08004013void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004014{
Robert Carr2e102c92018-10-23 12:11:15 -07004015 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004016 // If a layer has a parent, we allow it to out-live it's handle
4017 // with the idea that the parent holds a reference and will eventually
4018 // be cleaned up. However no one cleans up the top-level so we do so
4019 // here.
4020 if (layer->getParent() == nullptr) {
4021 mCurrentState.layersSortedByZ.remove(layer);
4022 }
4023 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004024
4025 auto it = mLayersByLocalBinderToken.begin();
4026 while (it != mLayersByLocalBinderToken.end()) {
4027 if (it->second == layer) {
4028 it = mLayersByLocalBinderToken.erase(it);
4029 } else {
4030 it++;
4031 }
4032 }
4033
Robert Carr695d5282018-12-18 15:27:58 -08004034 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004035}
4036
Mathias Agopianb60314a2012-04-10 22:09:54 -07004037// ---------------------------------------------------------------------------
4038
Andy McFadden13a082e2012-08-24 10:16:42 -07004039void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004040 const auto display = getDefaultDisplayDeviceLocked();
4041 if (!display) return;
4042
4043 const sp<IBinder> token = display->getDisplayToken().promote();
4044 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004045
Jesse Hall01e29052013-02-19 16:13:35 -08004046 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004047 Vector<ComposerState> state;
4048 Vector<DisplayState> displays;
4049 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004050 d.what = DisplayState::eDisplayProjectionChanged |
4051 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004052 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004053 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004054 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004055 d.frame.makeInvalid();
4056 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004057 d.width = 0;
4058 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004059 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004060 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4061 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004062
Peiyong Lin65248e02020-04-18 21:15:07 -07004063 setPowerModeInternal(display, hal::PowerMode::ON);
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004064 const nsecs_t vsyncPeriod = mRefreshRateConfigs->getCurrentRefreshRate().getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004065 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004066
Brian Andersond0010582017-03-07 13:20:31 -08004067 // Use phase of 0 since phase is not known.
4068 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004069 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004070 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004071}
4072
4073void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004074 // Async since we may be called from the main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004075 static_cast<void>(schedule([this]() MAIN_THREAD { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004076}
4077
Peiyong Lin65248e02020-04-18 21:15:07 -07004078void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004079 if (display->isVirtual()) {
4080 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004081 return;
4082 }
4083
Dominik Laskowski075d3172018-05-24 15:50:06 -07004084 const auto displayId = display->getId();
4085 LOG_ALWAYS_FATAL_IF(!displayId);
4086
Dominik Laskowski34157762018-10-31 13:07:19 -07004087 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004088
Peiyong Lin65248e02020-04-18 21:15:07 -07004089 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004090 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004091 return;
4092 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004094 display->setPowerMode(mode);
4095
Lloyd Pique4dccc412018-01-22 17:21:36 -08004096 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004097 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004098 }
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004099 const auto vsyncPeriod = mRefreshRateConfigs->getCurrentRefreshRate().getVsyncPeriod();
Peiyong Lin65248e02020-04-18 21:15:07 -07004100 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004101 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4102 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4103 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004104 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004105 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004106 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004107 mScheduler->onScreenAcquired(mAppConnectionHandle);
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004108 mScheduler->resyncToHardwareVsync(true, vsyncPeriod);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004109 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004110
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004111 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004112 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004113 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004114 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004115 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004116 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4117 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004118 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004119 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004120 mScheduler->disableHardwareVsync(true);
4121 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004122 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004123
Ady Abraham27c70212019-06-11 10:52:26 -07004124 // Make sure HWVsync is disabled before turning off the display
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004125 getHwComposer().setVsyncEnabled(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004126
Dominik Laskowski075d3172018-05-24 15:50:06 -07004127 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004128 mVisibleRegionsDirty = true;
4129 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004130 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004131 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004132 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004133 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004134 mScheduler->onScreenAcquired(mAppConnectionHandle);
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004135 mScheduler->resyncToHardwareVsync(true, vsyncPeriod);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004136 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004137 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004138 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004139 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004140 mScheduler->disableHardwareVsync(true);
4141 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004142 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004143 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004144 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004145 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004146 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004147 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004148
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004149 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004150 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004151 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004152 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004153 }
4154
Dominik Laskowski34157762018-10-31 13:07:19 -07004155 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004156}
4157
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004158void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004159 schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004160 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004161 if (!display) {
4162 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4163 displayToken.get());
4164 } else if (display->isVirtual()) {
4165 ALOGW("Attempt to set power mode %d for virtual display", mode);
4166 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004167 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004168 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004169 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004170}
4171
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004172status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004173 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004174
Mathias Agopianbd115332013-04-18 16:41:04 -07004175 IPCThreadState* ipc = IPCThreadState::self();
4176 const int pid = ipc->getCallingPid();
4177 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004178
Mathias Agopianbd115332013-04-18 16:41:04 -07004179 if ((uid != AID_SHELL) &&
4180 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004181 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4182 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004183 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004184 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004185 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004186 {"--dispsync"s,
4187 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004188 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004189 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4190 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4191 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4192 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4193 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4194 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004195 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004196 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4197 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004198
Dominik Laskowskic2867142019-01-21 11:33:38 -08004199 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004200
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004201 bool dumpLayers = true;
4202 {
4203 TimedLock lock(mStateLock, s2ns(1), __FUNCTION__);
4204 if (!lock.locked()) {
4205 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4206 strerror(-lock.status), lock.status);
4207 }
4208
4209 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4210 (it->second)(args, asProto, result);
4211 dumpLayers = false;
4212 } else if (!asProto) {
4213 dumpAllLocked(args, result);
4214 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004215 }
4216
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004217 if (dumpLayers) {
Dominik Laskowski46470112019-08-02 13:13:11 -07004218 const LayersProto layersProto = dumpProtoFromMainThread();
4219 if (asProto) {
4220 result.append(layersProto.SerializeAsString());
4221 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004222 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004223 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4224 result.append(LayerProtoParser::layerTreeToString(layerTree));
4225 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004226 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004227 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004228 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004229 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004230 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004231 return NO_ERROR;
4232}
4233
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004234status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4235 if (asProto && mTracing.isEnabled()) {
4236 mTracing.writeToFileAsync();
4237 }
4238
4239 return doDump(fd, DumpArgs(), asProto);
4240}
4241
Dominik Laskowskic2867142019-01-21 11:33:38 -08004242void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004243 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004244 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004245}
4246
Dominik Laskowskic2867142019-01-21 11:33:38 -08004247void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004248 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004249
Dominik Laskowskic2867142019-01-21 11:33:38 -08004250 if (args.size() > 1) {
4251 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004252 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004253 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004254 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004255 }
Robert Carr2047fae2016-11-28 14:09:09 -08004256 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004257 } else {
4258 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004259 }
4260}
4261
Dominik Laskowskic2867142019-01-21 11:33:38 -08004262void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004263 const bool clearAll = args.size() < 2;
4264 const auto name = clearAll ? String8() : String8(args[1]);
4265
Edgar Arriaga844fa672020-01-16 14:21:42 -08004266 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004267 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004268 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004269 }
Robert Carr2047fae2016-11-28 14:09:09 -08004270 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004271
Svetoslavd85084b2014-03-20 10:28:31 -07004272 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004273}
4274
Dominik Laskowskic2867142019-01-21 11:33:38 -08004275void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4276 mTimeStats->parseArgs(asProto, args, result);
4277}
4278
Jamie Gennis6547ff42013-07-16 20:12:42 -07004279// This should only be called from the main thread. Otherwise it would need
4280// the lock and should use mCurrentState rather than mDrawingState.
4281void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004282 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004283 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004284 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004285
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004286 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004287}
4288
Yiwei Zhang5434a782018-12-05 18:06:32 -08004289void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004290 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004291
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004292 if (isLayerTripleBufferingDisabled())
4293 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004294
Yiwei Zhang5434a782018-12-05 18:06:32 -08004295 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4296 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4297 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4298 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4299 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4300 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004301 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004302}
4303
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004304void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004305 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004306
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004307 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004308 result.append("\n");
4309
Ady Abraham9e16a482019-12-03 17:19:41 -08004310 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004311 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004312 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004313 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004314
Steven Thomasd4071902020-03-24 16:02:53 -07004315 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004316 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004317 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004318 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4319 policy.defaultConfig.value(), policy.primaryRange.min, policy.primaryRange.max,
4320 policy.appRequestRange.min, policy.appRequestRange.max);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004321 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4322 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004323 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4324 if (currentPolicy != policy) {
4325 StringAppendF(&result,
4326 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004327 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4328 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
4329 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
4330 currentPolicy.appRequestRange.max);
Ady Abraham07e54702020-04-16 15:05:37 -07004331 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004332
Ana Krulecc2870422019-01-29 19:00:58 -08004333 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004334 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004335}
4336
Yiwei Zhang5434a782018-12-05 18:06:32 -08004337void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4338 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004339 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4340 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004341 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004342 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004343 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004344 }
David Sodman4a36e932017-11-07 14:29:47 -08004345 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004346 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004347 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004348 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4349 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004350}
4351
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004352void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4353 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004354 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4355 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004356 for (const auto& segment : history) {
4357 if (!segment.usedThirdBuffer) {
4358 stats.twoBufferTime += segment.totalTime;
4359 }
4360 if (segment.occupancyAverage < 1.0f) {
4361 stats.doubleBufferedTime += segment.totalTime;
4362 } else if (segment.occupancyAverage < 2.0f) {
4363 stats.tripleBufferedTime += segment.totalTime;
4364 }
4365 ++stats.numSegments;
4366 stats.totalTime += segment.totalTime;
4367 }
4368}
4369
Yiwei Zhang5434a782018-12-05 18:06:32 -08004370void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4371 result.append("Layer frame timestamps:\n");
Josh Chienedaa9132020-12-04 18:30:46 +08004372 // Traverse all layers to dump frame-events for each layer
4373 mCurrentState.traverseInZOrder(
4374 [&] (Layer* layer) { layer->dumpFrameEvents(result); });
Brian Andersond6927fb2016-07-23 23:37:30 -07004375}
4376
Yiwei Zhang5434a782018-12-05 18:06:32 -08004377void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004378 result.append("Buffering stats:\n");
4379 result.append(" [Layer name] <Active time> <Two buffer> "
4380 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004381 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004382 typedef std::tuple<std::string, float, float, float> BufferTuple;
4383 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004384 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004385 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004386 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004387 if (stats.numSegments == 0) {
4388 continue;
4389 }
4390 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4391 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4392 stats.totalTime;
4393 float doubleBufferRatio = static_cast<float>(
4394 stats.doubleBufferedTime) / stats.totalTime;
4395 float tripleBufferRatio = static_cast<float>(
4396 stats.tripleBufferedTime) / stats.totalTime;
4397 sorted.insert({activeTime, {name, twoBufferRatio,
4398 doubleBufferRatio, tripleBufferRatio}});
4399 }
4400 for (const auto& sortedPair : sorted) {
4401 float activeTime = sortedPair.first;
4402 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004403 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4404 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004405 }
4406 result.append("\n");
4407}
4408
Yiwei Zhang5434a782018-12-05 18:06:32 -08004409void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004410 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004411 const auto displayId = display->getId();
4412 if (!displayId) {
4413 continue;
4414 }
4415 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004416 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004417 continue;
4418 }
4419
Yiwei Zhang5434a782018-12-05 18:06:32 -08004420 StringAppendF(&result,
4421 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4422 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004423 uint8_t port;
4424 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004425 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004426 result.append("no identification data\n");
4427 continue;
4428 }
4429
4430 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004431 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004432 continue;
4433 }
4434
4435 const auto edid = parseEdid(data);
4436 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004437 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004438 continue;
4439 }
4440
Yiwei Zhang5434a782018-12-05 18:06:32 -08004441 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004442 result.append(edid->displayName.data(), edid->displayName.length());
4443 result.append("\"\n");
4444 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004445}
4446
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004447void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4448 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004449 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004450 uint8_t port;
4451 DisplayIdentificationData data;
4452
4453 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4454 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4455 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4456 }
4457}
4458
Yiwei Zhang5434a782018-12-05 18:06:32 -08004459void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004460 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004461 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4462 StringAppendF(&result, "DisplayColorSetting: %s\n",
4463 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004464
4465 // TODO: print out if wide-color mode is active or not
4466
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004467 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004468 const auto displayId = display->getId();
4469 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004470 continue;
4471 }
4472
Yiwei Zhang5434a782018-12-05 18:06:32 -08004473 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004474 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004475 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004476 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004477 }
4478
Lloyd Pique32cbe282018-10-19 13:09:22 -07004479 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004480 StringAppendF(&result, " Current color mode: %s (%d)\n",
4481 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004482 }
4483 result.append("\n");
4484}
4485
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004486LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4487 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004488 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004489
chaviw1d044282017-09-27 12:19:28 -07004490 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004491 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004492 layer->writeToProto(layersProto, traceFlags, display.get());
chaviw08f3cb22020-01-13 13:17:21 -08004493 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004494
chaviw1d044282017-09-27 12:19:28 -07004495 return layersProto;
4496}
4497
Alec Mouri6b9e9912020-01-21 10:50:24 -08004498void SurfaceFlinger::dumpHwc(std::string& result) const {
4499 getHwComposer().dump(result);
4500}
4501
Vishnu Nair0f085c62019-08-30 08:49:12 -07004502void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4503 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4504 // it.
4505 LayerProto* rootProto = layersProto.add_layers();
4506 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4507 rootProto->set_id(offscreenRootLayerId);
4508 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004509 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004510
4511 for (Layer* offscreenLayer : mOffscreenLayers) {
4512 // Add layer as child of the fake root
4513 rootProto->add_children(offscreenLayer->sequence);
4514
4515 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004516 LayerProto* layerProto =
4517 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004518 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004519 }
4520}
4521
Vishnu Nair8406fd72019-07-30 11:29:31 -07004522LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004523 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004524}
4525
Vishnu Nair0f085c62019-08-30 08:49:12 -07004526void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4527 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004528 result.append(schedule([this] {
4529 std::string result;
4530 for (Layer* offscreenLayer : mOffscreenLayers) {
4531 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4532 [&](Layer* layer) {
4533 layer->dumpCallingUidPid(result);
4534 });
4535 }
4536 return result;
4537 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004538}
4539
Dominik Laskowskic2867142019-01-21 11:33:38 -08004540void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4541 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004542 Colorizer colorizer(colorize);
4543
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004544 // figure out if we're stuck somewhere
4545 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004546 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004547 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4548
4549 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004550 * Dump library configuration.
4551 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004552
4553 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004554 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004555 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004556 appendSfConfigString(result);
4557 appendUiConfigString(result);
4558 appendGuiConfigString(result);
4559 result.append("\n");
4560
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004561 result.append("\nDisplay identification data:\n");
4562 dumpDisplayIdentificationData(result);
4563
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004564 result.append("\nWide-Color information:\n");
4565 dumpWideColorInfo(result);
4566
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004567 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004568 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004569 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004570 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004571 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004572
Andy McFadden41d67d72014-04-25 16:58:34 -07004573 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004574 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004575 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004576 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004577 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004578
Dan Stozab90cf072015-03-05 11:05:59 -08004579 dumpStaticScreenStats(result);
4580 result.append("\n");
4581
Alec Mouri40189b02019-03-05 15:07:54 -08004582 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4583 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4584 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004585
Dan Stozae77c7662016-05-13 11:37:28 -07004586 dumpBufferingStats(result);
4587
Andy McFadden4803b742012-09-24 19:07:20 -07004588 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004589 * Dump the visible layer list
4590 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004591 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004592 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004593 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4594 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004595 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004596
Chia-I Wu2f884132018-09-13 15:17:58 -07004597 {
Lloyd Pique207def92019-02-28 16:09:52 -08004598 StringAppendF(&result, "Composition layers\n");
4599 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004600 auto* compositionState = layer->getCompositionState();
4601 if (!compositionState) return;
4602
4603 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4604 layer->getDebugName() ? layer->getDebugName()
4605 : "<unknown>");
4606 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004607 });
4608 }
4609
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004610 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004611 * Dump Display state
4612 */
4613
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004614 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004615 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004616 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004617 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004618 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004619 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004620 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004621
4622 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004623 * Dump CompositionEngine state
4624 */
4625
4626 mCompositionEngine->dump(result);
4627
4628 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004629 * Dump SurfaceFlinger global state
4630 */
4631
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004632 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004633 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004634 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004635
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004636 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004637
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004638 DebugEGLImageTracker::getInstance()->dump(result);
4639
Dominik Laskowski075d3172018-05-24 15:50:06 -07004640 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004641 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4642 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004643 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4644 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004645 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004646 StringAppendF(&result,
4647 " transaction-flags : %08x\n"
4648 " gpu_to_cpu_unsupported : %d\n",
4649 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004650
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004651 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004652 displayId && getHwComposer().isConnected(*displayId)) {
4653 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004654 StringAppendF(&result,
4655 " refresh-rate : %f fps\n"
4656 " x-dpi : %f\n"
4657 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004658 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4659 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004660 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004661
Yiwei Zhang5434a782018-12-05 18:06:32 -08004662 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004663
Dan Stozae22aec72016-08-01 13:20:59 -07004664 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004665 * Tracing state
4666 */
4667 mTracing.dump(result);
4668 result.append("\n");
4669
4670 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004671 * HWC layer minidump
4672 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004673 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004674 const auto displayId = display->getId();
4675 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004676 continue;
4677 }
4678
Yiwei Zhang5434a782018-12-05 18:06:32 -08004679 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004680 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004681
4682 const DisplayDevice& ref = *display;
4683 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07004684 result.append("\n");
4685 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004686
4687 /*
4688 * Dump HWComposer state
4689 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004690 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004691 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004692 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004693 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004694 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004695 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004696
4697 /*
4698 * Dump gralloc state
4699 */
4700 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4701 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004702
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004703 result.append(mTimeStats->miniDump());
4704 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004705}
4706
Chia-I Wu28f320b2018-05-03 11:02:56 -07004707void SurfaceFlinger::updateColorMatrixLocked() {
4708 mat4 colorMatrix;
4709 if (mGlobalSaturationFactor != 1.0f) {
4710 // Rec.709 luma coefficients
4711 float3 luminance{0.213f, 0.715f, 0.072f};
4712 luminance *= 1.0f - mGlobalSaturationFactor;
4713 mat4 saturationMatrix = mat4(
4714 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4715 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4716 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4717 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4718 );
4719 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4720 } else {
4721 colorMatrix = mClientColorMatrix * mDaltonizer();
4722 }
4723
4724 if (mCurrentState.colorMatrix != colorMatrix) {
4725 mCurrentState.colorMatrix = colorMatrix;
4726 mCurrentState.colorMatrixChanged = true;
4727 setTransactionFlags(eTransactionNeeded);
4728 }
4729}
4730
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004731status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004732#pragma clang diagnostic push
4733#pragma clang diagnostic error "-Wswitch-enum"
4734 switch (static_cast<ISurfaceComposerTag>(code)) {
4735 // These methods should at minimum make sure that the client requested
4736 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004737 case BOOT_FINISHED:
4738 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004739 case CREATE_DISPLAY:
4740 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004741 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004742 case GET_ANIMATION_FRAME_STATS:
4743 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004744 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004745 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004746 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004747 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4748 case SET_AUTO_LOW_LATENCY_MODE:
4749 case GET_GAME_CONTENT_TYPE_SUPPORT:
4750 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004751 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004752 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004753 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004754 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004755 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004756 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004757 case SET_GLOBAL_SHADOW_SETTINGS:
4758 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4759 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4760 // necessary permission dynamically. Don't use the permission cache for this check.
4761 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4762 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004763 IPCThreadState* ipc = IPCThreadState::self();
4764 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4765 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004766 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004767 }
Robert Carr1db73f62016-12-21 12:58:51 -08004768 return OK;
4769 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004770 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004771 IPCThreadState* ipc = IPCThreadState::self();
4772 const int pid = ipc->getCallingPid();
4773 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004774 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4775 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004776 return PERMISSION_DENIED;
4777 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004778 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004779 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004780 // Used by apps to hook Choreographer to SurfaceFlinger.
4781 case CREATE_DISPLAY_EVENT_CONNECTION:
4782 // The following calls are currently used by clients that do not
4783 // request necessary permissions. However, they do not expose any secret
4784 // information, so it is OK to pass them.
4785 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004786 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004787 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004788 case GET_PHYSICAL_DISPLAY_IDS:
4789 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004790 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004791 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004792 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004793 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004794 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004795 case GET_DISPLAY_STATS:
4796 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4797 // Calling setTransactionState is safe, because you need to have been
4798 // granted a reference to Client* and Handle* to do anything with it.
4799 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004800 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004801 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004802 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004803 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004804 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004805 // setFrameRate() is deliberately available for apps to call without any
4806 // special permissions.
4807 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004808 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4809 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004810 return OK;
4811 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004812 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004813 case CAPTURE_SCREEN:
4814 case ADD_REGION_SAMPLING_LISTENER:
4815 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004816 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004817 IPCThreadState* ipc = IPCThreadState::self();
4818 const int pid = ipc->getCallingPid();
4819 const int uid = ipc->getCallingUid();
4820 if ((uid != AID_GRAPHICS) &&
4821 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4822 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4823 return PERMISSION_DENIED;
4824 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004825 return OK;
4826 }
chaviw93df2ea2019-04-30 16:45:12 -07004827 case CAPTURE_SCREEN_BY_ID: {
4828 IPCThreadState* ipc = IPCThreadState::self();
4829 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004830 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004831 return OK;
4832 }
4833 return PERMISSION_DENIED;
4834 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004835 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004836
4837 // These codes are used for the IBinder protocol to either interrogate the recipient
4838 // side of the transaction for its canonical interface descriptor or to dump its state.
4839 // We let them pass by default.
4840 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4841 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4842 code == IBinder::SYSPROPS_TRANSACTION) {
4843 return OK;
4844 }
Ady Abraham07e54702020-04-16 15:05:37 -07004845 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004846 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004847 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004848 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4849 return OK;
4850 }
4851 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4852 return PERMISSION_DENIED;
4853#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004854}
4855
Ana Krulec13be8ad2018-08-21 02:43:56 +00004856status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4857 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004858 status_t credentialCheck = CheckTransactCodeCredentials(code);
4859 if (credentialCheck != OK) {
4860 return credentialCheck;
4861 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004862
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004863 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4864 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004865 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004866 IPCThreadState* ipc = IPCThreadState::self();
4867 const int uid = ipc->getCallingUid();
4868 if (CC_UNLIKELY(uid != AID_SYSTEM
4869 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004870 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004871 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004872 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004873 return PERMISSION_DENIED;
4874 }
4875 int n;
4876 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004877 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004878 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004879 return NO_ERROR;
4880 case 1002: // SHOW_UPDATES
4881 n = data.readInt32();
4882 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004883 invalidateHwcGeometry();
4884 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004885 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004886 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004887 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004888 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004889 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004890 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004891 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004892 setTransactionFlags(
4893 eTransactionNeeded|
4894 eDisplayTransactionNeeded|
4895 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004896 return NO_ERROR;
4897 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004898 case 1006:{ // send empty update
4899 signalRefresh();
4900 return NO_ERROR;
4901 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004902 case 1008: // toggle use of hw composer
4903 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004904 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004905 invalidateHwcGeometry();
4906 repaintEverything();
4907 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004908 case 1009: // toggle use of transform hint
4909 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004910 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004911 invalidateHwcGeometry();
4912 repaintEverything();
4913 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004914 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004915 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004916 reply->writeInt32(0);
4917 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004918 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004919 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004920 return NO_ERROR;
4921 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004922 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004923 if (!display) {
4924 return NAME_NOT_FOUND;
4925 }
4926
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004927 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004928 return NO_ERROR;
4929 }
4930 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004931 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004932 // daltonize
4933 n = data.readInt32();
4934 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004935 case 1:
4936 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4937 break;
4938 case 2:
4939 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4940 break;
4941 case 3:
4942 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4943 break;
4944 default:
4945 mDaltonizer.setType(ColorBlindnessType::None);
4946 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004947 }
4948 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004949 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004950 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004951 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004952 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004953
4954 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004955 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004956 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004957 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004958 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004959 // apply a color matrix
4960 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004961 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004962 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004963 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004964 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004965 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004966 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004967 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004968 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004969 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004970 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004971
4972 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4973 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004974 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004975 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4976 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4977 }
4978
Chia-I Wu28f320b2018-05-03 11:02:56 -07004979 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004980 return NO_ERROR;
4981 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004982 case 1016: { // Unused.
4983 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004984 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004985 case 1017: {
4986 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004987 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004988 return NO_ERROR;
4989 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004990 case 1018: { // Modify Choreographer's phase offset
4991 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004992 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004993 return NO_ERROR;
4994 }
4995 case 1019: { // Modify SurfaceFlinger's phase offset
4996 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004997 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004998 return NO_ERROR;
4999 }
Irvel468051e2016-06-13 16:44:44 -07005000 case 1020: { // Layer updates interceptor
5001 n = data.readInt32();
5002 if (n) {
5003 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005004 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005005 }
5006 else{
5007 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005008 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005009 }
5010 return NO_ERROR;
5011 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005012 case 1021: { // Disable HWC virtual displays
5013 n = data.readInt32();
5014 mUseHwcVirtualDisplays = !n;
5015 return NO_ERROR;
5016 }
Romain Guy0147a172017-06-01 13:53:56 -07005017 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005018 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005019 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005020
Chia-I Wu28f320b2018-05-03 11:02:56 -07005021 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005022 return NO_ERROR;
5023 }
Romain Guy54f154a2017-10-24 21:40:32 +01005024 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005025 int32_t colorMode;
5026
Chia-I Wu0d711262018-05-21 15:19:35 -07005027 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005028 if (data.readInt32(&colorMode) == NO_ERROR) {
5029 mForceColorMode = static_cast<ColorMode>(colorMode);
5030 }
Romain Guy54f154a2017-10-24 21:40:32 +01005031 invalidateHwcGeometry();
5032 repaintEverything();
5033 return NO_ERROR;
5034 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005035 // Deprecate, use 1030 to check whether the device is color managed.
5036 case 1024: {
5037 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005038 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005039 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005040 n = data.readInt32();
5041 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005042 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005043 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005044 reply->writeInt32(NO_ERROR);
5045 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005046 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005047 mTracingEnabledChanged = mTracing.disable();
5048 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005049 reply->writeInt32(mTracing.writeToFile());
5050 } else {
5051 reply->writeInt32(NO_ERROR);
5052 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005053 }
5054 return NO_ERROR;
5055 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005056 case 1026: { // Get layer tracing status
5057 reply->writeBool(mTracing.isEnabled());
5058 return NO_ERROR;
5059 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005060 // Is a DisplayColorSetting supported?
5061 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005062 const auto display = getDefaultDisplayDevice();
5063 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005064 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005065 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005066
5067 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5068 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005069 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005070 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005071 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005072 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005073 reply->writeBool(true);
5074 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005075 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005076 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005077 break;
5078 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005079 reply->writeBool(
5080 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005081 break;
5082 }
5083 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005084 }
Alec Mouri64f03f52020-09-09 18:57:07 -07005085 case 1028: { // Unused.
5086 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005087 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005088 // Set buffer size for SF tracing (value in KB)
5089 case 1029: {
5090 n = data.readInt32();
5091 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5092 ALOGW("Invalid buffer size: %d KB", n);
5093 reply->writeInt32(BAD_VALUE);
5094 return BAD_VALUE;
5095 }
5096
5097 ALOGD("Updating trace buffer to %d KB", n);
5098 mTracing.setBufferSize(n * 1024);
5099 reply->writeInt32(NO_ERROR);
5100 return NO_ERROR;
5101 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005102 // Is device color managed?
5103 case 1030: {
5104 reply->writeBool(useColorManagement);
5105 return NO_ERROR;
5106 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005107 // Override default composition data space
5108 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5109 // && adb shell stop zygote && adb shell start zygote
5110 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5111 // adb shell stop zygote && adb shell start zygote
5112 case 1031: {
5113 Mutex::Autolock _l(mStateLock);
5114 n = data.readInt32();
5115 if (n) {
5116 n = data.readInt32();
5117 if (n) {
5118 Dataspace dataspace = static_cast<Dataspace>(n);
5119 if (!validateCompositionDataspace(dataspace)) {
5120 return BAD_VALUE;
5121 }
5122 mDefaultCompositionDataspace = dataspace;
5123 }
5124 n = data.readInt32();
5125 if (n) {
5126 Dataspace dataspace = static_cast<Dataspace>(n);
5127 if (!validateCompositionDataspace(dataspace)) {
5128 return BAD_VALUE;
5129 }
5130 mWideColorGamutCompositionDataspace = dataspace;
5131 }
5132 } else {
5133 // restore composition data space.
5134 mDefaultCompositionDataspace = defaultCompositionDataspace;
5135 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5136 }
5137 return NO_ERROR;
5138 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005139 // Set trace flags
5140 case 1033: {
5141 n = data.readUint32();
5142 ALOGD("Updating trace flags to 0x%x", n);
5143 mTracing.setTraceFlags(n);
5144 reply->writeInt32(NO_ERROR);
5145 return NO_ERROR;
5146 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005147 case 1034: {
Dominik Laskowski20134642020-04-20 22:36:44 -07005148 switch (n = data.readInt32()) {
5149 case 0:
5150 case 1:
5151 enableRefreshRateOverlay(static_cast<bool>(n));
5152 break;
5153 default: {
5154 Mutex::Autolock lock(mStateLock);
5155 reply->writeBool(mRefreshRateOverlay != nullptr);
5156 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005157 }
5158 return NO_ERROR;
5159 }
Ady Abraham34392f72019-04-10 11:29:27 -07005160 case 1035: {
5161 n = data.readInt32();
5162 mDebugDisplayConfigSetByBackdoor = false;
5163 if (n >= 0) {
5164 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005165 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005166 if (result != NO_ERROR) {
5167 return result;
5168 }
5169 mDebugDisplayConfigSetByBackdoor = true;
5170 }
5171 return NO_ERROR;
5172 }
Ady Abraham07e54702020-04-16 15:05:37 -07005173 case 1036: {
5174 if (data.readInt32() > 0) {
5175 status_t result =
5176 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5177 if (result != NO_ERROR) {
5178 return result;
5179 }
5180 } else {
5181 mDebugFrameRateFlexibilityToken = nullptr;
5182 }
5183 return NO_ERROR;
5184 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005185 }
5186 }
5187 return err;
5188}
5189
Steven Thomas6d8110b2017-08-31 18:24:21 -07005190void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005191 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005192 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005193}
5194
Ana Krulec7d1d6832018-12-27 11:10:09 -08005195void SurfaceFlinger::repaintEverythingForHWC() {
5196 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005197 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005198 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005199}
5200
Ady Abrahama09852a2020-02-20 14:23:42 -08005201void SurfaceFlinger::kernelTimerChanged(bool expired) {
5202 static bool updateOverlay =
5203 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005204 if (!updateOverlay) return;
5205 if (Mutex::Autolock lock(mStateLock); !mRefreshRateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005206
5207 // Update the overlay on the main thread to avoid race conditions with
5208 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowski20134642020-04-20 22:36:44 -07005209 static_cast<void>(schedule([=] {
5210 const auto desiredActiveConfig = getDesiredActiveConfig();
5211 const auto& current = desiredActiveConfig
5212 ? mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId)
5213 : mRefreshRateConfigs->getCurrentRefreshRate();
5214 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5215
5216 if (current != min) {
Ana Krulecb9afd792020-06-11 13:16:15 -07005217 const bool timerExpired = mKernelIdleTimerEnabled && expired;
Ady Abrahama09852a2020-02-20 14:23:42 -08005218
Dominik Laskowski20134642020-04-20 22:36:44 -07005219 if (Mutex::Autolock lock(mStateLock); mRefreshRateOverlay) {
Ady Abrahama09852a2020-02-20 14:23:42 -08005220 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
Ady Abrahama09852a2020-02-20 14:23:42 -08005221 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005222 mEventQueue->invalidate();
Ady Abrahama09852a2020-02-20 14:23:42 -08005223 }
5224 }));
5225}
5226
Ana Krulecb9afd792020-06-11 13:16:15 -07005227void SurfaceFlinger::toggleKernelIdleTimer() {
5228 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
5229
5230 // If the support for kernel idle timer is disabled in SF code, don't do anything.
5231 if (!mSupportKernelIdleTimer) {
5232 return;
5233 }
5234 const KernelIdleTimerAction action = mRefreshRateConfigs->getIdleTimerAction();
5235
5236 switch (action) {
5237 case KernelIdleTimerAction::TurnOff:
5238 if (mKernelIdleTimerEnabled) {
5239 ATRACE_INT("KernelIdleTimer", 0);
5240 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "false");
5241 mKernelIdleTimerEnabled = false;
5242 }
5243 break;
5244 case KernelIdleTimerAction::TurnOn:
5245 if (!mKernelIdleTimerEnabled) {
5246 ATRACE_INT("KernelIdleTimer", 1);
5247 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "true");
5248 mKernelIdleTimerEnabled = true;
5249 }
5250 break;
5251 case KernelIdleTimerAction::NoChange:
5252 break;
5253 }
5254}
5255
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005256// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5257class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005258public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005259 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5260 ~WindowDisconnector() {
5261 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005262 }
5263
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005264private:
5265 ANativeWindow* mWindow;
5266 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005267};
5268
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005269status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005270 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005271 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5272 const Rect& sourceCrop, uint32_t reqWidth,
5273 uint32_t reqHeight, bool useIdentityTransform,
5274 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005275 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005276
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005277 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005278
Dominik Laskowski718f9602019-11-09 20:01:35 -08005279 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5280 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5281 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5282 renderAreaRotation = ui::Transform::ROT_0;
5283 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005284
Chia-I Wu20261cb2018-08-23 12:55:44 -07005285 sp<DisplayDevice> display;
5286 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005287 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005288
Chia-I Wu20261cb2018-08-23 12:55:44 -07005289 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005290 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005291
Chia-I Wucb023152018-08-28 12:57:23 -07005292 // set the requested width/height to the logical display viewport size
5293 // by default
5294 if (reqWidth == 0 || reqHeight == 0) {
5295 reqWidth = uint32_t(display->getViewport().width());
5296 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005297 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005298 }
5299
Peiyong Lin0e003c92018-09-17 11:09:51 -07005300 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005301 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005302 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5303 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005304 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005305 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005306}
5307
chaviw93df2ea2019-04-30 16:45:12 -07005308static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5309 switch (colorMode) {
5310 case ColorMode::DISPLAY_P3:
5311 case ColorMode::BT2100_PQ:
5312 case ColorMode::BT2100_HLG:
5313 case ColorMode::DISPLAY_BT2020:
5314 return Dataspace::DISPLAY_P3;
5315 default:
5316 return Dataspace::V0_SRGB;
5317 }
5318}
5319
Martin Liu4a322352020-03-24 21:30:38 +08005320status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5321 static constexpr int kFifoPriority = 2;
5322 static constexpr int kOtherPriority = 0;
5323
5324 struct sched_param param = {0};
5325 int sched_policy;
5326 if (enabled) {
5327 sched_policy = SCHED_FIFO;
5328 param.sched_priority = kFifoPriority;
5329 } else {
5330 sched_policy = SCHED_OTHER;
5331 param.sched_priority = kOtherPriority;
5332 }
5333
5334 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5335 return -errno;
5336 }
5337 return NO_ERROR;
5338}
5339
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005340sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005341 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5342 if (displayToken) {
5343 return getDisplayDeviceLocked(displayToken);
5344 }
5345 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5346 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005347 return getDisplayByLayerStack(displayOrLayerStack);
5348}
5349
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005350sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005351 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005352 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005353 return display;
5354 }
5355 }
5356 return nullptr;
5357}
5358
5359status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5360 sp<GraphicBuffer>* outBuffer) {
5361 sp<DisplayDevice> display;
5362 uint32_t width;
5363 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005364 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005365 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005366 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005367 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5368 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005369 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005370 }
5371
5372 width = uint32_t(display->getViewport().width());
5373 height = uint32_t(display->getViewport().height());
5374
Dominik Laskowski718f9602019-11-09 20:01:35 -08005375 const auto orientation = display->getOrientation();
5376 captureOrientation = ui::Transform::toRotationFlags(orientation);
5377
5378 switch (captureOrientation) {
5379 case ui::Transform::ROT_90:
5380 captureOrientation = ui::Transform::ROT_270;
5381 break;
5382
5383 case ui::Transform::ROT_270:
5384 captureOrientation = ui::Transform::ROT_90;
5385 break;
5386
5387 case ui::Transform::ROT_INVALID:
5388 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5389 captureOrientation = ui::Transform::ROT_0;
5390 break;
5391
5392 default:
5393 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005394 }
chaviw93df2ea2019-04-30 16:45:12 -07005395 *outDataspace =
5396 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5397 }
5398
5399 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5400 false /* captureSecureLayers */);
5401
5402 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5403 std::placeholders::_1);
5404 bool ignored = false;
5405 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5406 false /* useIdentityTransform */,
5407 ignored /* outCapturedSecureLayers */);
5408}
5409
Robert Carr866455f2019-04-02 16:28:26 -07005410status_t SurfaceFlinger::captureLayers(
5411 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5412 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5413 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5414 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005415 ATRACE_CALL();
5416
5417 class LayerRenderArea : public RenderArea {
5418 public:
Robert Carr578038f2018-03-09 12:25:24 -08005419 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005420 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005421 bool childrenOnly, const Rect& displayViewport)
5422 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005423 mLayer(layer),
5424 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005425 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005426 mFlinger(flinger),
5427 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005428 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005429 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005430 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005431 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005432 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005433 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005434 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005435 }
chaviwa76b2712017-09-20 12:02:26 -07005436 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005437 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005438 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005439 Rect getSourceCrop() const override {
5440 if (mCrop.isEmpty()) {
5441 return getBounds();
5442 } else {
5443 return mCrop;
5444 }
5445 }
Robert Carr578038f2018-03-09 12:25:24 -08005446 class ReparentForDrawing {
5447 public:
5448 const sp<Layer>& oldParent;
5449 const sp<Layer>& newParent;
5450
Vishnu Nair4351ad52019-02-11 14:13:02 -08005451 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5452 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005453 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005454 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005455 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5456 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005457 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005458 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005459 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005460 };
5461
5462 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005463 const Rect sourceCrop = getSourceCrop();
5464 // no need to check rotation because there is none
5465 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5466 sourceCrop.height() != getReqHeight();
5467
Robert Carr578038f2018-03-09 12:25:24 -08005468 if (!mChildrenOnly) {
5469 mTransform = mLayer->getTransform().inverse();
5470 drawLayers();
5471 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005472 uint32_t w = static_cast<uint32_t>(getWidth());
5473 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005474 // In the "childrenOnly" case we reparent the children to a screenshot
5475 // layer which has no properties set and which does not draw.
5476 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005477 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5478 "Screenshot Parent"s, w, h, 0,
5479 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005480
Vishnu Nair4351ad52019-02-11 14:13:02 -08005481 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005482 drawLayers();
5483 }
5484 }
chaviwa76b2712017-09-20 12:02:26 -07005485
chaviwa76b2712017-09-20 12:02:26 -07005486 private:
chaviw7206d492017-11-10 16:16:12 -08005487 const sp<Layer> mLayer;
5488 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005489
Peiyong Linefefaac2018-08-17 12:27:51 -07005490 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005491 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005492
5493 SurfaceFlinger* mFlinger;
5494 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005495 };
5496
Robert Carrc0df3122019-04-11 13:18:21 -07005497 int reqWidth = 0;
5498 int reqHeight = 0;
5499 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005500 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005501 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005502 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005503 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005504 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005505
Alec Mouri9a02eda2020-04-21 17:39:34 -07005506 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005507 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5508 ALOGE("captureLayers called with an invalid or removed parent");
5509 return NAME_NOT_FOUND;
5510 }
5511
5512 const int uid = IPCThreadState::self()->getCallingUid();
5513 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5514 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5515 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5516 return PERMISSION_DENIED;
5517 }
5518
Vishnu Nairefc42e22019-12-03 17:36:12 -08005519 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005520 if (sourceCrop.width() <= 0) {
5521 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005522 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005523 }
5524
5525 if (sourceCrop.height() <= 0) {
5526 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005527 crop.bottom = parentSourceBounds.getHeight();
5528 }
5529
5530 if (crop.isEmpty() || frameScale <= 0.0f) {
5531 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5532 // crop was not specified, or an invalid frame scale was provided.
5533 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005534 }
5535 reqWidth = crop.width() * frameScale;
5536 reqHeight = crop.height() * frameScale;
5537
5538 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005539 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005540 if (excludeLayer != nullptr) {
5541 excludeLayers.emplace(excludeLayer);
5542 } else {
5543 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5544 return NAME_NOT_FOUND;
5545 }
5546 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005547
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005548 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005549 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005550 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005551 }
5552
5553 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005554 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005555
Chia-I Wu20261cb2018-08-23 12:55:44 -07005556 // really small crop or frameScale
5557 if (reqWidth <= 0) {
5558 reqWidth = 1;
5559 }
5560 if (reqHeight <= 0) {
5561 reqHeight = 1;
5562 }
5563
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005564 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5565 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005566 auto traverseLayers = [parent, childrenOnly,
5567 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005568 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5569 if (!layer->isVisible()) {
5570 return;
Robert Carr578038f2018-03-09 12:25:24 -08005571 } else if (childrenOnly && layer == parent.get()) {
5572 return;
chaviwa76b2712017-09-20 12:02:26 -07005573 }
Robert Carr866455f2019-04-02 16:28:26 -07005574
5575 sp<Layer> p = layer;
5576 while (p != nullptr) {
5577 if (excludeLayers.count(p) != 0) {
5578 return;
5579 }
5580 p = p->getParent();
5581 }
5582
chaviwa76b2712017-09-20 12:02:26 -07005583 visitor(layer);
5584 });
5585 };
Robert Carr108b2c72019-04-02 16:32:58 -07005586
5587 bool outCapturedSecureLayers = false;
5588 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5589 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005590}
5591
5592status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5593 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005594 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005595 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005596 bool useIdentityTransform,
5597 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005598 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005599
Peiyong Lin0e003c92018-09-17 11:09:51 -07005600 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005601 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
Richard Liu11a11052020-04-08 10:51:55 +00005602 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_COMPOSER;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005603 *outBuffer =
5604 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5605 static_cast<android_pixel_format>(reqPixelFormat), 1,
5606 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005607
Robert Carr108b2c72019-04-02 16:32:58 -07005608 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005609 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005610}
5611
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005612status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5613 TraverseLayersFunction traverseLayers,
5614 const sp<GraphicBuffer>& buffer,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005615 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005616 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005617 const int uid = IPCThreadState::self()->getCallingUid();
5618 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5619
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005620 status_t result;
5621 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005622
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005623 do {
5624 std::tie(result, syncFd) =
5625 schedule([&] {
5626 if (mRefreshPending) {
5627 ATRACE_NAME("Skipping screenshot for now");
5628 return std::make_pair(EAGAIN, -1);
5629 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005630
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005631 status_t result = NO_ERROR;
5632 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005633
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005634 Mutex::Autolock lock(mStateLock);
5635 renderArea.render([&] {
5636 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5637 useIdentityTransform, forSystem, &fd,
5638 regionSampling, outCapturedSecureLayers);
5639 });
5640
5641 return std::make_pair(result, fd);
5642 }).get();
5643 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005644
5645 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005646 sync_wait(syncFd, -1);
5647 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005648 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005649
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005650 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005651}
5652
chaviwa76b2712017-09-20 12:02:26 -07005653void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005654 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005655 ANativeWindowBuffer* buffer, bool useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005656 bool regionSampling, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005657 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005658
chaviwa76b2712017-09-20 12:02:26 -07005659 const auto reqWidth = renderArea.getReqWidth();
5660 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005661 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005662 const auto transform = renderArea.getTransform();
5663 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005664 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005665
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005666 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005667 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005668
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005669 // assume that bounds are never offset, and that they are the same as the
5670 // buffer bounds.
5671 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005672 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005673 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005674
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005675 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5676 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005677
chaviw50da5042018-04-09 13:49:37 -07005678 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005679
Vishnu Nair9b079a22020-01-21 14:36:08 -08005680 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005681 fillLayer.source.buffer.buffer = nullptr;
5682 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005683 fillLayer.geometry.boundaries =
5684 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005685 fillLayer.alpha = half(alpha);
5686 clientCompositionLayers.push_back(fillLayer);
5687
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005688 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08005689 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005690 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005691 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005692 const bool supportProtectedContent = false;
5693 Region clip(renderArea.getBounds());
5694 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5695 clip,
5696 useIdentityTransform,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005697 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07005698 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005699 renderArea.isSecure(),
5700 supportProtectedContent,
5701 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005702 displayViewport,
5703 clientCompositionDisplay.outputDataspace,
5704 true, /* realContentIsVisible */
5705 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005706 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005707 std::vector<compositionengine::LayerFE::LayerSettings> results =
5708 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005709 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005710 for (auto& settings : results) {
5711 settings.geometry.positionTransform =
5712 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupinf11eba52020-04-20 18:42:31 -07005713 // There's no need to process blurs when we're executing region sampling,
5714 // we're just trying to understand what we're drawing, and doing so without
5715 // blurs is already a pretty good approximation.
5716 if (regionSampling) {
5717 settings.backgroundBlurRadius = 0;
5718 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005719 }
Yichi Chen40773d92020-04-01 10:10:18 +08005720 clientCompositionLayers.insert(clientCompositionLayers.end(),
5721 std::make_move_iterator(results.begin()),
5722 std::make_move_iterator(results.end()));
5723 renderedLayers.push_back(layer);
5724 }
chaviwa76b2712017-09-20 12:02:26 -07005725 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005726
Yichi Chen40773d92020-04-01 10:10:18 +08005727 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5728 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005729 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005730 clientCompositionLayerPointers.begin(),
5731 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005732
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005733 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005734 // Use an empty fence for the buffer fence, since we just created the buffer so
5735 // there is no need for synchronization with the GPU.
5736 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005737 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005738 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005739 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005740 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005741
5742 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005743
5744 if (*outSyncFd >= 0) {
5745 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5746 for (auto* layer : renderedLayers) {
5747 layer->onLayerDisplayed(releaseFence);
5748 }
5749 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005750}
5751
chaviwa76b2712017-09-20 12:02:26 -07005752status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5753 TraverseLayersFunction traverseLayers,
5754 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005755 bool useIdentityTransform, bool forSystem,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005756 int* outSyncFd, bool regionSampling,
5757 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005758 ATRACE_CALL();
5759
chaviwa76b2712017-09-20 12:02:26 -07005760 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005761 outCapturedSecureLayers =
5762 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005763 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005764
Robert Carr03480e22018-01-04 16:02:06 -08005765 // We allow the system server to take screenshots of secure layers for
5766 // use in situations like the Screen-rotation animation and place
5767 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005768 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005769 ALOGW("FB is protected: PERMISSION_DENIED");
5770 return PERMISSION_DENIED;
5771 }
Lucas Dupinf11eba52020-04-20 18:42:31 -07005772 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5773 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005774 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005775}
5776
chaviw95ef3c42019-02-14 10:55:09 -08005777void SurfaceFlinger::setInputWindowsFinished() {
5778 Mutex::Autolock _l(mStateLock);
5779
5780 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005781
chaviw95ef3c42019-02-14 10:55:09 -08005782 mTransactionCV.broadcast();
5783}
chaviw5f21a5e2019-02-14 10:00:34 -08005784
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005785// ---------------------------------------------------------------------------
5786
Edgar Arriaga844fa672020-01-16 14:21:42 -08005787void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5788 layersSortedByZ.traverse(visitor);
5789}
5790
Dan Stoza412903f2017-04-27 13:42:17 -07005791void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5792 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005793}
5794
Dan Stoza412903f2017-04-27 13:42:17 -07005795void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5796 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005797}
5798
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005799void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005800 const LayerVector::Visitor& visitor) {
5801 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005802 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005803 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005804 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005805 continue;
5806 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005807 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005808 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005809 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005810 return;
5811 }
chaviwa76b2712017-09-20 12:02:26 -07005812 if (!layer->isVisible()) {
5813 return;
5814 }
5815 visitor(layer);
5816 });
5817 }
5818}
5819
Steven Thomasd4071902020-03-24 16:02:53 -07005820status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5821 const sp<DisplayDevice>& display,
5822 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005823 Mutex::Autolock lock(mStateLock);
5824
Steven Thomasd4071902020-03-24 16:02:53 -07005825 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5826 "Can only set override policy on the primary display");
5827 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5828
Dominik Laskowski22488f62019-03-28 09:53:04 -07005829 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005830 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5831 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5832 // it should go thru setDesiredActiveConfig, similar to primary display.
5833 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5834 const auto displayId = display->getId();
5835 LOG_ALWAYS_FATAL_IF(!displayId);
5836
Peiyong Line9d809e2020-04-14 13:10:48 -07005837 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005838 constraints.desiredTimeNanos = systemTime();
5839 constraints.seamlessRequired = false;
5840
Peiyong Line9d809e2020-04-14 13:10:48 -07005841 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005842 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5843 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005844 constraints, &timeline) < 0) {
5845 return BAD_VALUE;
5846 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005847 if (timeline.refreshRequired) {
5848 repaintEverythingForHWC();
5849 }
5850
Steven Thomasd4071902020-03-24 16:02:53 -07005851 display->setActiveConfig(policy->defaultConfig);
5852 const nsecs_t vsyncPeriod = getHwComposer()
5853 .getConfigs(*displayId)[policy->defaultConfig.value()]
5854 ->getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07005855 mScheduler->onNonPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
5856 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005857 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005858 }
5859
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005860 if (mDebugDisplayConfigSetByBackdoor) {
5861 // ignore this request as config is overridden by backdoor
5862 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005863 }
5864
Steven Thomasd4071902020-03-24 16:02:53 -07005865 status_t setPolicyResult = overridePolicy
5866 ? mRefreshRateConfigs->setOverridePolicy(policy)
5867 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5868 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005869 return BAD_VALUE;
5870 }
Steven Thomasd4071902020-03-24 16:02:53 -07005871 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005872 return NO_ERROR;
5873 }
Steven Thomasd4071902020-03-24 16:02:53 -07005874 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005875
Steven Thomasf734df42020-04-13 21:09:28 -07005876 ALOGV("Setting desired display config specs: defaultConfig: %d primaryRange: [%.0f %.0f]"
5877 " expandedRange: [%.0f %.0f]",
5878 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
5879 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
5880 currentPolicy.appRequestRange.max);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005881
Ana Krulecb9afd792020-06-11 13:16:15 -07005882 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
5883 // be depending in this callback.
Alec Mouri60aee1c2019-10-28 16:18:59 -07005884 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005885 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5886 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07005887 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
5888 display->getActiveConfig(), vsyncPeriod);
Ana Krulecb9afd792020-06-11 13:16:15 -07005889 toggleKernelIdleTimer();
Ady Abraham838de062019-02-04 10:24:03 -08005890
Ana Krulec3f6a2062020-01-23 15:48:01 -08005891 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005892 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005893 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5894 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005895 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005896 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005897 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005898
Ady Abrahamabc27602020-04-08 17:20:29 -07005899 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5900 ALOGV("switching to Scheduler preferred config %d",
5901 preferredRefreshRate.getConfigId().value());
5902 setDesiredActiveConfig(
5903 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005904 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005905 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5906 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005907 }
5908
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005909 return NO_ERROR;
5910}
5911
Ana Krulec0782b882019-10-15 17:34:54 -07005912status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Steven Thomasf734df42020-04-13 21:09:28 -07005913 int32_t defaultConfig,
5914 float primaryRefreshRateMin,
5915 float primaryRefreshRateMax,
5916 float appRequestRefreshRateMin,
5917 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07005918 ATRACE_CALL();
5919
5920 if (!displayToken) {
5921 return BAD_VALUE;
5922 }
5923
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005924 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005925 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01005926 if (!display) {
5927 ALOGE("Attempt to set desired display configs for invalid display token %p",
5928 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005929 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01005930 } else if (display->isVirtual()) {
5931 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005932 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01005933 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005934 using Policy = scheduler::RefreshRateConfigs::Policy;
Steven Thomasf734df42020-04-13 21:09:28 -07005935 const Policy policy{HwcConfigIndexType(defaultConfig),
5936 {primaryRefreshRateMin, primaryRefreshRateMax},
5937 {appRequestRefreshRateMin, appRequestRefreshRateMax}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005938 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005939
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005940 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
5941 }
5942 });
5943
5944 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01005945}
5946
5947status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005948 int32_t* outDefaultConfig,
Steven Thomasf734df42020-04-13 21:09:28 -07005949 float* outPrimaryRefreshRateMin,
5950 float* outPrimaryRefreshRateMax,
5951 float* outAppRequestRefreshRateMin,
5952 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01005953 ATRACE_CALL();
5954
Steven Thomasf734df42020-04-13 21:09:28 -07005955 if (!displayToken || !outDefaultConfig || !outPrimaryRefreshRateMin ||
5956 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01005957 return BAD_VALUE;
5958 }
5959
5960 Mutex::Autolock lock(mStateLock);
5961 const auto display = getDisplayDeviceLocked(displayToken);
5962 if (!display) {
5963 return NAME_NOT_FOUND;
5964 }
5965
5966 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07005967 scheduler::RefreshRateConfigs::Policy policy =
5968 mRefreshRateConfigs->getDisplayManagerPolicy();
5969 *outDefaultConfig = policy.defaultConfig.value();
Steven Thomasf734df42020-04-13 21:09:28 -07005970 *outPrimaryRefreshRateMin = policy.primaryRange.min;
5971 *outPrimaryRefreshRateMax = policy.primaryRange.max;
5972 *outAppRequestRefreshRateMin = policy.appRequestRange.min;
5973 *outAppRequestRefreshRateMax = policy.appRequestRange.max;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005974 return NO_ERROR;
5975 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005976 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005977 } else {
5978 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005979 LOG_FATAL_IF(!displayId);
5980
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005981 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5982 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
Steven Thomasf734df42020-04-13 21:09:28 -07005983 *outPrimaryRefreshRateMin = 1e9f / vsyncPeriod;
5984 *outPrimaryRefreshRateMax = 1e9f / vsyncPeriod;
5985 *outAppRequestRefreshRateMin = 1e9f / vsyncPeriod;
5986 *outAppRequestRefreshRateMax = 1e9f / vsyncPeriod;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005987 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005988 }
Ana Krulec0782b882019-10-15 17:34:54 -07005989}
5990
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005991void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005992 mFlinger->setInputWindowsFinished();
5993}
5994
Alec Mouri9a02eda2020-04-21 17:39:34 -07005995wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5996 Mutex::Autolock _l(mStateLock);
5997 return fromHandleLocked(handle);
5998}
5999
6000wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006001 BBinder* b = nullptr;
6002 if (handle) {
6003 b = handle->localBinder();
6004 }
Robert Carrc0df3122019-04-11 13:18:21 -07006005 if (b == nullptr) {
6006 return nullptr;
6007 }
6008 auto it = mLayersByLocalBinderToken.find(b);
6009 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006010 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006011 }
6012 return nullptr;
6013}
6014
Dominik Laskowski75848362019-11-11 17:57:20 -08006015void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006016 mNumLayers++;
6017 mScheduler->registerLayer(layer);
6018}
6019
6020void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6021 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006022 removeFromOffscreenLayers(layer);
6023}
6024
6025// WARNING: ONLY CALL THIS FROM LAYER DTOR
6026// Here we add children in the current state to offscreen layers and remove the
6027// layer itself from the offscreen layer list. Since
6028// this is the dtor, it is safe to access the current state. This keeps us
6029// from dangling children layers such that they are not reachable from the
6030// Drawing state nor the offscreen layer list
6031// See b/141111965
6032void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6033 for (auto& child : layer->getCurrentChildren()) {
6034 mOffscreenLayers.emplace(child.get());
6035 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006036 mOffscreenLayers.erase(layer);
6037}
6038
Alec Mouri4545a8a2019-08-08 20:05:32 -07006039void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6040 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6041}
6042
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006043status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6044 float lightPosY, float lightPosZ,
6045 float lightRadius) {
6046 Mutex::Autolock _l(mStateLock);
6047 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6048 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6049 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6050 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6051 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6052
6053 // these values are overridden when calculating the shadow settings for a layer.
6054 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6055 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006056 return NO_ERROR;
6057}
6058
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006059const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6060 const {
6061 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6062 // on the work to remove the table in that bug rather than adding more to
6063 // it.
6064 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006065 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6066 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6067 };
6068 return genericLayerMetadataKeyMap;
6069}
6070
Steven Thomas62a4cf82020-01-31 12:04:03 -08006071status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6072 int8_t compatibility) {
6073 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6074 return BAD_VALUE;
6075 }
6076
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006077 static_cast<void>(schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006078 Mutex::Autolock lock(mStateLock);
6079 if (authenticateSurfaceTextureLocked(surface)) {
6080 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
Ady Abraham162f6432020-10-08 18:40:47 +00006081 if (layer == nullptr) {
6082 ALOGE("Attempt to set frame rate on a layer that no longer exists");
6083 return BAD_VALUE;
6084 }
6085
Ady Abraham60e42ea2020-03-09 19:17:31 -07006086 if (layer->setFrameRate(
6087 Layer::FrameRate(frameRate,
6088 Layer::FrameRate::convertCompatibility(compatibility)))) {
6089 setTransactionFlags(eTraversalNeeded);
6090 }
6091 } else {
6092 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6093 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006094 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006095 return NO_ERROR;
6096 }));
6097
Steven Thomas62a4cf82020-01-31 12:04:03 -08006098 return NO_ERROR;
6099}
6100
Steven Thomasd4071902020-03-24 16:02:53 -07006101status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6102 if (!outToken) {
6103 return BAD_VALUE;
6104 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006105
6106 auto future = schedule([this] {
6107 status_t result = NO_ERROR;
6108 sp<IBinder> token;
6109
Steven Thomasd4071902020-03-24 16:02:53 -07006110 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006111 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Steven Thomasd4071902020-03-24 16:02:53 -07006112
6113 // This is a little racy, but not in a way that hurts anything. As we grab the
6114 // defaultConfig from the display manager policy, we could be setting a new display
6115 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6116 // matter for the override policy though, since we set allowGroupSwitching to true, so
6117 // it's not a problem.
6118 scheduler::RefreshRateConfigs::Policy overridePolicy;
6119 overridePolicy.defaultConfig =
6120 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6121 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006122 constexpr bool kOverridePolicy = true;
6123 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006124 }
6125
6126 if (result == NO_ERROR) {
6127 mFrameRateFlexibilityTokenCount++;
6128 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6129 // below, is something to consider carefully. The lifetime of the
6130 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6131 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6132 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6133 // in this case, for two reasons:
6134 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6135 // the program exits is via a crash. So we won't have a situation where the
6136 // SurfaceFlinger object is dead but the process is still up.
6137 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6138 // if condition 1 were changed, the problem would only show up when running CTS tests,
6139 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006140 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006141 [this]() { onFrameRateFlexibilityTokenReleased(); });
6142 ALOGD("Frame rate flexibility token acquired. count=%d",
6143 mFrameRateFlexibilityTokenCount);
6144 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006145
6146 return std::make_pair(result, token);
6147 });
6148
6149 status_t result;
6150 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006151 return result;
6152}
6153
6154void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006155 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006156 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6157 "Failed tracking frame rate flexibility tokens");
6158 mFrameRateFlexibilityTokenCount--;
6159 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6160 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006161 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006162 constexpr bool kOverridePolicy = true;
6163 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006164 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6165 }
6166 }));
6167}
6168
Dominik Laskowski20134642020-04-20 22:36:44 -07006169void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
6170 static_cast<void>(schedule([=] {
6171 std::unique_ptr<RefreshRateOverlay> overlay;
6172 if (enable) {
6173 overlay = std::make_unique<RefreshRateOverlay>(*this);
6174 }
6175
6176 {
6177 Mutex::Autolock lock(mStateLock);
6178
6179 // Destroy the layer of the current overlay, if any, outside the lock.
6180 mRefreshRateOverlay.swap(overlay);
6181 if (!mRefreshRateOverlay) return;
6182
6183 if (const auto display = getDefaultDisplayDeviceLocked()) {
6184 mRefreshRateOverlay->setViewport(display->getSize());
6185 }
6186
6187 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
6188 }
6189 }));
6190}
6191
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006192} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006193
Mathias Agopian3f844832013-08-07 21:24:32 -07006194#if defined(__gl_h_)
6195#error "don't include gl/gl.h in this file"
6196#endif
6197
6198#if defined(__gl2_h_)
6199#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006200#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006201
6202// TODO(b/129481165): remove the #pragma below and fix conversion issues
6203#pragma clang diagnostic pop // ignored "-Wconversion"