blob: c4c362655d31be3d7a2f13570934e9984514fa02 [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 }
Robert Carr720e5062018-07-30 17:45:14 -0700599 sp<IBinder> input(defaultServiceManager()->getService(
600 String16("inputflinger")));
601 if (input == nullptr) {
602 ALOGE("Failed to link to input service");
603 } else {
604 mInputFlinger = interface_cast<IInputFlinger>(input);
605 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700606
607 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700608 // formerly we would just kill the process, but we now ask it to exit so it
609 // can choose where to stop the animation.
610 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700611
612 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
613 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
614 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700615
Dominik Laskowski20134642020-04-20 22:36:44 -0700616 static_cast<void>(schedule([this] {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800617 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700618 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800619 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800620
Ady Abraham8a82ba62020-01-17 12:43:17 -0800621 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700622 enableRefreshRateOverlay(true);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800623 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800624 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800625}
626
Dan Stoza436ccf32018-06-21 12:10:12 -0700627uint32_t SurfaceFlinger::getNewTexture() {
628 {
629 std::lock_guard lock(mTexturePoolMutex);
630 if (!mTexturePool.empty()) {
631 uint32_t name = mTexturePool.back();
632 mTexturePool.pop_back();
633 ATRACE_INT("TexturePoolSize", mTexturePool.size());
634 return name;
635 }
636
637 // The pool was too small, so increase it for the future
638 ++mTexturePoolSize;
639 }
640
641 // The pool was empty, so we need to get a new texture name directly using a
642 // blocking call to the main thread
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700643 return schedule([this] {
644 uint32_t name = 0;
645 getRenderEngine().genTextures(1, &name);
646 return name;
647 })
648 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700649}
650
Mathias Agopian3f844832013-08-07 21:24:32 -0700651void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700652 std::lock_guard lock(mTexturePoolMutex);
653 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
654 // to actually delete this or not based on mTexturePoolSize
655 mTexturePool.push_back(texture);
656 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700657}
658
Wei Wangf9b05ee2017-07-19 20:59:39 -0700659// Do not call property_set on main thread which will be blocked by init
660// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700661void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700662 ALOGI( "SurfaceFlinger's main thread ready to run. "
663 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700664 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800665
Steven Thomasb02664d2017-07-26 18:48:28 -0700666 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700667 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800668 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700669 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
670 renderengine::RenderEngineCreationArgs::Builder()
671 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
672 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
673 .setUseColorManagerment(useColorManagement)
674 .setEnableProtectedContext(enable_protected_contents(false))
675 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700676 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700677 .setContextPriority(useContextPriority
678 ? renderengine::RenderEngine::ContextPriority::HIGH
679 : renderengine::RenderEngine::ContextPriority::MEDIUM)
680 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800681 mCompositionEngine->setTimeStats(mTimeStats);
Lloyd Pique441d5042018-10-18 16:49:51 -0700682 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800683 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800684 // Process any initial hotplug and resulting display changes.
685 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700686 const auto display = getDefaultDisplayDeviceLocked();
687 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700688 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700689 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800690
Mathias Agopian92a979a2012-08-02 18:32:23 -0700691 // initialize our drawing state
692 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700693
Andy McFadden13a082e2012-08-24 10:16:42 -0700694 // set initial conditions (e.g. unblank default device)
695 initializeDisplays();
696
Steven Thomas137d4bc2019-07-25 16:55:14 -0700697 char primeShaderCache[PROPERTY_VALUE_MAX];
698 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
699 if (atoi(primeShaderCache)) {
700 getRenderEngine().primeCache();
701 }
Dan Stoza4e637772016-07-28 13:31:51 -0700702
Wei Wangf9b05ee2017-07-19 20:59:39 -0700703 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700704
705 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700706 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700707 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700708
709 if (mStartPropertySetThread->Start() != NO_ERROR) {
710 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800711 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800712
Dan Stoza9e56aa02015-11-02 13:00:03 -0800713 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700714}
715
Romain Guy11d63f42017-07-20 12:47:14 -0700716void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700717 Mutex::Autolock _l(mStateLock);
718
Romain Guy11d63f42017-07-20 12:47:14 -0700719 char value[PROPERTY_VALUE_MAX];
720
721 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800722 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700723 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800724 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100725
726 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700727 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800728
729 property_get("persist.sys.sf.color_mode", value, "0");
730 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700731
732 property_get("persist.sys.sf.disable_blurs", value, "0");
733 bool disableBlurs = atoi(value);
734 mDisableBlurs = disableBlurs;
735 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700736}
737
Mathias Agopiana67e4182012-06-19 17:26:12 -0700738void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800739 // Start boot animation service by setting a property mailbox
740 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700741 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800742 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 if (mStartPropertySetThread->join() != NO_ERROR) {
744 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800745 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700746}
747
Mathias Agopian875d8e12013-06-07 15:35:48 -0700748size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700749 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700750}
751
Mathias Agopian875d8e12013-06-07 15:35:48 -0700752size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700753 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700754}
755
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800756// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800757
Jamie Gennis582270d2011-08-17 18:19:00 -0700758bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800759 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800760 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800761 return authenticateSurfaceTextureLocked(bufferProducer);
762}
763
764bool SurfaceFlinger::authenticateSurfaceTextureLocked(
765 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800766 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800767 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800768}
769
Brian Anderson6b376712017-04-04 10:51:39 -0700770status_t SurfaceFlinger::getSupportedFrameTimestamps(
771 std::vector<FrameEvent>* outSupported) const {
772 *outSupported = {
773 FrameEvent::REQUESTED_PRESENT,
774 FrameEvent::ACQUIRE,
775 FrameEvent::LATCH,
776 FrameEvent::FIRST_REFRESH_START,
777 FrameEvent::LAST_REFRESH_START,
778 FrameEvent::GPU_COMPOSITION_DONE,
779 FrameEvent::DEQUEUE_READY,
780 FrameEvent::RELEASE,
781 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700782 ConditionalLock _l(mStateLock,
783 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700784 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700785 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
786 }
787 return NO_ERROR;
788}
789
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800790status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
791 if (!displayToken || !state) {
792 return BAD_VALUE;
793 }
794
795 Mutex::Autolock lock(mStateLock);
796
797 const auto display = getDisplayDeviceLocked(displayToken);
798 if (!display) {
799 return NAME_NOT_FOUND;
800 }
801
802 state->layerStack = display->getLayerStack();
803 state->orientation = display->getOrientation();
804
805 const Rect viewport = display->getViewport();
806 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
807
808 return NO_ERROR;
809}
810
811status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
812 if (!displayToken || !info) {
813 return BAD_VALUE;
814 }
815
816 Mutex::Autolock lock(mStateLock);
817
818 const auto display = getDisplayDeviceLocked(displayToken);
819 if (!display) {
820 return NAME_NOT_FOUND;
821 }
822
Dominik Laskowski55c85402020-01-21 16:25:47 -0800823 if (const auto connectionType = display->getConnectionType())
824 info->connectionType = *connectionType;
825 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800826 return INVALID_OPERATION;
827 }
828
829 if (mEmulatedDisplayDensity) {
830 info->density = mEmulatedDisplayDensity;
831 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800832 info->density = info->connectionType == DisplayConnectionType::Internal
833 ? mInternalDisplayDensity
834 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800835 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700836 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800837
838 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200839 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800840
841 return NO_ERROR;
842}
843
Dominik Laskowski22488f62019-03-28 09:53:04 -0700844status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800845 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700846 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 return BAD_VALUE;
848 }
849
Dominik Laskowski22488f62019-03-28 09:53:04 -0700850 Mutex::Autolock lock(mStateLock);
851
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800852 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700853 if (!displayId) {
854 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700855 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700856
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800857 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700858
Dan Stoza7f7da322014-05-02 15:26:25 -0700859 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700860
Dominik Laskowski075d3172018-05-24 15:50:06 -0700861 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800862 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700863
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800864 auto width = hwConfig->getWidth();
865 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700866
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800867 auto xDpi = hwConfig->getDpiX();
868 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700869
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800870 if (isInternal &&
871 (internalDisplayOrientation == ui::ROTATION_90 ||
872 internalDisplayOrientation == ui::ROTATION_270)) {
873 std::swap(width, height);
874 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 }
876
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800877 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800878
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800879 if (mEmulatedDisplayDensity) {
880 config.xDpi = mEmulatedDisplayDensity;
881 config.yDpi = mEmulatedDisplayDensity;
882 } else {
883 config.xDpi = xDpi;
884 config.yDpi = yDpi;
885 }
886
887 const nsecs_t period = hwConfig->getVsyncPeriod();
888 config.refreshRate = 1e9f / period;
889
890 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
891 config.appVsyncOffset = offsets.late.app;
892 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800893 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894
Andy McFadden91b2ca82014-06-13 14:04:23 -0700895 // This is how far in advance a buffer must be queued for
896 // presentation at a given time. If you want a buffer to appear
897 // on the screen at time N, you must submit the buffer before
898 // (N - presentationDeadline).
899 //
900 // Normally it's one full refresh period (to give SF a chance to
901 // latch the buffer), but this can be reduced by configuring a
902 // DispSync offset. Any additional delays introduced by the hardware
903 // composer or panel must be accounted for here.
904 //
905 // We add an additional 1ms to allow for processing time and
906 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800907 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700908
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800909 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700910 }
911
Dan Stoza7f7da322014-05-02 15:26:25 -0700912 return NO_ERROR;
913}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700914
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700915status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
916 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700917 return BAD_VALUE;
918 }
919
Ana Krulecc2870422019-01-29 19:00:58 -0800920 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700921 return NO_ERROR;
922}
923
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700925 int activeConfig;
926 bool isPrimary;
927
928 {
929 Mutex::Autolock lock(mStateLock);
930
931 if (const auto display = getDisplayDeviceLocked(displayToken)) {
932 activeConfig = display->getActiveConfig().value();
933 isPrimary = display->isPrimary();
934 } else {
935 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
936 return NAME_NOT_FOUND;
937 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800938 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700939
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700940 if (isPrimary) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700941 if (const auto config = getDesiredActiveConfig()) {
942 return config->configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700943 }
Steven Thomasc9098452019-09-30 17:15:05 -0700944 }
Ady Abraham2139f732019-11-13 18:56:40 -0800945
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700946 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700947}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700948
Ady Abraham03b02dd2019-03-21 15:40:11 -0700949void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800950 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800951 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700952 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800953
Ady Abrahamb838aed2019-02-12 15:30:16 -0800954 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800955 if (mDesiredActiveConfigChanged) {
956 // If a config change is pending, just cache the latest request in
957 // mDesiredActiveConfig
958 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
959 mDesiredActiveConfig = info;
960 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
961 } else {
962 // Check is we are already at the desired config
963 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700964 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800965 return;
966 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800967
Ady Abraham59db0a32020-03-02 18:04:20 -0800968 // Initiate a config change.
969 mDesiredActiveConfigChanged = true;
970 mDesiredActiveConfig = info;
971
Ady Abrahamb838aed2019-02-12 15:30:16 -0800972 // This will trigger HWC refresh without resetting the idle timer.
973 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700974 // Start receiving vsync samples now, so that we can detect a period
975 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700976 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700977 // As we called to set period, we will call to onRefreshRateChangeCompleted once
978 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700979 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800980
Ady Abrahamabc27602020-04-08 17:20:29 -0700981 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800982 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -0700983 mScheduler->setConfigChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800984 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700985
986 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800987 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700988 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989}
990
991status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
992 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800993
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100994 if (!displayToken) {
995 return BAD_VALUE;
996 }
Ady Abraham838de062019-02-04 10:24:03 -0800997
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700998 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -0700999 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001000 if (!display) {
1001 ALOGE("Attempt to set allowed display configs for invalid display token %p",
1002 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001003 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001004 } else if (display->isVirtual()) {
1005 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001006 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001007 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001008 const HwcConfigIndexType config(mode);
1009 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
Steven Thomasf734df42020-04-13 21:09:28 -07001010 const scheduler::RefreshRateConfigs::Policy policy{config, {fps, fps}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001011 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001012
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001013 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1014 }
1015 });
1016
1017 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001018}
1019
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020void SurfaceFlinger::setActiveConfigInternal() {
1021 ATRACE_CALL();
1022
Dominik Laskowski22488f62019-03-28 09:53:04 -07001023 const auto display = getDefaultDisplayDeviceLocked();
1024 if (!display) {
1025 return;
1026 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001027
Alec Mouri8de697e2020-03-19 10:52:01 -07001028 auto& oldRefreshRate =
1029 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1030
Dominik Laskowski22488f62019-03-28 09:53:04 -07001031 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001032 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001033 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001034 display->setActiveConfig(mUpcomingActiveConfig.configId);
1035
Ady Abraham2e1dd892020-03-05 13:48:36 -08001036 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001037 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001038 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001039 mTimeStats->incrementRefreshRateSwitches();
1040 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001041 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001042 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001043 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001044
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001045 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001046 const nsecs_t vsyncPeriod =
1047 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001048 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001049 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
1050 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001051 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001052}
1053
Ady Abraham53852a52019-05-28 18:07:44 -07001054void SurfaceFlinger::desiredActiveConfigChangeDone() {
1055 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1056 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1057 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001058
Ady Abraham2e1dd892020-03-05 13:48:36 -08001059 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001060 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001061 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1062 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001063 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001064 mScheduler->setConfigChangePending(false);
Ady Abraham53852a52019-05-28 18:07:44 -07001065}
1066
Ady Abraham27cbed72020-04-10 12:56:59 -07001067void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001068 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001069 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001070 // Store the local variable to release the lock.
Dominik Laskowski20134642020-04-20 22:36:44 -07001071 const auto desiredActiveConfig = getDesiredActiveConfig();
Ady Abraham27cbed72020-04-10 12:56:59 -07001072 if (!desiredActiveConfig) {
1073 // No desired active config pending to be applied
1074 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001075 }
1076
Ady Abraham2e1dd892020-03-05 13:48:36 -08001077 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001078 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001079 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1080 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001081 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001082 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001083 // display is not valid or we are already in the requested mode
1084 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001085 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001086 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001087 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001088
Ady Abraham838de062019-02-04 10:24:03 -08001089 // Desired active config was set, it is different than the config currently in use, however
1090 // allowed configs might have change by the time we process the refresh.
1091 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001092 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001093 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001094 return;
Ady Abraham838de062019-02-04 10:24:03 -08001095 }
Alec Mouri7f015182019-07-11 13:56:22 -07001096
Ady Abraham27cbed72020-04-10 12:56:59 -07001097 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001098 const auto displayId = display->getId();
1099 LOG_ALWAYS_FATAL_IF(!displayId);
1100
Ady Abrahamabc27602020-04-08 17:20:29 -07001101 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001102
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001103 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001104 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001105 constraints.desiredTimeNanos = systemTime();
1106 constraints.seamlessRequired = false;
1107
Peiyong Line9d809e2020-04-14 13:10:48 -07001108 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001109 auto status =
1110 getHwComposer().setActiveConfigWithConstraints(*displayId,
1111 mUpcomingActiveConfig.configId.value(),
1112 constraints, &outTimeline);
1113 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001114 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1115 // to be sent. We just log the error in this case.
1116 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001117 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001118 }
1119
1120 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1121 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001122 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001123}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001124
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001125status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1126 Vector<ColorMode>* outColorModes) {
1127 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001128 return BAD_VALUE;
1129 }
1130
Peiyong Lina52f0292018-03-14 17:26:31 -07001131 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001132 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001133 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001134 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1135
1136 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1137 if (!displayId) {
1138 return NAME_NOT_FOUND;
1139 }
1140
Dominik Laskowski075d3172018-05-24 15:50:06 -07001141 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001142 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001143 }
Michael Wright28f24d02016-07-12 13:30:53 -07001144 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001145
1146 // If it's built-in display and the configuration claims it's not wide color capable,
1147 // filter out all wide color modes. The typical reason why this happens is that the
1148 // hardware is not good enough to support GPU composition of wide color, and thus the
1149 // OEMs choose to disable this capability.
1150 if (isInternalDisplay && !hasWideColorDisplay) {
1151 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1152 isWideColorMode);
1153 } else {
1154 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1155 }
Michael Wright28f24d02016-07-12 13:30:53 -07001156
1157 return NO_ERROR;
1158}
1159
Daniel Solomon42d04562019-01-20 21:03:19 -08001160status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1161 ui::DisplayPrimaries &primaries) {
1162 if (!displayToken) {
1163 return BAD_VALUE;
1164 }
1165
1166 // Currently we only support this API for a single internal display.
1167 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001168 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001169 }
1170
1171 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1172 return NO_ERROR;
1173}
1174
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001175ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001176 Mutex::Autolock lock(mStateLock);
1177
1178 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001179 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001180 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001181 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001182}
1183
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001184status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001185 schedule([=]() MAIN_THREAD {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001186 Vector<ColorMode> modes;
1187 getDisplayColorModes(displayToken, &modes);
1188 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1189 if (mode < ColorMode::NATIVE || !exists) {
1190 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1191 decodeColorMode(mode).c_str(), mode, displayToken.get());
1192 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001193 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001194 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001195 if (!display) {
1196 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1197 decodeColorMode(mode).c_str(), mode, displayToken.get());
1198 } else if (display->isVirtual()) {
1199 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1200 decodeColorMode(mode).c_str(), mode);
1201 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001202 display->getCompositionDisplay()->setColorProfile(
1203 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1204 RenderIntent::COLORIMETRIC,
1205 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001206 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001207 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001208
Michael Wright28f24d02016-07-12 13:30:53 -07001209 return NO_ERROR;
1210}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001211
Galia Peycheva5492cb52019-10-30 14:13:16 +01001212status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1213 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001214 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001215 return BAD_VALUE;
1216 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001217
1218 Mutex::Autolock lock(mStateLock);
1219
Galia Peycheva5492cb52019-10-30 14:13:16 +01001220 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1221 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001222 return NAME_NOT_FOUND;
1223 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001224 *outSupport =
1225 getHwComposer().hasDisplayCapability(*displayId,
1226 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001227 return NO_ERROR;
1228}
1229
1230void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001231 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001232 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1233 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1234 } else {
1235 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1236 }
1237 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001238}
1239
1240status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1241 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001242 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001243 return BAD_VALUE;
1244 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001245
1246 Mutex::Autolock lock(mStateLock);
1247
Galia Peycheva5492cb52019-10-30 14:13:16 +01001248 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1249 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001250 return NAME_NOT_FOUND;
1251 }
1252
Peiyong Line9d809e2020-04-14 13:10:48 -07001253 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001254 getHwComposer().getSupportedContentTypes(*displayId, &types);
1255
1256 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001257 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001258 return NO_ERROR;
1259}
1260
1261void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001262 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001263 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001264 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001265 getHwComposer().setContentType(*displayId, type);
1266 } else {
1267 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1268 }
1269 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001270}
1271
Svetoslavd85084b2014-03-20 10:28:31 -07001272status_t SurfaceFlinger::clearAnimationFrameStats() {
1273 Mutex::Autolock _l(mStateLock);
1274 mAnimFrameTracker.clearStats();
1275 return NO_ERROR;
1276}
1277
1278status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1279 Mutex::Autolock _l(mStateLock);
1280 mAnimFrameTracker.getStats(outStats);
1281 return NO_ERROR;
1282}
1283
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001284status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1285 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001286 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001287
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001288 const auto display = getDisplayDeviceLocked(displayToken);
1289 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001290 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1291 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001292 }
1293
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001294 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001295 // meaning the luminance information is already queried from
1296 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001297 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001298 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1299 capabilities.getDesiredMaxLuminance(),
1300 capabilities.getDesiredMaxAverageLuminance(),
1301 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001302
1303 return NO_ERROR;
1304}
1305
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001306std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1307 const DisplayDevice& display) const {
1308 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1309 // avoid repetitive HAL IPC and EDID parsing.
1310 const auto displayId = display.getId();
1311 LOG_FATAL_IF(!displayId);
1312
1313 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1314 LOG_FATAL_IF(!hwcDisplayId);
1315
1316 uint8_t port;
1317 DisplayIdentificationData data;
1318 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1319 ALOGV("%s: No identification data.", __FUNCTION__);
1320 return {};
1321 }
1322
1323 const auto info = parseDisplayIdentificationData(port, data);
1324 if (!info) {
1325 return {};
1326 }
1327 return info->deviceProductInfo;
1328}
1329
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001330status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1331 ui::PixelFormat* outFormat,
1332 ui::Dataspace* outDataspace,
1333 uint8_t* outComponentMask) const {
1334 if (!outFormat || !outDataspace || !outComponentMask) {
1335 return BAD_VALUE;
1336 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001337
1338 Mutex::Autolock lock(mStateLock);
1339
1340 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1341 if (!displayId) {
1342 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001343 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001344
1345 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001346 outDataspace, outComponentMask);
1347}
1348
Kevin DuBois74e53772018-11-19 10:52:38 -08001349status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1350 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001351 uint64_t maxFrames) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001352 return schedule([=]() MAIN_THREAD -> status_t {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001353 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1354 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1355 componentMask,
1356 maxFrames);
1357 } else {
1358 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1359 return NAME_NOT_FOUND;
1360 }
1361 })
1362 .get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001363}
1364
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001365status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1366 uint64_t maxFrames, uint64_t timestamp,
1367 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001368 Mutex::Autolock lock(mStateLock);
1369
1370 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1371 if (!displayId) {
1372 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001373 }
1374
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001375 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001376}
1377
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001378status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1379 if (!outSupported) {
1380 return BAD_VALUE;
1381 }
1382 *outSupported = getRenderEngine().supportsProtectedContent();
1383 return NO_ERROR;
1384}
1385
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001386status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1387 bool* outIsWideColorDisplay) const {
1388 if (!displayToken || !outIsWideColorDisplay) {
1389 return BAD_VALUE;
1390 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001391
1392 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001393 const auto display = getDisplayDeviceLocked(displayToken);
1394 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001395 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001396 }
Peiyong Linff84a152019-05-17 18:36:19 -07001397
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001398 *outIsWideColorDisplay =
1399 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001400 return NO_ERROR;
1401}
1402
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001403status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001404 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001405 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001406
Dominik Laskowski6505f792019-09-18 11:10:05 -07001407 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1408 mEventQueue->setEventConnection(
1409 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001410 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001411 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001412
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001413 return NO_ERROR;
1414}
1415
1416status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001417 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001418 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001419}
1420
Vishnu Nair43bccf82020-06-05 10:53:37 -07001421status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001422 outLayers->clear();
Vishnu Nair43bccf82020-06-05 10:53:37 -07001423 schedule([=] {
1424 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
1425 mDrawingState.traverseInZOrder([&](Layer* layer) {
1426 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1427 });
1428 }).wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001429 return NO_ERROR;
1430}
1431
Peiyong Linc6780972018-10-28 15:24:08 -07001432status_t SurfaceFlinger::getCompositionPreference(
1433 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1434 Dataspace* outWideColorGamutDataspace,
1435 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001436 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001437 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001438 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001439 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001440 return NO_ERROR;
1441}
1442
Dan Stozaec460082018-12-17 15:35:09 -08001443status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1444 const sp<IBinder>& stopLayerHandle,
1445 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001446 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001447 return BAD_VALUE;
1448 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001449
1450 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1451 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001452 return NO_ERROR;
1453}
1454
Dan Stozaec460082018-12-17 15:35:09 -08001455status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001456 if (!listener) {
1457 return BAD_VALUE;
1458 }
Dan Stozaec460082018-12-17 15:35:09 -08001459 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001460 return NO_ERROR;
1461}
Dan Gittik57e63c52019-01-18 16:37:54 +00001462
1463status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1464 bool* outSupport) const {
1465 if (!displayToken || !outSupport) {
1466 return BAD_VALUE;
1467 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001468
1469 Mutex::Autolock lock(mStateLock);
1470
Dan Gittik57e63c52019-01-18 16:37:54 +00001471 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1472 if (!displayId) {
1473 return NAME_NOT_FOUND;
1474 }
1475 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001476 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001477 return NO_ERROR;
1478}
1479
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001480status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001481 if (!displayToken) {
1482 return BAD_VALUE;
1483 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001484
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001485 return promise::chain(schedule([=]() MAIN_THREAD {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001486 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1487 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1488 } else {
1489 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001490 return promise::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001491 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001492 }))
1493 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001494 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001495}
1496
Ady Abraham8532d012019-05-08 14:50:56 -07001497status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1498 PowerHint powerHint = static_cast<PowerHint>(hintId);
1499
1500 if (powerHint == PowerHint::INTERACTION) {
1501 mScheduler->notifyTouchEvent();
1502 }
1503
1504 return NO_ERROR;
1505}
1506
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001507// ----------------------------------------------------------------------------
1508
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001509sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001510 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001511 const auto& handle =
1512 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001513
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001514 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001515}
1516
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001517void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001518 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001519 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001520 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001521}
1522
1523void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001524 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001525 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001526 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001527}
1528
1529void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001530 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001531 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001532}
1533
Ady Abrahamf69d11d2020-07-24 11:09:55 -07001534nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001535 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001536 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1537 return 0;
1538 }
1539
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001540 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001541}
1542
Peiyong Line9d809e2020-04-14 13:10:48 -07001543void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001544 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001545 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001546 ATRACE_NAME("SF onVsync");
1547
Steven Thomas3cfac282017-02-06 12:29:30 -08001548 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001549 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001550 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001551 return;
1552 }
1553
Dominik Laskowski075d3172018-05-24 15:50:06 -07001554 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001555 return;
1556 }
1557
Dominik Laskowski075d3172018-05-24 15:50:06 -07001558 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001559 // For now, we don't do anything with external display vsyncs.
1560 return;
1561 }
1562
Alec Mourif8e689c2019-05-20 18:32:22 -07001563 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001564 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001565 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001566 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001567 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001568}
1569
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001570void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001571 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1572 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001573}
1574
Ady Abraham2139f732019-11-13 18:56:40 -08001575bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001576 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001577}
1578
Ady Abraham2139f732019-11-13 18:56:40 -08001579void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1580 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001581 const auto display = getDefaultDisplayDeviceLocked();
1582 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001583 return;
1584 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001585 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001586
Ana Krulec7d1d6832018-12-27 11:10:09 -08001587 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001588 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001589 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001590 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001591 return;
1592 }
1593
Ady Abrahamabc27602020-04-08 17:20:29 -07001594 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001595}
1596
Peiyong Line9d809e2020-04-14 13:10:48 -07001597void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001598 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001599 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001600 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001601
Lloyd Piqueba04e622017-12-14 17:11:26 -08001602 // Ignore events that do not have the right sequenceId.
1603 if (sequenceId != getBE().mComposerSequenceId) {
1604 return;
1605 }
1606
Steven Thomasb02664d2017-07-26 18:48:28 -07001607 // Only lock if we're not on the main thread. This function is normally
1608 // called on a hwbinder thread, but for the primary display it's called on
1609 // the main thread with the state lock already held, so don't attempt to
1610 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001611 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001612
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001613 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001614
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001615 if (std::this_thread::get_id() == mMainThreadId) {
1616 // Process all pending hot plug events immediately if we are on the main thread.
1617 processDisplayHotplugEventsLocked();
1618 }
1619
Lloyd Piqueba04e622017-12-14 17:11:26 -08001620 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001621}
1622
Ady Abraham7159f572019-10-11 11:10:18 -07001623void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001624 int32_t sequenceId, hal::HWDisplayId /*display*/,
1625 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001626 Mutex::Autolock lock(mStateLock);
1627 if (sequenceId != getBE().mComposerSequenceId) {
1628 return;
1629 }
1630 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001631}
1632
Peiyong Line9d809e2020-04-14 13:10:48 -07001633void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001634 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1635 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1636}
1637
Peiyong Line9d809e2020-04-14 13:10:48 -07001638void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001639 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001640 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001641 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001642 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001643 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001644}
1645
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001646void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001647 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001648
1649 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1650 // display power state.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001651 static_cast<void>(schedule([=]() MAIN_THREAD { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001652}
1653
1654void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1655 ATRACE_CALL();
1656
Peiyong Line9d809e2020-04-14 13:10:48 -07001657 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001658
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001659 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001660 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1661 if (display && display->isPoweredOn()) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02001662 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001663 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001664 }
Mathias Agopian86303202012-07-24 22:46:10 -07001665}
1666
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001667sp<Fence> SurfaceFlinger::previousFrameFence() {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001668 // We are storing the last 2 present fences. If sf's phase offset is to be
1669 // woken up before the actual vsync but targeting the next vsync, we need to check
1670 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001671 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1672 : mPreviousPresentFences[1];
1673}
1674
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001675bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001676 ATRACE_CALL();
1677 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001678
Ady Abraham11579302019-09-19 12:35:58 -07001679 if (fence == Fence::NO_FENCE) {
1680 return false;
1681 }
1682
Dan Stoza59083052020-04-28 10:13:20 -07001683 const status_t status = fence->wait(graceTimeMs);
1684 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1685 // which calls wait(0) again internally
1686 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001687}
1688
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001689nsecs_t SurfaceFlinger::previousFramePresentTime() {
Alec Mouri6d414b52020-03-17 11:18:05 -07001690 const sp<Fence>& fence = previousFrameFence();
1691
1692 if (fence == Fence::NO_FENCE) {
1693 return Fence::SIGNAL_TIME_INVALID;
1694 }
1695
1696 return fence->getSignalTime();
1697}
1698
Ady Abraham5facfb12020-04-22 15:18:31 -07001699nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001700 DisplayStatInfo stats;
1701 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001702 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001703 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001704 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001705}
1706
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001707void SurfaceFlinger::onMessageReceived(int32_t what, nsecs_t expectedVSyncTime) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001708 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001709 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001710 case MessageQueue::INVALIDATE: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001711 onMessageInvalidate(expectedVSyncTime);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001712 break;
1713 }
1714 case MessageQueue::REFRESH: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001715 onMessageRefresh();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001716 break;
1717 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001718 }
1719}
1720
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001721void SurfaceFlinger::onMessageInvalidate(nsecs_t expectedVSyncTime) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001722 ATRACE_CALL();
1723
1724 const nsecs_t frameStart = systemTime();
1725 // calculate the expected present time once and use the cached
1726 // value throughout this frame to make sure all layers are
1727 // seeing this same value.
1728 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
1729 mExpectedPresentTime = expectedVSyncTime;
1730
1731 // When Backpressure propagation is enabled we want to give a small grace period
1732 // for the present fence to fire instead of just giving up on this frame to handle cases
1733 // where present fence is just about to get signaled.
1734 const int graceTimeForPresentFenceMs =
1735 (mPropagateBackpressure &&
1736 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1737 ? 1
1738 : 0;
1739
1740 // Pending frames may trigger backpressure propagation.
1741 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1742 previousFramePending(graceTimeForPresentFenceMs)};
1743
1744 // Frame missed counts for metrics tracking.
1745 // A frame is missed if the prior frame is still pending. If no longer pending,
1746 // then we still count the frame as missed if the predicted present time
1747 // was further in the past than when the fence actually fired.
1748
1749 // Add some slop to correct for drift. This should generally be
1750 // smaller than a typical frame duration, but should not be so small
1751 // that it reports reasonable drift as a missed frame.
1752 DisplayStatInfo stats;
1753 mScheduler->getDisplayStatInfo(&stats);
1754 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1755 const nsecs_t previousPresentTime = previousFramePresentTime();
1756 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
1757 framePending ||
1758 (previousPresentTime >= 0 &&
1759 (lastExpectedPresentTime <
1760 previousPresentTime - frameMissedSlop))};
1761 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
1762 mHadDeviceComposition && frameMissed};
1763 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
1764 mHadClientComposition && frameMissed};
1765
1766 if (frameMissed) {
1767 mFrameMissedCount++;
1768 mTimeStats->incrementMissedFrames();
1769 if (mMissedFrameJankCount == 0) {
1770 mMissedFrameJankStart = systemTime();
1771 }
1772 mMissedFrameJankCount++;
1773 }
1774
1775 if (hwcFrameMissed) {
1776 mHwcFrameMissedCount++;
1777 }
1778
1779 if (gpuFrameMissed) {
1780 mGpuFrameMissedCount++;
1781 }
1782
1783 // If we are in the middle of a config change and the fence hasn't
1784 // fired yet just wait for the next invalidate
1785 if (mSetActiveConfigPending) {
1786 if (framePending) {
1787 mEventQueue->invalidate();
1788 return;
1789 }
1790
1791 // We received the present fence from the HWC, so we assume it successfully updated
1792 // the config, hence we update SF.
1793 mSetActiveConfigPending = false;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001794 ON_MAIN_THREAD(setActiveConfigInternal());
Dan Stoza28d46a52020-04-28 09:54:54 -07001795 }
1796
1797 if (framePending && mPropagateBackpressure) {
1798 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
1799 signalLayerUpdate();
1800 return;
1801 }
1802 }
1803
1804 // Our jank window is always at least 100ms since we missed a
1805 // frame...
1806 static constexpr nsecs_t kMinJankyDuration =
1807 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1808 // ...but if it's larger than 1s then we missed the trace cutoff.
1809 static constexpr nsecs_t kMaxJankyDuration =
1810 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001811 nsecs_t jankDurationToUpload = -1;
Dan Stoza28d46a52020-04-28 09:54:54 -07001812 // If we're in a user build then don't push any atoms
1813 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001814 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dan Stoza28d46a52020-04-28 09:54:54 -07001815 // Only report jank when the display is on, as displays in DOZE
1816 // power mode may operate at a different frame rate than is
1817 // reported in their config, which causes noticeable (but less
1818 // severe) jank.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001819 if (display && display->getPowerMode() == hal::PowerMode::ON) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001820 const nsecs_t currentTime = systemTime();
1821 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1822 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001823 jankDurationToUpload = jankDuration;
Dan Stoza28d46a52020-04-28 09:54:54 -07001824 }
1825
1826 // We either reported a jank event or we missed the trace
1827 // window, so clear counters here.
1828 if (jankDuration > kMinJankyDuration) {
1829 mMissedFrameJankCount = 0;
1830 mMissedFrameJankStart = 0;
1831 }
1832 }
1833 }
1834
Dan Stoza28d46a52020-04-28 09:54:54 -07001835 if (mTracingEnabledChanged) {
1836 mTracingEnabled = mTracing.isEnabled();
1837 mTracingEnabledChanged = false;
1838 }
1839
1840 bool refreshNeeded;
1841 {
1842 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1843
1844 refreshNeeded = handleMessageTransaction();
1845 refreshNeeded |= handleMessageInvalidate();
1846 if (mTracingEnabled) {
1847 mAddCompositionStateToTrace =
1848 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1849 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1850 mTracing.notifyLocked("visibleRegionsDirty");
1851 }
1852 }
1853 }
1854
1855 // Layers need to get updated (in the previous line) before we can use them for
1856 // choosing the refresh rate.
1857 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1858 // and may eventually call to ~Layer() if it holds the last reference
1859 {
1860 Mutex::Autolock _l(mStateLock);
1861 mScheduler->chooseRefreshRateForContent();
1862 }
1863
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001864 ON_MAIN_THREAD(performSetActiveConfig());
Dan Stoza28d46a52020-04-28 09:54:54 -07001865
1866 updateCursorAsync();
1867 updateInputFlinger();
1868
1869 refreshNeeded |= mRepaintEverything;
1870 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001871 mLastJankDuration = jankDurationToUpload;
Dan Stoza28d46a52020-04-28 09:54:54 -07001872 // Signal a refresh if a transaction modified the window state,
1873 // a new buffer was latched, or if HWC has requested a full
1874 // repaint
1875 if (mFrameStartTime <= 0) {
1876 // We should only use the time of the first invalidate
1877 // message that signals a refresh as the beginning of the
1878 // frame. Otherwise the real frame time will be
1879 // underestimated.
1880 mFrameStartTime = frameStart;
1881 }
1882 signalRefresh();
1883 }
1884}
1885
Dan Stoza6b9454d2014-11-07 16:00:59 -08001886bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001887 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001888 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001889
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001890 bool flushedATransaction = flushTransactionQueues();
1891
Valerie Hau47826a72020-06-15 12:34:40 -07001892 bool runHandleTransaction =
1893 (transactionFlags && (transactionFlags != eTransactionFlushNeeded)) ||
Robert Carr6417d2e2020-06-24 15:26:32 -07001894 flushedATransaction ||
1895 mForceTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001896
1897 if (runHandleTransaction) {
1898 handleTransaction(eTransactionMask);
1899 } else {
1900 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001901 }
1902
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001903 if (transactionFlushNeeded()) {
1904 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001905 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001906
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001907 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001908}
1909
Dan Stoza28d46a52020-04-28 09:54:54 -07001910void SurfaceFlinger::onMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001911 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001912
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001913 mRefreshPending = false;
1914
Lloyd Piqueab039b52019-02-13 14:22:42 -08001915 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001916 const auto& displays = ON_MAIN_THREAD(mDisplays);
1917 refreshArgs.outputs.reserve(displays.size());
1918 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08001919 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1920 }
1921 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001922 if (auto layerFE = layer->getCompositionEngineLayerFE())
1923 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001924 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001925 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1926 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001927 if (auto layerFE = layer->getCompositionEngineLayerFE())
1928 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001929 }
1930
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001931 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001932 refreshArgs.outputColorSetting = useColorManagement
1933 ? mDisplayColorSetting
1934 : compositionengine::OutputColorSetting::kUnmanaged;
1935 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1936 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001937
1938 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1939 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001940 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02001941 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001942
1943 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1944 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1945 mDrawingState.colorMatrixChanged = false;
1946 }
1947
1948 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1949
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001950 if (mDebugRegion != 0) {
1951 refreshArgs.devOptFlashDirtyRegionsDelay =
1952 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1953 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001954
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001955 mGeometryInvalid = false;
1956
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001957 // Store the present time just before calling to the composition engine so we could notify
1958 // the scheduler.
1959 const auto presentTime = systemTime();
1960
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001961 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001962 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1963 // Reset the frame start time now that we've recorded this frame.
1964 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001965
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001966 mScheduler->onDisplayRefreshed(presentTime);
1967
David Sodmanfa9b2af2017-12-24 13:28:59 -08001968 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001969 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001970
Alec Mouri8f7a0102020-04-15 12:11:10 -07001971 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
1972
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001973 mHadClientComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
1974 const auto& state = pair.second->getCompositionDisplay()->getState();
1975 return state.usesClientComposition && !state.reusedClientComposition;
1976 });
1977 mHadDeviceComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
1978 const auto& state = pair.second->getCompositionDisplay()->getState();
1979 return state.usesDeviceComposition;
1980 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001981 mReusedClientComposition =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001982 std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
1983 const auto& state = pair.second->getCompositionDisplay()->getState();
1984 return state.reusedClientComposition;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001985 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001986
Alec Mouri8f7a0102020-04-15 12:11:10 -07001987 // Only report a strategy change if we move in and out of composition with hw overlays
1988 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
1989 mTimeStats->incrementCompositionStrategyChanges();
1990 }
1991
Yichi Chen28dee2c2020-07-06 21:24:14 +08001992 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
1993 mVSyncModulator->onRefreshed(mHadClientComposition || mReusedClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001994
David Sodman7e4ae112018-02-09 15:02:28 -08001995 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001996 if (mVisibleRegionsDirty) {
1997 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07001998 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07001999 mTracing.notify("visibleRegionsDirty");
2000 }
2001 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002002
2003 if (mCompositionEngine->needsAnotherUpdate()) {
2004 signalLayerUpdate();
2005 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002006}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002007
David Sodmanfa9b2af2017-12-24 13:28:59 -08002008bool SurfaceFlinger::handleMessageInvalidate() {
2009 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002010 bool refreshNeeded = handlePageFlip();
2011
Vishnu Nair4351ad52019-02-11 14:13:02 -08002012 if (mVisibleRegionsDirty) {
2013 computeLayerBounds();
2014 }
2015
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002016 for (auto& layer : mLayersPendingRefresh) {
2017 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002018 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002019 invalidateLayerStack(layer, visibleReg);
2020 }
2021 mLayersPendingRefresh.clear();
2022 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002023}
2024
Ana Krulece588e312018-09-18 12:32:24 -07002025void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2026 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002027 // Update queue of past composite+present times and determine the
2028 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002029 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002030 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002031 while (!getBE().mCompositePresentTimes.empty()) {
2032 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002033 // Cached values should have been updated before calling this method,
2034 // which helps avoid duplicate syscalls.
2035 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2036 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2037 break;
2038 }
2039 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002040 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002041 }
2042
2043 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002044 while (getBE().mCompositePresentTimes.size() > 16) {
2045 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002046 }
2047
Ana Krulece588e312018-09-18 12:32:24 -07002048 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002049}
2050
Ana Krulece588e312018-09-18 12:32:24 -07002051void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2052 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002053 // Integer division and modulo round toward 0 not -inf, so we need to
2054 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002055 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2056 ? (stats.vsyncPeriod -
2057 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2058 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002059
Ady Abraham9e16a482019-12-03 17:19:41 -08002060 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002061 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002062 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002063 }
2064
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002065 // Snap the latency to a value that removes scheduling jitter from the
2066 // composition and present times, which often have >1ms of jitter.
2067 // Reducing jitter is important if an app attempts to extrapolate
2068 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002069 // Snapping also allows an app to precisely calculate
2070 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002071 nsecs_t bias = stats.vsyncPeriod / 2;
2072 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2073 nsecs_t snappedCompositeToPresentLatency =
2074 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075
David Sodman99974d22017-11-28 12:04:33 -08002076 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002077 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2078 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002079 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002080}
2081
David Sodman2b406362017-12-15 13:33:47 -08002082void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002083{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 ATRACE_CALL();
2085 ALOGV("postComposition");
2086
Brian Andersonf6386862016-10-31 16:34:13 -07002087 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002088 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002089 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002090 }
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002091
2092 const auto* display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002093
David Sodman73beded2017-11-15 11:56:06 -08002094 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002095 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002096 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002097 glCompositionDoneFenceTime =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002098 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002099 ->getRenderSurface()
2100 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002101 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002102 } else {
2103 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2104 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002105
David Sodman73beded2017-11-15 11:56:06 -08002106 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002107 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002108 mPreviousPresentFences[0] =
2109 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Ady Abrahambe0f9482019-04-24 15:41:53 -07002110 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002111 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002112
Ana Krulece588e312018-09-18 12:32:24 -07002113 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002114 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002115
Lloyd Piqueab039b52019-02-13 14:22:42 -08002116 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2117 // be sampled a little later than when we started doing work for this frame,
2118 // but that should be okay since updateCompositorTiming has snapping logic.
2119 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2120 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002121 CompositorTiming compositorTiming;
2122 {
David Sodman99974d22017-11-28 12:04:33 -08002123 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2124 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002125 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002126
Edgar Arriaga844fa672020-01-16 14:21:42 -08002127 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002128 const bool frameLatched = layer->onPostComposition(display, glCompositionDoneFenceTime,
2129 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002130 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002131 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002132 }
Robert Carr2047fae2016-11-28 14:09:09 -08002133 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002134
Valerie Hau4b678442020-04-14 10:50:42 -07002135 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2136 mTransactionCompletedThread.sendCallbacks();
2137
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002138 if (display && display->isPrimary() && display->getPowerMode() == hal::PowerMode::ON &&
2139 presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002140 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002141 }
2142
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002143 const bool isDisplayConnected = display && getHwComposer().isConnected(*display->getId());
2144
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002145 if (!hasSyncFramework) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002146 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002147 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002148 }
2149 }
2150
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002151 if (mAnimCompositionPending) {
2152 mAnimCompositionPending = false;
2153
Brian Anderson4e606e32017-03-16 15:34:57 -07002154 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002155 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002156 std::move(presentFenceTime));
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002157 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002158 // The HWC doesn't support present fences, so use the refresh
2159 // timestamp instead.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002160 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002161 mAnimFrameTracker.setActualPresentTime(presentTime);
2162 }
2163 mAnimFrameTracker.advanceFrame();
2164 }
Dan Stozab90cf072015-03-05 11:05:59 -08002165
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002166 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002167 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002168 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002169 }
2170
Vishnu Nair9b079a22020-01-21 14:36:08 -08002171 if (mReusedClientComposition) {
2172 mTimeStats->incrementClientCompositionReusedFrames();
2173 }
2174
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002175 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002176
Alec Mouri717bcb62020-02-10 17:07:19 -08002177 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2178 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2179 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2180
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002181 if (mLastJankDuration > 0) {
2182 ATRACE_NAME("Jank detected");
2183 const int32_t jankyDurationMillis = mLastJankDuration / (1000 * 1000);
2184 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED, jankyDurationMillis,
2185 mMissedFrameJankCount);
2186 mLastJankDuration = -1;
2187 }
2188
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002189 if (isDisplayConnected && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002190 return;
2191 }
2192
2193 nsecs_t currentTime = systemTime();
2194 if (mHasPoweredOff) {
2195 mHasPoweredOff = false;
2196 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002197 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002198 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002199 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2200 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002201 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002202 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002203 }
David Sodman4a36e932017-11-07 14:29:47 -08002204 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002205 }
David Sodman4a36e932017-11-07 14:29:47 -08002206 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002207
Alec Mouri4dde1782019-09-30 17:27:13 -07002208 // Cleanup any outstanding resources due to rendering a prior frame.
2209 getRenderEngine().cleanupPostRender();
2210
Dan Stoza436ccf32018-06-21 12:10:12 -07002211 {
2212 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002213 if (mTexturePool.size() < mTexturePoolSize) {
2214 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002215 const size_t offset = mTexturePool.size();
2216 mTexturePool.resize(mTexturePoolSize);
2217 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2218 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002219 } else if (mTexturePool.size() > mTexturePoolSize) {
2220 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2221 const size_t offset = mTexturePoolSize;
2222 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2223 mTexturePool.resize(mTexturePoolSize);
2224 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002225 }
2226 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002227
Kevin DuBois413287f2019-02-25 08:46:47 -08002228 if (mLumaSampling && mRegionSamplingThread) {
2229 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002230 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002231
2232 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2233 // side-effect of getTotalSize(), so we check that again here
2234 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002235 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002236 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2237 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002238}
2239
Lloyd Pique7eebe692020-04-22 22:40:06 -07002240FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2241 return displayDevice.getViewport().toFloatRect();
2242}
2243
Vishnu Nair4351ad52019-02-11 14:13:02 -08002244void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002245 for (const auto& pair : ON_MAIN_THREAD(mDisplays)) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08002246 const auto& displayDevice = pair.second;
2247 const auto display = displayDevice->getCompositionDisplay();
2248 for (const auto& layer : mDrawingState.layersSortedByZ) {
2249 // only consider the layers on the given layer stack
2250 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002251 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002252 }
2253
Lloyd Pique7eebe692020-04-22 22:40:06 -07002254 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002255 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002256 }
2257 }
2258}
2259
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002260void SurfaceFlinger::postFrame() {
2261 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002262 if (display && getHwComposer().isConnected(*display->getId())) {
2263 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002264 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2265 logFrameStats();
2266 }
2267 }
2268}
2269
Mathias Agopian87baae12012-07-31 12:38:26 -07002270void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002271{
Mathias Agopian841cde52012-03-01 15:44:37 -08002272 ATRACE_CALL();
2273
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002274 // here we keep a copy of the drawing state (that is the state that's
2275 // going to be overwritten by handleTransactionLocked()) outside of
2276 // mStateLock so that the side-effects of the State assignment
2277 // don't happen with mStateLock held (which can cause deadlocks).
2278 State drawingState(mDrawingState);
2279
Mathias Agopianca4d3602011-05-19 15:38:14 -07002280 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002281 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002282
Mathias Agopianca4d3602011-05-19 15:38:14 -07002283 // Here we're guaranteed that some transaction flags are set
2284 // so we can call handleTransactionLocked() unconditionally.
2285 // We call getTransactionFlags(), which will also clear the flags,
2286 // with mStateLock held to guarantee that mCurrentState won't change
2287 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002288
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002289 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002290 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002291 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002292
Mathias Agopianca4d3602011-05-19 15:38:14 -07002293 mDebugInTransaction = 0;
2294 invalidateHwcGeometry();
2295 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002296}
2297
Lloyd Piqueba04e622017-12-14 17:11:26 -08002298void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2299 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002300 const std::optional<DisplayIdentificationInfo> info =
2301 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002302
Dominik Laskowski075d3172018-05-24 15:50:06 -07002303 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002304 continue;
2305 }
2306
Dominik Laskowski55c85402020-01-21 16:25:47 -08002307 const DisplayId displayId = info->id;
2308 const auto it = mPhysicalDisplayTokens.find(displayId);
2309
Peiyong Line9d809e2020-04-14 13:10:48 -07002310 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002311 if (it == mPhysicalDisplayTokens.end()) {
2312 ALOGV("Creating display %s", to_string(displayId).c_str());
2313
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002314 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002315 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002316 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002317
Dominik Laskowski075d3172018-05-24 15:50:06 -07002318 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002319 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2320 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002321 state.isSecure = true; // All physical displays are currently considered secure.
2322 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002323
2324 sp<IBinder> token = new BBinder();
2325 mCurrentState.displays.add(token, state);
2326 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2327
Dominik Laskowski075d3172018-05-24 15:50:06 -07002328 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002329 } else {
2330 ALOGV("Recreating display %s", to_string(displayId).c_str());
2331
2332 const auto token = it->second;
2333 auto& state = mCurrentState.displays.editValueFor(token);
2334 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002335 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002336 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002337 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002338
Dominik Laskowski55c85402020-01-21 16:25:47 -08002339 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002340 if (index >= 0) {
2341 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2342 mInterceptor->saveDisplayDeletion(state.sequenceId);
2343 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002344 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002345 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002346 }
2347
2348 processDisplayChangesLocked();
2349 }
2350
2351 mPendingHotplugEvents.clear();
2352}
2353
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002354void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002355 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2356 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002357}
2358
Lloyd Pique99d3da52018-01-22 17:48:03 -08002359sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002360 const wp<IBinder>& displayToken,
2361 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002362 const DisplayDeviceState& state,
2363 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002364 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002365 auto displayId = compositionDisplay->getDisplayId();
2366 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002367 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002368 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002369 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002370 creationArgs.hasWideColorGamut = false;
2371 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002372
Dominik Laskowski55c85402020-01-21 16:25:47 -08002373 if (const auto& physical = state.physical) {
2374 creationArgs.connectionType = physical->type;
2375 }
2376
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002377 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002378 creationArgs.isPrimary = isInternalDisplay;
2379
2380 if (useColorManagement && displayId) {
2381 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002382 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002383 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002384 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002385 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002386
Dominik Laskowski7e045462018-05-30 13:02:02 -07002387 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002388 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002389 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002390 }
tangrobin6753a022018-08-10 10:58:54 +08002391 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392
Dominik Laskowski075d3172018-05-24 15:50:06 -07002393 if (displayId) {
2394 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002395 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002396 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002397 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002398
Lloyd Pique90c115d2018-09-18 21:39:42 -07002399 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002400 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002401 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402
Lloyd Pique99d3da52018-01-22 17:48:03 -08002403 // Make sure that composition can never be stalled by a virtual display
2404 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002405 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002406 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002407 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2408 }
2409
Dominik Laskowski718f9602019-11-09 20:01:35 -08002410 creationArgs.physicalOrientation =
2411 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002412
Lloyd Pique99d3da52018-01-22 17:48:03 -08002413 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002414 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002416 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002417
2418 if (maxFrameBufferAcquiredBuffers >= 3) {
2419 nativeWindowSurface->preallocateBuffers();
2420 }
2421
2422 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002423 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002424 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002425 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002426 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002427 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002428 display->getCompositionDisplay()->setColorProfile(
2429 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2430 RenderIntent::COLORIMETRIC,
2431 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002432 if (!state.isVirtual()) {
2433 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002434 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2435 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002436 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002437
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002438 display->setLayerStack(state.layerStack);
2439 display->setProjection(state.orientation, state.viewport, state.frame);
2440 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002441
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002442 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002443}
2444
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002445void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2446 const DisplayDeviceState& state) {
2447 int width = 0;
2448 int height = 0;
2449 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2450 if (state.physical) {
2451 const auto& activeConfig =
2452 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2453 width = activeConfig->getWidth();
2454 height = activeConfig->getHeight();
2455 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2456 } else if (state.surface != nullptr) {
2457 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2458 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2459 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2460 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2461 int intPixelFormat;
2462 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2463 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2464 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2465 } else {
2466 // Virtual displays without a surface are dormant:
2467 // they have external state (layer stack, projection,
2468 // etc.) but no internal state (i.e. a DisplayDevice).
2469 return;
2470 }
2471
2472 compositionengine::DisplayCreationArgsBuilder builder;
2473 if (const auto& physical = state.physical) {
2474 builder.setPhysical({physical->id, physical->type});
2475 }
2476 builder.setPixels(ui::Size(width, height));
2477 builder.setPixelFormat(pixelFormat);
2478 builder.setIsSecure(state.isSecure);
2479 builder.setLayerStackId(state.layerStack);
2480 builder.setPowerAdvisor(&mPowerAdvisor);
Alec Mouri643053a2020-09-09 18:57:07 -07002481 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002482 builder.setName(state.displayName);
2483 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2484
2485 sp<compositionengine::DisplaySurface> displaySurface;
2486 sp<IGraphicBufferProducer> producer;
2487 sp<IGraphicBufferProducer> bqProducer;
2488 sp<IGraphicBufferConsumer> bqConsumer;
2489 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2490
2491 std::optional<DisplayId> displayId = compositionDisplay->getId();
2492
2493 if (state.isVirtual()) {
2494 sp<VirtualDisplaySurface> vds =
2495 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2496 bqConsumer, state.displayName);
2497
2498 displaySurface = vds;
2499 producer = vds;
2500 } else {
2501 ALOGE_IF(state.surface != nullptr,
2502 "adding a supported display, but rendering "
2503 "surface is provided (%p), ignoring it",
2504 state.surface.get());
2505
2506 LOG_ALWAYS_FATAL_IF(!displayId);
2507 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2508 maxGraphicsWidth, maxGraphicsHeight);
2509 producer = bqProducer;
2510 }
2511
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002512 LOG_FATAL_IF(!displaySurface);
2513 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2514 displaySurface, producer);
2515 mDisplays.emplace(displayToken, display);
2516 if (!state.isVirtual()) {
2517 LOG_FATAL_IF(!displayId);
2518 dispatchDisplayHotplugEvent(displayId->value, true);
2519 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002520
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002521 if (display->isPrimary()) {
2522 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002523 }
2524}
2525
2526void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2527 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2528 // Save display ID before disconnecting.
2529 const auto displayId = display->getId();
2530 display->disconnect();
2531
2532 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002533 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002534 dispatchDisplayHotplugEvent(displayId->value, false);
2535 }
2536 }
2537
2538 mDisplays.erase(displayToken);
2539}
2540
2541void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2542 const DisplayDeviceState& currentState,
2543 const DisplayDeviceState& drawingState) {
2544 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2545 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002546 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002547 // changing the surface is like destroying and recreating the DisplayDevice
2548 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2549 display->disconnect();
2550 }
2551 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002552 if (const auto& physical = currentState.physical) {
2553 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2554 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002555 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002556 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002557 const auto display = getDisplayDeviceLocked(displayToken);
2558 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002559 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002560 return;
2561 }
2562
2563 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2564 if (currentState.layerStack != drawingState.layerStack) {
2565 display->setLayerStack(currentState.layerStack);
2566 }
2567 if ((currentState.orientation != drawingState.orientation) ||
2568 (currentState.viewport != drawingState.viewport) ||
2569 (currentState.frame != drawingState.frame)) {
2570 display->setProjection(currentState.orientation, currentState.viewport,
2571 currentState.frame);
2572 }
2573 if (currentState.width != drawingState.width ||
2574 currentState.height != drawingState.height) {
2575 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07002576
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002577 if (display->isPrimary()) {
2578 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2579 }
Dominik Laskowski20134642020-04-20 22:36:44 -07002580
2581 if (mRefreshRateOverlay) {
2582 mRefreshRateOverlay->setViewport(display->getSize());
2583 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002584 }
2585 }
2586}
2587
Lloyd Pique347200f2017-12-14 17:00:15 -08002588void SurfaceFlinger::processDisplayChangesLocked() {
2589 // here we take advantage of Vector's copy-on-write semantics to
2590 // improve performance by skipping the transaction entirely when
2591 // know that the lists are identical
2592 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2593 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2594 if (!curr.isIdenticalTo(draw)) {
2595 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002596
2597 // find the displays that were removed
2598 // (ie: in drawing state but not in current state)
2599 // also handle displays that changed
2600 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002601 for (size_t i = 0; i < draw.size(); i++) {
2602 const wp<IBinder>& displayToken = draw.keyAt(i);
2603 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002604 if (j < 0) {
2605 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002606 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002607 } else {
2608 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002609 const DisplayDeviceState& currentState = curr[j];
2610 const DisplayDeviceState& drawingState = draw[i];
2611 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002612 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002613 }
2614
2615 // find displays that were added
2616 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002617 for (size_t i = 0; i < curr.size(); i++) {
2618 const wp<IBinder>& displayToken = curr.keyAt(i);
2619 if (draw.indexOfKey(displayToken) < 0) {
2620 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002621 }
2622 }
2623 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002624
2625 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002626}
2627
Mathias Agopian87baae12012-07-31 12:38:26 -07002628void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002629{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002630 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2631
Dan Stoza7dde5992015-05-22 09:51:44 -07002632 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002633 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002634 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002635 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002636
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637 /*
2638 * Traversal of the children
2639 * (perform the transaction for each of them if needed)
2640 */
2641
Valerie Haud50e7412020-06-16 17:58:14 -07002642 if ((transactionFlags & eTraversalNeeded) || mForceTraversal) {
2643 mForceTraversal = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002644 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002646 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647
2648 const uint32_t flags = layer->doTransaction(0);
2649 if (flags & Layer::eVisibleRegion)
2650 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002651
2652 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002653 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002654 }
Robert Carr2047fae2016-11-28 14:09:09 -08002655 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 }
2657
2658 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002659 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660 */
2661
Mathias Agopiane57f2922012-08-09 16:29:12 -07002662 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002663 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002664 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666
Vishnu Nair6213bd92020-05-08 17:42:25 -07002667 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002668 // The transform hint might have changed for some layers
2669 // (either because a display has changed, or because a layer
2670 // as changed).
2671 //
2672 // Walk through all the layers in currentLayers,
2673 // and update their transform hint.
2674 //
2675 // If a layer is visible only on a single display, then that
2676 // display is used to calculate the hint, otherwise we use the
2677 // default display.
2678 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002679 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002680 // the hint is set before we acquire a buffer from the surface texture.
2681 //
2682 // NOTE: layer transactions have taken place already, so we use their
2683 // drawing state. However, SurfaceFlinger's own transaction has not
2684 // happened yet, so we must use the current state layer list
2685 // (soon to become the drawing state list).
2686 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002687 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002688 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002689 bool first = true;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002690 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08002691 // NOTE: we rely on the fact that layers are sorted by
2692 // layerStack first (so we don't have to traverse the list
2693 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002694 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002695 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002696 currentlayerStack = layerStack;
2697 // figure out if this layerstack is mirrored
2698 // (more than one display) if so, pick the default display,
2699 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002700 hintDisplay = nullptr;
2701 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002702 if (display->getCompositionDisplay()
2703 ->belongsInOutput(layer->getLayerStack(),
2704 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002705 if (hintDisplay) {
2706 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002707 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002708 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002709 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002710 }
2711 }
2712 }
2713 }
Chet Haase91d25932013-04-11 15:24:55 -07002714
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002715 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002716 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2717 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002718
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002719 // could be null when this layer is using a layerStack
2720 // that is not visible on any display. Also can occur at
2721 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002722 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002723 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002724
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002725 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002726 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002727 if (hintDisplay) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002728 layer->updateTransformHint(hintDisplay->getTransformHint());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002729 }
Robert Carr2047fae2016-11-28 14:09:09 -08002730
2731 first = false;
2732 });
Mathias Agopian84300952012-11-21 16:02:13 -08002733 }
2734
Mathias Agopian3559b072012-08-15 13:46:03 -07002735 /*
2736 * Perform our own transaction if needed
2737 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002738
2739 if (mLayersAdded) {
2740 mLayersAdded = false;
2741 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002742 mVisibleRegionsDirty = true;
2743 }
2744
2745 // some layers might have been removed, so
2746 // we need to update the regions they're exposing.
2747 if (mLayersRemoved) {
2748 mLayersRemoved = false;
2749 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002750 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002751 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002752 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002753 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002754 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002755 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002756 }
Robert Carr2047fae2016-11-28 14:09:09 -08002757 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 }
2759
Vishnu Nairec0ab382019-02-13 15:32:56 -08002760 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002762}
2763
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002764void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002765 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002766 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002767 return;
2768 }
2769
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002770 if (mVisibleRegionsDirty || mInputInfoChanged) {
2771 mInputInfoChanged = false;
2772 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002773 } else if (mInputWindowCommands.syncInputWindows) {
2774 // If the caller requested to sync input windows, but there are no
2775 // changes to input windows, notify immediately.
2776 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002777 }
2778
Arthur Hung6cbb9752019-09-05 16:38:18 +08002779 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002780}
2781
2782void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002783 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002784
2785 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Robert Carredd13602020-04-13 17:24:34 -07002786 if (layer->needsInputInfo()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002787 // When calculating the screen bounds we ignore the transparent region since it may
2788 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002789 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002790 }
2791 });
chaviw291d88a2019-02-14 10:33:58 -08002792
2793 mInputFlinger->setInputWindows(inputHandles,
2794 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2795 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002796}
2797
Vishnu Nairec0ab382019-02-13 15:32:56 -08002798void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002799 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002800 mPendingInputWindowCommands.clear();
2801}
2802
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002803void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002804 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002805 for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002806 if (display->getId()) {
2807 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002808 }
2809 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002810
2811 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002812}
2813
Ady Abraham2139f732019-11-13 18:56:40 -08002814void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002815 Scheduler::ConfigEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08002816 // If this is called from the main thread mStateLock must be locked before
2817 // Currently the only way to call this function from the main thread is from
2818 // Sheduler::chooseRefreshRateForContent
2819
2820 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002821 changeRefreshRateLocked(refreshRate, event);
2822}
2823
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002824void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2825 if (mScheduler) {
2826 // In practice it's not allowed to hotplug in/out the primary display once it's been
2827 // connected during startup, but some tests do it, so just warn and return.
2828 ALOGW("Can't re-init scheduler");
2829 return;
2830 }
2831
Ady Abraham2139f732019-11-13 18:56:40 -08002832 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002833 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002834 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002835 primaryDisplayId),
2836 currentConfig);
2837 mRefreshRateStats =
2838 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002839 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002840 mRefreshRateStats->setConfigMode(currentConfig);
2841
Ady Abraham9e16a482019-12-03 17:19:41 -08002842 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2843
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002844 // start the EventThread
2845 mScheduler =
2846 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002847 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002848 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002849 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002850 impl::EventThread::InterceptVSyncsCallback());
2851 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002852 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002853 [this](nsecs_t timestamp) {
2854 mInterceptor->saveVSyncEvent(timestamp);
2855 });
2856
2857 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2858 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002859 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002860
2861 mRegionSamplingThread =
2862 new RegionSamplingThread(*this, *mScheduler,
2863 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002864 // Dispatch a config change request for the primary display on scheduler
2865 // initialization, so that the EventThreads always contain a reference to a
2866 // prior configuration.
2867 //
2868 // This is a bit hacky, but this avoids a back-pointer into the main SF
2869 // classes from EventThread, and there should be no run-time binder cost
2870 // anyway since there are no connected apps at this point.
2871 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002872 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07002873 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, primaryDisplayId.value,
2874 currentConfig, vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002875}
2876
Mathias Agopian4fec8732012-06-29 14:12:52 -07002877void SurfaceFlinger::commitTransaction()
2878{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002879 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002880 mTransactionPending = false;
2881 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002882 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883}
2884
Lloyd Pique58e24a32019-08-01 15:50:14 -07002885void SurfaceFlinger::commitTransactionLocked() {
2886 if (!mLayersPendingRemoval.isEmpty()) {
2887 // Notify removed layers now that they can't be drawn from
2888 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002889 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002890
2891 // Ensure any buffers set to display on any children are released.
2892 if (l->isRemovedFromCurrentState()) {
2893 l->latchAndReleaseBuffer();
2894 }
2895
2896 // If the layer has been removed and has no parent, then it will not be reachable
2897 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2898 // ensure we can copy its current to drawing state.
2899 if (!l->getParent()) {
2900 mOffscreenLayers.emplace(l.get());
2901 }
2902 }
2903 mLayersPendingRemoval.clear();
2904 }
2905
2906 // If this transaction is part of a window animation then the next frame
2907 // we composite should be considered an animation as well.
2908 mAnimCompositionPending = mAnimTransactionPending;
2909
2910 mDrawingState = mCurrentState;
2911 // clear the "changed" flags in current state
2912 mCurrentState.colorMatrixChanged = false;
2913
Edgar Arriaga844fa672020-01-16 14:21:42 -08002914 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002915 layer->commitChildList();
2916
2917 // If the layer can be reached when traversing mDrawingState, then the layer is no
2918 // longer offscreen. Remove the layer from the offscreenLayer set.
2919 if (mOffscreenLayers.count(layer)) {
2920 mOffscreenLayers.erase(layer);
2921 }
2922 });
2923
2924 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002925 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002926}
2927
chaviw74d90ad2019-04-26 14:45:26 -07002928void SurfaceFlinger::commitOffscreenLayers() {
2929 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002930 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002931 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2932 if (!trFlags) return;
2933
2934 layer->doTransaction(0);
2935 layer->commitChildList();
2936 });
2937 }
2938}
2939
Chia-I Wuab0c3192017-08-01 11:29:00 -07002940void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002941 for (const auto& [token, displayDevice] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002942 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002943 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002944 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002945 }
2946 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002947}
2948
Dan Stoza6b9454d2014-11-07 16:00:59 -08002949bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002950{
Ady Abraham09bd3922019-04-08 10:44:56 -07002951 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002952 ALOGV("handlePageFlip");
2953
Brian Andersond6927fb2016-07-23 23:37:30 -07002954 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002955
Mathias Agopian4fec8732012-06-29 14:12:52 -07002956 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002957 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002958 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002959
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002960 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2961
Eric Penner51c59cd2014-07-28 19:51:58 -07002962 // Store the set of layers that need updates. This set must not change as
2963 // buffers are being latched, as this could result in a deadlock.
2964 // Example: Two producers share the same command stream and:
2965 // 1.) Layer 0 is latched
2966 // 2.) Layer 0 gets a new frame
2967 // 2.) Layer 1 gets a new frame
2968 // 3.) Layer 1 is latched.
2969 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2970 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002971 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002972 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002973 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002974 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002975 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002976 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002977 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002978 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002979 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002980 } else {
2981 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002982 }
Robert Carr2047fae2016-11-28 14:09:09 -08002983 });
2984
chaviw49a108c2019-08-12 11:23:06 -07002985 // The client can continue submitting buffers for offscreen layers, but they will not
2986 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2987 // layers to ensure dequeueBuffer doesn't block indefinitely.
2988 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002989 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002990 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2991 }
2992
Lloyd Piquef2c79392018-12-20 16:23:33 -08002993 if (!mLayersWithQueuedFrames.empty()) {
2994 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2995 // writes to Layer current state. See also b/119481871
2996 Mutex::Autolock lock(mStateLock);
2997
2998 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002999 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003000 mLayersPendingRefresh.push_back(layer);
3001 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003002 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003003 if (layer->isBufferLatched()) {
3004 newDataLatched = true;
3005 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003006 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003007 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003008
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003009 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003010
3011 // If we will need to wake up at some time in the future to deal with a
3012 // queued frame that shouldn't be displayed during this vsync period, wake
3013 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003014 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003015 signalLayerUpdate();
3016 }
3017
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003018 // enter boot animation on first buffer latch
3019 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3020 ALOGI("Enter boot animation");
3021 mBootStage = BootStage::BOOTANIMATION;
3022 }
3023
Edgar Arriaga844fa672020-01-16 14:21:42 -08003024 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003025
Dan Stoza6b9454d2014-11-07 16:00:59 -08003026 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003027 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003028}
3029
Mathias Agopianad456f92011-01-13 17:53:01 -08003030void SurfaceFlinger::invalidateHwcGeometry()
3031{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003032 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003033}
3034
Robert Carrc0df3122019-04-11 13:18:21 -07003035status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3036 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3037 const sp<IBinder>& parentHandle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003038 const sp<Layer>& parentLayer, bool addToCurrentState,
3039 uint32_t* outTransformHint) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003040 // add this layer to the current state list
3041 {
3042 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003043 sp<Layer> parent;
3044 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003045 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003046 if (parent == nullptr) {
3047 return NAME_NOT_FOUND;
3048 }
3049 } else {
3050 parent = parentLayer;
3051 }
3052
Ady Abraham0a525092020-03-03 12:51:24 -08003053 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003054 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003055 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003056 return NO_MEMORY;
3057 }
Robert Carrc0df3122019-04-11 13:18:21 -07003058
3059 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3060
Robert Carrb89ea9d2018-12-10 13:01:14 -08003061 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003062 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003063 } else if (parent == nullptr) {
3064 lbc->onRemovedFromCurrentState();
3065 } else if (parent->isRemovedFromCurrentState()) {
3066 parent->addChild(lbc);
3067 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003068 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 parent->addChild(lbc);
3070 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003071
Yiwei Zhang243b3782018-05-15 17:40:04 -07003072 if (gbc != nullptr) {
3073 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3074 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3075 mMaxGraphicBufferProducerListSize,
3076 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3077 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003078 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003079 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003080
3081 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07003082 lbc->updateTransformHint(display->getTransformHint());
Vishnu Nair6213bd92020-05-08 17:42:25 -07003083 }
3084 if (outTransformHint) {
3085 *outTransformHint = lbc->getTransformHint();
3086 }
3087
Robert Carr1f0a16a2016-10-24 16:27:39 -07003088 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003089 }
3090
Mathias Agopian96f08192010-06-02 23:28:45 -07003091 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003092 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003093
Dan Stoza7d89d062015-04-30 13:29:25 -07003094 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003095}
3096
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003097void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3098 static_cast<void>(schedule([=] {
3099 Mutex::Autolock lock(mStateLock);
3100 mGraphicBufferProducerList.erase(binder);
3101 }));
3102}
3103
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003104uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003105 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003106}
3107
Mathias Agopian3f844832013-08-07 21:24:32 -07003108uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003109 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110}
3111
Mathias Agopian3f844832013-08-07 21:24:32 -07003112uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ady Abrahambf1349c2020-06-12 14:26:18 -07003113 return setTransactionFlags(flags, Scheduler::TransactionStart::Normal);
Dan Stoza84d619e2018-03-28 17:07:36 -07003114}
3115
3116uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003117 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003118 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003119 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003121 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122 }
3123 return old;
3124}
3125
Valerie Haud50e7412020-06-16 17:58:14 -07003126void SurfaceFlinger::setTraversalNeeded() {
3127 mForceTraversal = true;
Robert Carr7ec777d2020-05-29 12:02:51 -07003128}
3129
Marissa Wall713b63f2018-10-17 15:42:43 -07003130bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003131 // to prevent onHandleDestroyed from being called while the lock is held,
3132 // we must keep a copy of the transactions (specifically the composer
3133 // states) around outside the scope of the lock
3134 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003135 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003136 {
3137 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003138
Valerie Haufce31b82019-04-30 16:41:14 -07003139 auto it = mTransactionQueues.begin();
3140 while (it != mTransactionQueues.end()) {
3141 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003142
Valerie Haufce31b82019-04-30 16:41:14 -07003143 while (!transactionQueue.empty()) {
3144 const auto& transaction = transactionQueue.front();
3145 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3146 transaction.states)) {
3147 setTransactionFlags(eTransactionFlushNeeded);
3148 break;
3149 }
3150 transactions.push_back(transaction);
3151 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3152 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003153 transaction.buffer, transaction.postTime,
3154 transaction.privileged, transaction.hasListenerCallbacks,
3155 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003156 transactionQueue.pop();
3157 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003158 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003159
Valerie Haufce31b82019-04-30 16:41:14 -07003160 if (transactionQueue.empty()) {
3161 it = mTransactionQueues.erase(it);
3162 mTransactionCV.broadcast();
3163 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003164 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003165 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003166 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003167 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003168 return flushedATransaction;
3169}
3170
3171bool SurfaceFlinger::transactionFlushNeeded() {
3172 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003173}
3174
chaviwca27f252018-02-06 16:46:39 -08003175
Marissa Wall17b4e452018-12-26 16:32:34 -08003176bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3177 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003178
3179 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003180 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3181 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3182 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3183 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3184 return false;
3185 }
3186
Marissa Wall713b63f2018-10-17 15:42:43 -07003187 for (const ComposerState& state : states) {
3188 const layer_state_t& s = state.state;
3189 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3190 continue;
3191 }
3192 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003193 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003194 }
3195 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003196 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003197}
3198
Valerie Hau9dab9732019-08-20 09:29:25 -07003199void SurfaceFlinger::setTransactionState(
3200 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3201 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3202 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3203 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003204 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003205
Valerie Haubc6ddb12019-03-08 11:10:15 -08003206 const int64_t postTime = systemTime();
3207
Robert Carr14167e02019-02-13 13:50:55 -08003208 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3209
Mathias Agopian698c0872011-06-28 19:09:31 -07003210 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003211
Marissa Wall713b63f2018-10-17 15:42:43 -07003212 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003213 auto itr = mTransactionQueues.find(applyToken);
3214 // if this is an animation frame, wait until prior animation frame has
3215 // been applied by SF
3216 if (flags & eAnimation) {
3217 while (itr != mTransactionQueues.end()) {
3218 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3219 if (CC_UNLIKELY(err != NO_ERROR)) {
3220 ALOGW_IF(err == TIMED_OUT,
3221 "setTransactionState timed out "
3222 "waiting for animation frame to apply");
3223 break;
3224 }
3225 itr = mTransactionQueues.find(applyToken);
3226 }
3227 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003228
Ady Abraham5facfb12020-04-22 15:18:31 -07003229 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003230 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003231 if (!pendingTransactions) {
3232 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3233 }
3234
3235 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003236 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003237 uncacheBuffer, postTime, privileged,
3238 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003239 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003240 return;
3241 }
3242
Valerie Haubc6ddb12019-03-08 11:10:15 -08003243 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003244 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3245 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003246}
3247
Valerie Hau9dab9732019-08-20 09:29:25 -07003248void SurfaceFlinger::applyTransactionState(
3249 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3250 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3251 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3252 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3253 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003254 uint32_t transactionFlags = 0;
3255
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003256 if (flags & eAnimation) {
3257 // For window updates that are part of an animation we must wait for
3258 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003259 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003260 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003261 if (CC_UNLIKELY(err != NO_ERROR)) {
3262 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003263 // caller after a few seconds.
3264 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3265 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003266 mAnimTransactionPending = false;
3267 break;
3268 }
3269 }
3270 }
3271
chaviwca27f252018-02-06 16:46:39 -08003272 for (const DisplayState& display : displays) {
3273 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003274 }
3275
Valerie Hau9dab9732019-08-20 09:29:25 -07003276 // start and end registration for listeners w/ no surface so they can get their callback. Note
3277 // that listeners with SurfaceControls will start registration during setClientStateLocked
3278 // below.
3279 for (const auto& listener : listenerCallbacks) {
3280 mTransactionCompletedThread.startRegistration(listener);
3281 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003282 }
3283
Valerie Hau9dab9732019-08-20 09:29:25 -07003284 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003285 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003286 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003287 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3288 listenerCallbacksWithSurfaces);
Ady Abraham5def7332020-05-29 16:13:47 -07003289 if ((flags & eAnimation) && state.state.surface) {
3290 if (const auto layer = fromHandleLocked(state.state.surface).promote(); layer) {
3291 mScheduler->recordLayerHistory(layer.get(), desiredPresentTime,
3292 LayerHistory::LayerUpdateType::AnimationTX);
3293 }
3294 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07003295 }
3296
Valerie Hau9dab9732019-08-20 09:29:25 -07003297 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003298 mTransactionCompletedThread.endRegistration(listenerCallback);
3299 }
3300
Marissa Walle2ffb422018-10-12 11:33:52 -07003301 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003302 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003303 mTransactionCompletedThread.sendCallbacks();
3304 }
3305 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003306
chaviw273171b2018-12-26 11:46:30 -08003307 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3308
Marissa Wall947d34e2019-03-29 14:03:53 -07003309 if (uncacheBuffer.isValid()) {
3310 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003311 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003312 }
3313
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003314 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3315 // anyway. This can be used as a flush mechanism for previous async transactions.
3316 // Empty animation transaction can be used to simulate back-pressure, so also force a
3317 // transaction for empty animation transactions.
3318 if (transactionFlags == 0 &&
3319 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003320 transactionFlags = eTransactionNeeded;
3321 }
3322
Marissa Wall06255332019-03-27 13:48:27 -07003323 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3324 // so we don't have to wake up again next frame to preform an uneeded traversal.
3325 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3326 transactionFlags = transactionFlags & (~eTraversalNeeded);
Valerie Haud50e7412020-06-16 17:58:14 -07003327 mForceTraversal = true;
Marissa Wall06255332019-03-27 13:48:27 -07003328 }
3329
Ady Abrahambf1349c2020-06-12 14:26:18 -07003330 const auto transactionStart = [](uint32_t flags) {
3331 if (flags & eEarlyWakeup) {
3332 return Scheduler::TransactionStart::Early;
3333 }
3334 if (flags & eExplicitEarlyWakeupEnd) {
3335 return Scheduler::TransactionStart::EarlyEnd;
3336 }
3337 if (flags & eExplicitEarlyWakeupStart) {
3338 return Scheduler::TransactionStart::EarlyStart;
3339 }
3340 return Scheduler::TransactionStart::Normal;
3341 }(flags);
3342
Mathias Agopian386aa982011-11-07 21:58:03 -08003343 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003344 if (mInterceptor->isEnabled()) {
3345 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003346 }
Irvel468051e2016-06-13 16:44:44 -07003347
Ady Abrahambf1349c2020-06-12 14:26:18 -07003348 // TODO(b/159125966): Remove eEarlyWakeup completly as no client should use this flag
3349 if (flags & eEarlyWakeup) {
3350 ALOGW("eEarlyWakeup is deprecated. Use eExplicitEarlyWakeup[Start|End]");
3351 }
3352
3353 if (!privileged && (flags & (eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd))) {
3354 ALOGE("Only WindowManager is allowed to use eExplicitEarlyWakeup[Start|End] flags");
3355 flags &= ~(eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd);
3356 }
3357
Mathias Agopian386aa982011-11-07 21:58:03 -08003358 // this triggers the transaction
Ady Abrahambf1349c2020-06-12 14:26:18 -07003359 setTransactionFlags(transactionFlags, transactionStart);
Mathias Agopian386aa982011-11-07 21:58:03 -08003360
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003361 if (flags & eAnimation) {
3362 mAnimTransactionPending = true;
3363 }
Robert Carr238f4a22020-04-29 13:04:02 -07003364
3365 // if this is a synchronous transaction, wait for it to take effect
3366 // before returning.
3367 const bool synchronous = flags & eSynchronous;
3368 const bool syncInput = inputWindowCommands.syncInputWindows;
3369 if (!synchronous && !syncInput) {
3370 return;
3371 }
3372
3373 if (synchronous) {
3374 mTransactionPending = true;
3375 }
3376 if (syncInput) {
chaviw4fe36852019-04-15 16:25:49 -07003377 mPendingSyncInputWindows = true;
3378 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003379
Robert Carr238f4a22020-04-29 13:04:02 -07003380
Valerie Hau0779ded2019-03-19 12:43:04 -07003381 // applyTransactionState can be called by either the main SF thread or by
3382 // another process through setTransactionState. While a given process may wish
3383 // to wait on synchronous transactions, the main SF thread should never
3384 // be blocked. Therefore, we only wait if isMainThread is false.
3385 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003386 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3387 if (CC_UNLIKELY(err != NO_ERROR)) {
3388 // just in case something goes wrong in SF, return to the
3389 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003390 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3391 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003392 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003393 break;
3394 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003395 }
Ady Abrahambf1349c2020-06-12 14:26:18 -07003396 } else {
3397 // even if a transaction is not needed, we need to update VsyncModulator
3398 // about explicit early indications
3399 if (transactionStart == Scheduler::TransactionStart::EarlyStart ||
3400 transactionStart == Scheduler::TransactionStart::EarlyEnd) {
3401 mVSyncModulator->setTransactionStart(transactionStart);
3402 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003403 }
3404}
3405
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003406uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3407 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3408 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003409
Mathias Agopiane57f2922012-08-09 16:29:12 -07003410 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003411 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3412
3413 const uint32_t what = s.what;
3414 if (what & DisplayState::eSurfaceChanged) {
3415 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3416 state.surface = s.surface;
3417 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003418 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003419 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003420 if (what & DisplayState::eLayerStackChanged) {
3421 if (state.layerStack != s.layerStack) {
3422 state.layerStack = s.layerStack;
3423 flags |= eDisplayTransactionNeeded;
3424 }
3425 }
3426 if (what & DisplayState::eDisplayProjectionChanged) {
3427 if (state.orientation != s.orientation) {
3428 state.orientation = s.orientation;
3429 flags |= eDisplayTransactionNeeded;
3430 }
3431 if (state.frame != s.frame) {
3432 state.frame = s.frame;
3433 flags |= eDisplayTransactionNeeded;
3434 }
3435 if (state.viewport != s.viewport) {
3436 state.viewport = s.viewport;
3437 flags |= eDisplayTransactionNeeded;
3438 }
3439 }
3440 if (what & DisplayState::eDisplaySizeChanged) {
3441 if (state.width != s.width) {
3442 state.width = s.width;
3443 flags |= eDisplayTransactionNeeded;
3444 }
3445 if (state.height != s.height) {
3446 state.height = s.height;
3447 flags |= eDisplayTransactionNeeded;
3448 }
3449 }
3450
Mathias Agopiane57f2922012-08-09 16:29:12 -07003451 return flags;
3452}
3453
Steven Thomasd4071902020-03-24 16:02:53 -07003454bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003455 IPCThreadState* ipc = IPCThreadState::self();
3456 const int pid = ipc->getCallingPid();
3457 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003458 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003459 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3460 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003461 return false;
3462 }
3463 return true;
3464}
3465
Marissa Wall3dad52d2019-03-22 14:03:19 -07003466uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003467 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3468 bool privileged,
3469 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003470 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003471
Valerie Hau9dab9732019-08-20 09:29:25 -07003472 for (auto& listener : s.listeners) {
3473 // note that startRegistration will not re-register if the listener has
3474 // already be registered for a prior surface control
3475 mTransactionCompletedThread.startRegistration(listener);
3476 listenerCallbacks.insert(listener);
3477 }
3478
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003479 sp<Layer> layer = nullptr;
3480 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003481 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003482 } else {
3483 // The client may provide us a null handle. Treat it as if the layer was removed.
3484 ALOGW("Attempt to set client state with a null layer handle");
3485 }
chaviw8b3871a2017-11-01 17:41:01 -07003486 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003487 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003488 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003489 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003490 }
chaviw8b3871a2017-11-01 17:41:01 -07003491 return 0;
3492 }
3493
chaviw8b3871a2017-11-01 17:41:01 -07003494 uint32_t flags = 0;
3495
Garfield Tan8a3083e2018-12-03 13:21:07 -08003496 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003497
3498 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3499 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003500 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003501 layer->pushPendingState();
3502 }
3503
Valerie Hau871d6352020-01-29 08:44:02 -08003504 // Only set by BLAST adapter layers
3505 if (what & layer_state_t::eProducerDisconnect) {
3506 layer->onDisconnect();
3507 }
3508
chaviw8b3871a2017-11-01 17:41:01 -07003509 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003510 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003511 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003512 }
chaviw8b3871a2017-11-01 17:41:01 -07003513 }
3514 if (what & layer_state_t::eLayerChanged) {
3515 // NOTE: index needs to be calculated before we update the state
3516 const auto& p = layer->getParent();
3517 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003518 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003519 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003520 mCurrentState.layersSortedByZ.removeAt(idx);
3521 mCurrentState.layersSortedByZ.add(layer);
3522 // we need traversal (state changed)
3523 // AND transaction (list changed)
3524 flags |= eTransactionNeeded|eTraversalNeeded;
3525 }
chaviw8b3871a2017-11-01 17:41:01 -07003526 } else {
3527 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003528 flags |= eTransactionNeeded|eTraversalNeeded;
3529 }
3530 }
chaviw8b3871a2017-11-01 17:41:01 -07003531 }
3532 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003533 // NOTE: index needs to be calculated before we update the state
3534 const auto& p = layer->getParent();
3535 if (p == nullptr) {
3536 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3537 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3538 mCurrentState.layersSortedByZ.removeAt(idx);
3539 mCurrentState.layersSortedByZ.add(layer);
3540 // we need traversal (state changed)
3541 // AND transaction (list changed)
3542 flags |= eTransactionNeeded|eTraversalNeeded;
3543 }
3544 } else {
3545 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3546 flags |= eTransactionNeeded|eTraversalNeeded;
3547 }
chaviw8b3871a2017-11-01 17:41:01 -07003548 }
3549 }
3550 if (what & layer_state_t::eSizeChanged) {
3551 if (layer->setSize(s.w, s.h)) {
3552 flags |= eTraversalNeeded;
3553 }
3554 }
3555 if (what & layer_state_t::eAlphaChanged) {
3556 if (layer->setAlpha(s.alpha))
3557 flags |= eTraversalNeeded;
3558 }
3559 if (what & layer_state_t::eColorChanged) {
3560 if (layer->setColor(s.color))
3561 flags |= eTraversalNeeded;
3562 }
Peiyong Lind3788632018-09-18 16:01:31 -07003563 if (what & layer_state_t::eColorTransformChanged) {
3564 if (layer->setColorTransform(s.colorTransform)) {
3565 flags |= eTraversalNeeded;
3566 }
3567 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003568 if (what & layer_state_t::eBackgroundColorChanged) {
3569 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3570 flags |= eTraversalNeeded;
3571 }
3572 }
chaviw8b3871a2017-11-01 17:41:01 -07003573 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003574 // TODO: b/109894387
3575 //
3576 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3577 // rotation. To see the problem observe that if we have a square parent, and a child
3578 // of the same size, then we rotate the child 45 degrees around it's center, the child
3579 // must now be cropped to a non rectangular 8 sided region.
3580 //
3581 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3582 // private API, and the WindowManager only uses rotation in one case, which is on a top
3583 // level layer in which cropping is not an issue.
3584 //
3585 // However given that abuse of rotation matrices could lead to surfaces extending outside
3586 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3587 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3588 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003589 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003590 flags |= eTraversalNeeded;
3591 }
3592 if (what & layer_state_t::eTransparentRegionChanged) {
3593 if (layer->setTransparentRegionHint(s.transparentRegion))
3594 flags |= eTraversalNeeded;
3595 }
3596 if (what & layer_state_t::eFlagsChanged) {
3597 if (layer->setFlags(s.flags, s.mask))
3598 flags |= eTraversalNeeded;
3599 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003600 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003601 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003602 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003603 if (what & layer_state_t::eCornerRadiusChanged) {
3604 if (layer->setCornerRadius(s.cornerRadius))
3605 flags |= eTraversalNeeded;
3606 }
Lucas Dupin130e55c2020-05-26 16:11:18 -07003607 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003608 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3609 }
chaviw8b3871a2017-11-01 17:41:01 -07003610 if (what & layer_state_t::eLayerStackChanged) {
3611 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3612 // We only allow setting layer stacks for top level layers,
3613 // everything else inherits layer stack from its parent.
3614 if (layer->hasParent()) {
3615 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003616 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003617 } else if (idx < 0) {
3618 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003619 "that also does not appear in the top level layer list. Something"
3620 " has gone wrong.",
3621 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003622 } else if (layer->setLayerStack(s.layerStack)) {
3623 mCurrentState.layersSortedByZ.removeAt(idx);
3624 mCurrentState.layersSortedByZ.add(layer);
3625 // we need traversal (state changed)
3626 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07003627 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003628 }
3629 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003630 if (what & layer_state_t::eDeferTransaction_legacy) {
3631 if (s.barrierHandle_legacy != nullptr) {
3632 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3633 } else if (s.barrierGbp_legacy != nullptr) {
3634 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003635 if (authenticateSurfaceTextureLocked(gbp)) {
3636 const auto& otherLayer =
3637 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003638 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003639 } else {
3640 ALOGE("Attempt to defer transaction to to an"
3641 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003642 }
3643 }
chaviw8b3871a2017-11-01 17:41:01 -07003644 // We don't trigger a traversal here because if no other state is
3645 // changed, we don't want this to cause any more work
3646 }
chaviw8b3871a2017-11-01 17:41:01 -07003647 if (what & layer_state_t::eReparentChildren) {
3648 if (layer->reparentChildren(s.reparentHandle)) {
3649 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003650 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003651 }
chaviw8b3871a2017-11-01 17:41:01 -07003652 if (what & layer_state_t::eDetachChildren) {
3653 layer->detachChildren();
3654 }
3655 if (what & layer_state_t::eOverrideScalingModeChanged) {
3656 layer->setOverrideScalingMode(s.overrideScalingMode);
3657 // We don't trigger a traversal here because if no other state is
3658 // changed, we don't want this to cause any more work
3659 }
Marissa Wall61c58622018-07-18 10:12:20 -07003660 if (what & layer_state_t::eTransformChanged) {
3661 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3662 }
3663 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3664 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3665 flags |= eTraversalNeeded;
3666 }
3667 if (what & layer_state_t::eCropChanged) {
3668 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3669 }
Marissa Wall861616d2018-10-22 12:52:23 -07003670 if (what & layer_state_t::eFrameChanged) {
3671 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3672 }
Marissa Wall61c58622018-07-18 10:12:20 -07003673 if (what & layer_state_t::eAcquireFenceChanged) {
3674 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3675 }
3676 if (what & layer_state_t::eDataspaceChanged) {
3677 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3678 }
3679 if (what & layer_state_t::eHdrMetadataChanged) {
3680 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3681 }
3682 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3683 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3684 }
3685 if (what & layer_state_t::eApiChanged) {
3686 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3687 }
3688 if (what & layer_state_t::eSidebandStreamChanged) {
3689 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3690 }
Robert Carr720e5062018-07-30 17:45:14 -07003691 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003692 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003693 layer->setInputInfo(s.inputInfo);
3694 flags |= eTraversalNeeded;
3695 } else {
3696 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3697 }
Robert Carr720e5062018-07-30 17:45:14 -07003698 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003699 if (what & layer_state_t::eMetadataChanged) {
3700 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3701 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003702 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3703 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3704 flags |= eTraversalNeeded;
3705 }
3706 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003707 if (what & layer_state_t::eShadowRadiusChanged) {
3708 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3709 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003710 if (what & layer_state_t::eFrameRateSelectionPriority) {
3711 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3712 flags |= eTraversalNeeded;
3713 }
3714 }
Steven Thomas3172e202020-01-06 19:25:30 -08003715 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003716 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3717 "SurfaceFlinger::setClientStateLocked") &&
3718 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3719 Layer::FrameRate::convertCompatibility(
3720 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003721 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003722 }
Steven Thomas3172e202020-01-06 19:25:30 -08003723 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003724 if (what & layer_state_t::eFixedTransformHintChanged) {
3725 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
3726 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
3727 }
3728 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003729 // This has to happen after we reparent children because when we reparent to null we remove
3730 // child layers from current state and remove its relative z. If the children are reparented in
3731 // the same transaction, then we have to make sure we reparent the children first so we do not
3732 // lose its relative z order.
3733 if (what & layer_state_t::eReparent) {
3734 bool hadParent = layer->hasParent();
3735 if (layer->reparent(s.parentHandleForChild)) {
3736 if (!hadParent) {
3737 mCurrentState.layersSortedByZ.remove(layer);
3738 }
3739 flags |= eTransactionNeeded | eTraversalNeeded;
3740 }
3741 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003742 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003743 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3744 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003745 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3746 }
3747 }
Marissa Wall78b72202019-03-15 14:58:34 -07003748 bool bufferChanged = what & layer_state_t::eBufferChanged;
3749 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3750 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003751 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003752 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003753 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3754 if (success) {
3755 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3756 success = ClientCache::getInstance()
3757 .registerErasedRecipient(s.cachedBuffer,
3758 wp<ClientCache::ErasedRecipient>(this));
3759 if (!success) {
3760 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3761 }
3762 }
Marissa Wall78b72202019-03-15 14:58:34 -07003763 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003764 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003765 } else if (bufferChanged) {
3766 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003767 }
Marissa Wall78b72202019-03-15 14:58:34 -07003768 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003769 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3770 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003771 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003772 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003773 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003774 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3775 // Do not put anything that updates layer state or modifies flags after
3776 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003777 return flags;
3778}
3779
chaviw273171b2018-12-26 11:46:30 -08003780uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3781 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003782 if (inputWindowCommands.syncInputWindows) {
3783 flags |= eTraversalNeeded;
3784 }
3785
Vishnu Nairec0ab382019-02-13 15:32:56 -08003786 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003787 return flags;
3788}
3789
chaviwfe94a222019-08-21 13:52:59 -07003790status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3791 sp<IBinder>* outHandle) {
3792 if (!mirrorFromHandle) {
3793 return NAME_NOT_FOUND;
3794 }
3795
3796 sp<Layer> mirrorLayer;
3797 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003798 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003799
3800 {
3801 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003802 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003803 if (!mirrorFrom) {
3804 return NAME_NOT_FOUND;
3805 }
3806
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003807 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3808 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003809 if (result != NO_ERROR) {
3810 return result;
3811 }
3812
3813 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3814 }
3815
Vishnu Nair6213bd92020-05-08 17:42:25 -07003816 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false,
3817 nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07003818}
3819
Marissa Wall2d814fb2019-04-09 18:52:57 +00003820status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3821 uint32_t h, PixelFormat format, uint32_t flags,
3822 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003823 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003824 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3825 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003826 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003827 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003828 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003829 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003830 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003831
Robert Carrc0df3122019-04-11 13:18:21 -07003832 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3833 "Expected only one of parentLayer or parentHandle to be non-null. "
3834 "Programmer error?");
3835
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003836 status_t result = NO_ERROR;
3837
3838 sp<Layer> layer;
3839
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003840 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003841
Evan Roskya1f1e152019-01-24 16:17:46 -08003842 bool primaryDisplayOnly = false;
3843
3844 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3845 // TODO b/64227542
3846 if (metadata.has(METADATA_WINDOW_TYPE)) {
3847 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3848 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003849 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003850 primaryDisplayOnly = true;
3851 }
3852 }
3853
Mathias Agopian3165cc22012-08-08 19:42:09 -07003854 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003855 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003856 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3857 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003858
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003859 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003860 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003861 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003862 std::move(metadata), handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003863 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003864 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003865 // check if buffer size is set for color layer.
3866 if (w > 0 || h > 0) {
3867 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3868 int(w), int(h));
3869 return BAD_VALUE;
3870 }
3871
Vishnu Nairfa247b12020-02-11 08:58:26 -08003872 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3873 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003874 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003875 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003876 // check if buffer size is set for container layer.
3877 if (w > 0 || h > 0) {
3878 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3879 int(w), int(h));
3880 return BAD_VALUE;
3881 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003882 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3883 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003884 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003885 default:
3886 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003887 break;
3888 }
3889
Dan Stoza7d89d062015-04-30 13:29:25 -07003890 if (result != NO_ERROR) {
3891 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003892 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003893
Evan Roskya1f1e152019-01-24 16:17:46 -08003894 if (primaryDisplayOnly) {
3895 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003896 }
3897
Robert Carrb89ea9d2018-12-10 13:01:14 -08003898 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003899 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003900 addToCurrentState, outTransformHint);
Dan Stoza7d89d062015-04-30 13:29:25 -07003901 if (result != NO_ERROR) {
3902 return result;
3903 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003904 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003905
3906 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003907 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003908}
3909
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003910std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3911 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003912
3913 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003914 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003915
Dan Stoza436ccf32018-06-21 12:10:12 -07003916 // Grab the state lock since we're accessing mCurrentState
3917 Mutex::Autolock lock(mStateLock);
3918
Cody Northropbc755282017-03-31 12:00:08 -06003919 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003920 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003921 while (matchFound) {
3922 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003923 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003924 if (layer->getName() == uniqueName) {
3925 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003926 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003927 }
3928 });
3929 }
3930
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003931 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003932 return uniqueName;
3933}
3934
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003935status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003936 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003937 LayerMetadata metadata, PixelFormat& format,
3938 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003939 sp<IGraphicBufferProducer>* gbp,
3940 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003941 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003942 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003943 case PIXEL_FORMAT_TRANSPARENT:
3944 case PIXEL_FORMAT_TRANSLUCENT:
3945 format = PIXEL_FORMAT_RGBA_8888;
3946 break;
3947 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003948 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003949 break;
3950 }
3951
chaviwb4c6e582019-08-16 14:35:07 -07003952 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003953 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003954 args.textureName = getNewTexture();
3955 {
3956 // Grab the SF state lock during this since it's the only safe way to access
3957 // RenderEngine when creating a BufferLayerConsumer
3958 // TODO: Check if this lock is still needed here
3959 Mutex::Autolock lock(mStateLock);
3960 layer = getFactory().createBufferQueueLayer(args);
3961 }
3962
Marissa Wallfd668622018-05-10 10:21:13 -07003963 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003964 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003965 *handle = layer->getHandle();
3966 *gbp = layer->getProducer();
3967 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003968 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003969
Marissa Wallfd668622018-05-10 10:21:13 -07003970 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003971 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003972}
3973
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003974status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003975 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003976 LayerMetadata metadata, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003977 sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003978 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003979 args.textureName = getNewTexture();
3980 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07003981 *handle = layer->getHandle();
3982 *outLayer = layer;
3983
3984 return NO_ERROR;
3985}
3986
Vishnu Nairfa247b12020-02-11 08:58:26 -08003987status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3988 uint32_t h, uint32_t flags, LayerMetadata metadata,
3989 sp<IBinder>* handle, sp<Layer>* outLayer) {
3990 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003991 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003992 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003993 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003994}
3995
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003996status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003997 uint32_t w, uint32_t h, uint32_t flags,
3998 LayerMetadata metadata, sp<IBinder>* handle,
3999 sp<Layer>* outLayer) {
4000 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004001 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004002 *handle = (*outLayer)->getHandle();
4003 return NO_ERROR;
4004}
4005
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004006void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004007 mLayersPendingRemoval.add(layer);
4008 mLayersRemoved = true;
4009 setTransactionFlags(eTransactionNeeded);
4010}
4011
Robert Carr695d5282018-12-18 15:27:58 -08004012void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004013{
Robert Carr2e102c92018-10-23 12:11:15 -07004014 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004015 // If a layer has a parent, we allow it to out-live it's handle
4016 // with the idea that the parent holds a reference and will eventually
4017 // be cleaned up. However no one cleans up the top-level so we do so
4018 // here.
4019 if (layer->getParent() == nullptr) {
4020 mCurrentState.layersSortedByZ.remove(layer);
4021 }
4022 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004023
4024 auto it = mLayersByLocalBinderToken.begin();
4025 while (it != mLayersByLocalBinderToken.end()) {
4026 if (it->second == layer) {
4027 it = mLayersByLocalBinderToken.erase(it);
4028 } else {
4029 it++;
4030 }
4031 }
4032
Robert Carr695d5282018-12-18 15:27:58 -08004033 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004034}
4035
Mathias Agopianb60314a2012-04-10 22:09:54 -07004036// ---------------------------------------------------------------------------
4037
Andy McFadden13a082e2012-08-24 10:16:42 -07004038void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004039 const auto display = getDefaultDisplayDeviceLocked();
4040 if (!display) return;
4041
4042 const sp<IBinder> token = display->getDisplayToken().promote();
4043 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004044
Jesse Hall01e29052013-02-19 16:13:35 -08004045 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004046 Vector<ComposerState> state;
4047 Vector<DisplayState> displays;
4048 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004049 d.what = DisplayState::eDisplayProjectionChanged |
4050 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004051 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004052 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004053 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004054 d.frame.makeInvalid();
4055 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004056 d.width = 0;
4057 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004058 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004059 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4060 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004061
Peiyong Lin65248e02020-04-18 21:15:07 -07004062 setPowerModeInternal(display, hal::PowerMode::ON);
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004063 const nsecs_t vsyncPeriod = mRefreshRateConfigs->getCurrentRefreshRate().getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004064 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004065
Brian Andersond0010582017-03-07 13:20:31 -08004066 // Use phase of 0 since phase is not known.
4067 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004068 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004069 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004070}
4071
4072void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004073 // Async since we may be called from the main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004074 static_cast<void>(schedule([this]() MAIN_THREAD { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004075}
4076
Peiyong Lin65248e02020-04-18 21:15:07 -07004077void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004078 if (display->isVirtual()) {
4079 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004080 return;
4081 }
4082
Dominik Laskowski075d3172018-05-24 15:50:06 -07004083 const auto displayId = display->getId();
4084 LOG_ALWAYS_FATAL_IF(!displayId);
4085
Dominik Laskowski34157762018-10-31 13:07:19 -07004086 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004087
Peiyong Lin65248e02020-04-18 21:15:07 -07004088 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004089 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004090 return;
4091 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004093 display->setPowerMode(mode);
4094
Lloyd Pique4dccc412018-01-22 17:21:36 -08004095 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004096 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004097 }
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004098 const auto vsyncPeriod = mRefreshRateConfigs->getCurrentRefreshRate().getVsyncPeriod();
Peiyong Lin65248e02020-04-18 21:15:07 -07004099 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004100 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4101 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4102 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004103 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004104 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004105 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004106 mScheduler->onScreenAcquired(mAppConnectionHandle);
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004107 mScheduler->resyncToHardwareVsync(true, vsyncPeriod);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004108 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004109
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004110 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004111 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004112 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004113 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004114 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004115 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4116 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004117 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004118 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004119 mScheduler->disableHardwareVsync(true);
4120 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004121 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004122
Ady Abraham27c70212019-06-11 10:52:26 -07004123 // Make sure HWVsync is disabled before turning off the display
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004124 getHwComposer().setVsyncEnabled(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004125
Dominik Laskowski075d3172018-05-24 15:50:06 -07004126 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004127 mVisibleRegionsDirty = true;
4128 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004129 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004130 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004131 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004132 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004133 mScheduler->onScreenAcquired(mAppConnectionHandle);
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004134 mScheduler->resyncToHardwareVsync(true, vsyncPeriod);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004135 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004136 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004137 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004138 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004139 mScheduler->disableHardwareVsync(true);
4140 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004141 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004142 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004143 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004144 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004145 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004146 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004147
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004148 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004149 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004150 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004151 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004152 }
4153
Dominik Laskowski34157762018-10-31 13:07:19 -07004154 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004155}
4156
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004157void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004158 schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004159 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004160 if (!display) {
4161 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4162 displayToken.get());
4163 } else if (display->isVirtual()) {
4164 ALOGW("Attempt to set power mode %d for virtual display", mode);
4165 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004166 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004167 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004168 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004169}
4170
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004171status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004172 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004173
Mathias Agopianbd115332013-04-18 16:41:04 -07004174 IPCThreadState* ipc = IPCThreadState::self();
4175 const int pid = ipc->getCallingPid();
4176 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004177
Mathias Agopianbd115332013-04-18 16:41:04 -07004178 if ((uid != AID_SHELL) &&
4179 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004180 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4181 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004182 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004183 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004184 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004185 {"--dispsync"s,
4186 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004187 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004188 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4189 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4190 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4191 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4192 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4193 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004194 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004195 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4196 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004197
Dominik Laskowskic2867142019-01-21 11:33:38 -08004198 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004199
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004200 bool dumpLayers = true;
4201 {
4202 TimedLock lock(mStateLock, s2ns(1), __FUNCTION__);
4203 if (!lock.locked()) {
4204 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4205 strerror(-lock.status), lock.status);
4206 }
4207
4208 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4209 (it->second)(args, asProto, result);
4210 dumpLayers = false;
4211 } else if (!asProto) {
4212 dumpAllLocked(args, result);
4213 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004214 }
4215
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004216 if (dumpLayers) {
Dominik Laskowski46470112019-08-02 13:13:11 -07004217 const LayersProto layersProto = dumpProtoFromMainThread();
4218 if (asProto) {
4219 result.append(layersProto.SerializeAsString());
4220 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004221 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004222 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4223 result.append(LayerProtoParser::layerTreeToString(layerTree));
4224 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004225 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004226 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004227 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004228 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004229 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004230 return NO_ERROR;
4231}
4232
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004233status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4234 if (asProto && mTracing.isEnabled()) {
4235 mTracing.writeToFileAsync();
4236 }
4237
4238 return doDump(fd, DumpArgs(), asProto);
4239}
4240
Dominik Laskowskic2867142019-01-21 11:33:38 -08004241void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004242 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004243 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004244}
4245
Dominik Laskowskic2867142019-01-21 11:33:38 -08004246void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004247 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004248
Dominik Laskowskic2867142019-01-21 11:33:38 -08004249 if (args.size() > 1) {
4250 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004251 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004252 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004253 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004254 }
Robert Carr2047fae2016-11-28 14:09:09 -08004255 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004256 } else {
4257 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004258 }
4259}
4260
Dominik Laskowskic2867142019-01-21 11:33:38 -08004261void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004262 const bool clearAll = args.size() < 2;
4263 const auto name = clearAll ? String8() : String8(args[1]);
4264
Edgar Arriaga844fa672020-01-16 14:21:42 -08004265 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004266 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004267 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004268 }
Robert Carr2047fae2016-11-28 14:09:09 -08004269 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004270
Svetoslavd85084b2014-03-20 10:28:31 -07004271 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004272}
4273
Dominik Laskowskic2867142019-01-21 11:33:38 -08004274void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4275 mTimeStats->parseArgs(asProto, args, result);
4276}
4277
Jamie Gennis6547ff42013-07-16 20:12:42 -07004278// This should only be called from the main thread. Otherwise it would need
4279// the lock and should use mCurrentState rather than mDrawingState.
4280void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004281 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004282 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004283 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004284
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004285 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004286}
4287
Yiwei Zhang5434a782018-12-05 18:06:32 -08004288void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004289 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004290
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004291 if (isLayerTripleBufferingDisabled())
4292 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004293
Yiwei Zhang5434a782018-12-05 18:06:32 -08004294 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4295 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4296 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4297 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4298 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4299 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004300 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004301}
4302
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004303void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004304 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004305
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004306 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004307 result.append("\n");
4308
Ady Abraham9e16a482019-12-03 17:19:41 -08004309 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004310 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004311 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abrahamf69d11d2020-07-24 11:09:55 -07004312 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004313
Steven Thomasd4071902020-03-24 16:02:53 -07004314 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004315 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004316 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004317 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4318 policy.defaultConfig.value(), policy.primaryRange.min, policy.primaryRange.max,
4319 policy.appRequestRange.min, policy.appRequestRange.max);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004320 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4321 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004322 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4323 if (currentPolicy != policy) {
4324 StringAppendF(&result,
4325 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004326 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4327 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
4328 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
4329 currentPolicy.appRequestRange.max);
Ady Abraham07e54702020-04-16 15:05:37 -07004330 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004331
Ana Krulecc2870422019-01-29 19:00:58 -08004332 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004333 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004334}
4335
Yiwei Zhang5434a782018-12-05 18:06:32 -08004336void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4337 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004338 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4339 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004340 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004341 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004342 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004343 }
David Sodman4a36e932017-11-07 14:29:47 -08004344 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004345 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004346 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004347 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4348 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004349}
4350
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004351void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4352 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004353 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4354 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004355 for (const auto& segment : history) {
4356 if (!segment.usedThirdBuffer) {
4357 stats.twoBufferTime += segment.totalTime;
4358 }
4359 if (segment.occupancyAverage < 1.0f) {
4360 stats.doubleBufferedTime += segment.totalTime;
4361 } else if (segment.occupancyAverage < 2.0f) {
4362 stats.tripleBufferedTime += segment.totalTime;
4363 }
4364 ++stats.numSegments;
4365 stats.totalTime += segment.totalTime;
4366 }
4367}
4368
Yiwei Zhang5434a782018-12-05 18:06:32 -08004369void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4370 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004371
4372 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4373 const size_t count = currentLayers.size();
4374 for (size_t i=0 ; i<count ; i++) {
4375 currentLayers[i]->dumpFrameEvents(result);
4376 }
4377}
4378
Yiwei Zhang5434a782018-12-05 18:06:32 -08004379void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004380 result.append("Buffering stats:\n");
4381 result.append(" [Layer name] <Active time> <Two buffer> "
4382 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004383 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004384 typedef std::tuple<std::string, float, float, float> BufferTuple;
4385 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004386 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004387 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004388 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004389 if (stats.numSegments == 0) {
4390 continue;
4391 }
4392 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4393 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4394 stats.totalTime;
4395 float doubleBufferRatio = static_cast<float>(
4396 stats.doubleBufferedTime) / stats.totalTime;
4397 float tripleBufferRatio = static_cast<float>(
4398 stats.tripleBufferedTime) / stats.totalTime;
4399 sorted.insert({activeTime, {name, twoBufferRatio,
4400 doubleBufferRatio, tripleBufferRatio}});
4401 }
4402 for (const auto& sortedPair : sorted) {
4403 float activeTime = sortedPair.first;
4404 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004405 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4406 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004407 }
4408 result.append("\n");
4409}
4410
Yiwei Zhang5434a782018-12-05 18:06:32 -08004411void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004412 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004413 const auto displayId = display->getId();
4414 if (!displayId) {
4415 continue;
4416 }
4417 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004418 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004419 continue;
4420 }
4421
Yiwei Zhang5434a782018-12-05 18:06:32 -08004422 StringAppendF(&result,
4423 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4424 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004425 uint8_t port;
4426 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004427 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004428 result.append("no identification data\n");
4429 continue;
4430 }
4431
4432 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004433 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004434 continue;
4435 }
4436
4437 const auto edid = parseEdid(data);
4438 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004439 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004440 continue;
4441 }
4442
Yiwei Zhang5434a782018-12-05 18:06:32 -08004443 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004444 result.append(edid->displayName.data(), edid->displayName.length());
4445 result.append("\"\n");
4446 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004447}
4448
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004449void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4450 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004451 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004452 uint8_t port;
4453 DisplayIdentificationData data;
4454
4455 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4456 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4457 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4458 }
4459}
4460
Yiwei Zhang5434a782018-12-05 18:06:32 -08004461void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004462 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004463 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4464 StringAppendF(&result, "DisplayColorSetting: %s\n",
4465 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004466
4467 // TODO: print out if wide-color mode is active or not
4468
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004469 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004470 const auto displayId = display->getId();
4471 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004472 continue;
4473 }
4474
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004476 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004477 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004478 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004479 }
4480
Lloyd Pique32cbe282018-10-19 13:09:22 -07004481 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004482 StringAppendF(&result, " Current color mode: %s (%d)\n",
4483 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004484 }
4485 result.append("\n");
4486}
4487
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004488LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4489 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004490 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004491
chaviw1d044282017-09-27 12:19:28 -07004492 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004493 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004494 layer->writeToProto(layersProto, traceFlags, display.get());
chaviw08f3cb22020-01-13 13:17:21 -08004495 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004496
chaviw1d044282017-09-27 12:19:28 -07004497 return layersProto;
4498}
4499
Alec Mouri6b9e9912020-01-21 10:50:24 -08004500void SurfaceFlinger::dumpHwc(std::string& result) const {
4501 getHwComposer().dump(result);
4502}
4503
Vishnu Nair0f085c62019-08-30 08:49:12 -07004504void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4505 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4506 // it.
4507 LayerProto* rootProto = layersProto.add_layers();
4508 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4509 rootProto->set_id(offscreenRootLayerId);
4510 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004511 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004512
4513 for (Layer* offscreenLayer : mOffscreenLayers) {
4514 // Add layer as child of the fake root
4515 rootProto->add_children(offscreenLayer->sequence);
4516
4517 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004518 LayerProto* layerProto =
4519 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004520 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004521 }
4522}
4523
Vishnu Nair8406fd72019-07-30 11:29:31 -07004524LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004525 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004526}
4527
Vishnu Nair0f085c62019-08-30 08:49:12 -07004528void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4529 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004530 result.append(schedule([this] {
4531 std::string result;
4532 for (Layer* offscreenLayer : mOffscreenLayers) {
4533 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4534 [&](Layer* layer) {
4535 layer->dumpCallingUidPid(result);
4536 });
4537 }
4538 return result;
4539 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004540}
4541
Dominik Laskowskic2867142019-01-21 11:33:38 -08004542void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4543 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004544 Colorizer colorizer(colorize);
4545
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004546 // figure out if we're stuck somewhere
4547 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004548 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004549 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4550
4551 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004552 * Dump library configuration.
4553 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004554
4555 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004556 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004557 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004558 appendSfConfigString(result);
4559 appendUiConfigString(result);
4560 appendGuiConfigString(result);
4561 result.append("\n");
4562
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004563 result.append("\nDisplay identification data:\n");
4564 dumpDisplayIdentificationData(result);
4565
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004566 result.append("\nWide-Color information:\n");
4567 dumpWideColorInfo(result);
4568
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004569 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004570 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004571 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004572 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004573 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004574
Andy McFadden41d67d72014-04-25 16:58:34 -07004575 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004576 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004577 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004578 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004579 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004580
Dan Stozab90cf072015-03-05 11:05:59 -08004581 dumpStaticScreenStats(result);
4582 result.append("\n");
4583
Alec Mouri40189b02019-03-05 15:07:54 -08004584 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4585 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4586 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004587
Dan Stozae77c7662016-05-13 11:37:28 -07004588 dumpBufferingStats(result);
4589
Andy McFadden4803b742012-09-24 19:07:20 -07004590 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004591 * Dump the visible layer list
4592 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004593 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004594 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004595 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4596 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004597 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004598
Chia-I Wu2f884132018-09-13 15:17:58 -07004599 {
Lloyd Pique207def92019-02-28 16:09:52 -08004600 StringAppendF(&result, "Composition layers\n");
4601 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004602 auto* compositionState = layer->getCompositionState();
4603 if (!compositionState) return;
4604
4605 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4606 layer->getDebugName() ? layer->getDebugName()
4607 : "<unknown>");
4608 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004609 });
4610 }
4611
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004612 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004613 * Dump Display state
4614 */
4615
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004616 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004617 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004618 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004619 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004620 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004621 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004622 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004623
4624 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004625 * Dump CompositionEngine state
4626 */
4627
4628 mCompositionEngine->dump(result);
4629
4630 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004631 * Dump SurfaceFlinger global state
4632 */
4633
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004634 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004635 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004636 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004637
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004638 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004639
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004640 DebugEGLImageTracker::getInstance()->dump(result);
4641
Dominik Laskowski075d3172018-05-24 15:50:06 -07004642 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004643 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4644 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004645 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4646 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004647 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004648 StringAppendF(&result,
4649 " transaction-flags : %08x\n"
4650 " gpu_to_cpu_unsupported : %d\n",
4651 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004652
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004653 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004654 displayId && getHwComposer().isConnected(*displayId)) {
4655 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004656 StringAppendF(&result,
4657 " refresh-rate : %f fps\n"
4658 " x-dpi : %f\n"
4659 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004660 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4661 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004662 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004663
Yiwei Zhang5434a782018-12-05 18:06:32 -08004664 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004665
Dan Stozae22aec72016-08-01 13:20:59 -07004666 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004667 * Tracing state
4668 */
4669 mTracing.dump(result);
4670 result.append("\n");
4671
4672 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004673 * HWC layer minidump
4674 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004675 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004676 const auto displayId = display->getId();
4677 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004678 continue;
4679 }
4680
Yiwei Zhang5434a782018-12-05 18:06:32 -08004681 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004682 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004683
4684 const DisplayDevice& ref = *display;
4685 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07004686 result.append("\n");
4687 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004688
4689 /*
4690 * Dump HWComposer state
4691 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004692 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004693 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004694 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004695 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004696 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004697 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004698
4699 /*
4700 * Dump gralloc state
4701 */
4702 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4703 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004704
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004705 result.append(mTimeStats->miniDump());
4706 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004707}
4708
Chia-I Wu28f320b2018-05-03 11:02:56 -07004709void SurfaceFlinger::updateColorMatrixLocked() {
4710 mat4 colorMatrix;
4711 if (mGlobalSaturationFactor != 1.0f) {
4712 // Rec.709 luma coefficients
4713 float3 luminance{0.213f, 0.715f, 0.072f};
4714 luminance *= 1.0f - mGlobalSaturationFactor;
4715 mat4 saturationMatrix = mat4(
4716 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4717 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4718 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4719 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4720 );
4721 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4722 } else {
4723 colorMatrix = mClientColorMatrix * mDaltonizer();
4724 }
4725
4726 if (mCurrentState.colorMatrix != colorMatrix) {
4727 mCurrentState.colorMatrix = colorMatrix;
4728 mCurrentState.colorMatrixChanged = true;
4729 setTransactionFlags(eTransactionNeeded);
4730 }
4731}
4732
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004733status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004734#pragma clang diagnostic push
4735#pragma clang diagnostic error "-Wswitch-enum"
4736 switch (static_cast<ISurfaceComposerTag>(code)) {
4737 // These methods should at minimum make sure that the client requested
4738 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004739 case BOOT_FINISHED:
4740 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004741 case CREATE_DISPLAY:
4742 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004743 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004744 case GET_ANIMATION_FRAME_STATS:
4745 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004746 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004747 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004748 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004749 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4750 case SET_AUTO_LOW_LATENCY_MODE:
4751 case GET_GAME_CONTENT_TYPE_SUPPORT:
4752 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004753 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004754 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004755 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004756 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004757 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004758 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004759 case SET_GLOBAL_SHADOW_SETTINGS:
4760 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4761 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4762 // necessary permission dynamically. Don't use the permission cache for this check.
4763 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4764 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004765 IPCThreadState* ipc = IPCThreadState::self();
4766 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4767 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004768 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004769 }
Robert Carr1db73f62016-12-21 12:58:51 -08004770 return OK;
4771 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004772 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004773 IPCThreadState* ipc = IPCThreadState::self();
4774 const int pid = ipc->getCallingPid();
4775 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004776 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4777 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004778 return PERMISSION_DENIED;
4779 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004780 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004781 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004782 // Used by apps to hook Choreographer to SurfaceFlinger.
4783 case CREATE_DISPLAY_EVENT_CONNECTION:
4784 // The following calls are currently used by clients that do not
4785 // request necessary permissions. However, they do not expose any secret
4786 // information, so it is OK to pass them.
4787 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004788 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004789 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004790 case GET_PHYSICAL_DISPLAY_IDS:
4791 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004792 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004793 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004794 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004795 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004796 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004797 case GET_DISPLAY_STATS:
4798 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4799 // Calling setTransactionState is safe, because you need to have been
4800 // granted a reference to Client* and Handle* to do anything with it.
4801 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004802 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004803 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004804 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004805 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004806 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004807 // setFrameRate() is deliberately available for apps to call without any
4808 // special permissions.
4809 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004810 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4811 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004812 return OK;
4813 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004814 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004815 case CAPTURE_SCREEN:
4816 case ADD_REGION_SAMPLING_LISTENER:
4817 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004818 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004819 IPCThreadState* ipc = IPCThreadState::self();
4820 const int pid = ipc->getCallingPid();
4821 const int uid = ipc->getCallingUid();
4822 if ((uid != AID_GRAPHICS) &&
4823 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4824 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4825 return PERMISSION_DENIED;
4826 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004827 return OK;
4828 }
chaviw93df2ea2019-04-30 16:45:12 -07004829 case CAPTURE_SCREEN_BY_ID: {
4830 IPCThreadState* ipc = IPCThreadState::self();
4831 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004832 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004833 return OK;
4834 }
4835 return PERMISSION_DENIED;
4836 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004837 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004838
4839 // These codes are used for the IBinder protocol to either interrogate the recipient
4840 // side of the transaction for its canonical interface descriptor or to dump its state.
4841 // We let them pass by default.
4842 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4843 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4844 code == IBinder::SYSPROPS_TRANSACTION) {
4845 return OK;
4846 }
Ady Abraham07e54702020-04-16 15:05:37 -07004847 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004848 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004849 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004850 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4851 return OK;
4852 }
4853 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4854 return PERMISSION_DENIED;
4855#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004856}
4857
Ana Krulec13be8ad2018-08-21 02:43:56 +00004858status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4859 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004860 status_t credentialCheck = CheckTransactCodeCredentials(code);
4861 if (credentialCheck != OK) {
4862 return credentialCheck;
4863 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004864
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004865 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4866 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004867 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004868 IPCThreadState* ipc = IPCThreadState::self();
4869 const int uid = ipc->getCallingUid();
4870 if (CC_UNLIKELY(uid != AID_SYSTEM
4871 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004872 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004873 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004874 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004875 return PERMISSION_DENIED;
4876 }
4877 int n;
4878 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004879 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004880 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004881 return NO_ERROR;
4882 case 1002: // SHOW_UPDATES
4883 n = data.readInt32();
4884 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004885 invalidateHwcGeometry();
4886 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004887 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004888 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004889 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004890 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004891 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004892 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004893 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004894 setTransactionFlags(
4895 eTransactionNeeded|
4896 eDisplayTransactionNeeded|
4897 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004898 return NO_ERROR;
4899 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004900 case 1006:{ // send empty update
4901 signalRefresh();
4902 return NO_ERROR;
4903 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004904 case 1008: // toggle use of hw composer
4905 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004906 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004907 invalidateHwcGeometry();
4908 repaintEverything();
4909 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004910 case 1009: // toggle use of transform hint
4911 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004912 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004913 invalidateHwcGeometry();
4914 repaintEverything();
4915 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004916 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004917 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004918 reply->writeInt32(0);
4919 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004920 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004921 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004922 return NO_ERROR;
4923 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004924 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004925 if (!display) {
4926 return NAME_NOT_FOUND;
4927 }
4928
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004929 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004930 return NO_ERROR;
4931 }
4932 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004933 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004934 // daltonize
4935 n = data.readInt32();
4936 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004937 case 1:
4938 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4939 break;
4940 case 2:
4941 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4942 break;
4943 case 3:
4944 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4945 break;
4946 default:
4947 mDaltonizer.setType(ColorBlindnessType::None);
4948 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004949 }
4950 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004951 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004952 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004953 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004954 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004955
4956 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004957 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004958 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004959 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004960 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004961 // apply a color matrix
4962 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004963 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004964 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004965 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004966 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004967 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004968 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004969 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004970 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004971 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004972 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004973
4974 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4975 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004976 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004977 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4978 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4979 }
4980
Chia-I Wu28f320b2018-05-03 11:02:56 -07004981 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004982 return NO_ERROR;
4983 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004984 case 1016: { // Unused.
4985 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004986 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004987 case 1017: {
4988 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004989 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004990 return NO_ERROR;
4991 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004992 case 1018: { // Modify Choreographer's phase offset
4993 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004994 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004995 return NO_ERROR;
4996 }
4997 case 1019: { // Modify SurfaceFlinger's phase offset
4998 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004999 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005000 return NO_ERROR;
5001 }
Irvel468051e2016-06-13 16:44:44 -07005002 case 1020: { // Layer updates interceptor
5003 n = data.readInt32();
5004 if (n) {
5005 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005006 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005007 }
5008 else{
5009 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005010 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005011 }
5012 return NO_ERROR;
5013 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005014 case 1021: { // Disable HWC virtual displays
5015 n = data.readInt32();
5016 mUseHwcVirtualDisplays = !n;
5017 return NO_ERROR;
5018 }
Romain Guy0147a172017-06-01 13:53:56 -07005019 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005020 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005021 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005022
Chia-I Wu28f320b2018-05-03 11:02:56 -07005023 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005024 return NO_ERROR;
5025 }
Romain Guy54f154a2017-10-24 21:40:32 +01005026 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005027 int32_t colorMode;
5028
Chia-I Wu0d711262018-05-21 15:19:35 -07005029 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005030 if (data.readInt32(&colorMode) == NO_ERROR) {
5031 mForceColorMode = static_cast<ColorMode>(colorMode);
5032 }
Romain Guy54f154a2017-10-24 21:40:32 +01005033 invalidateHwcGeometry();
5034 repaintEverything();
5035 return NO_ERROR;
5036 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005037 // Deprecate, use 1030 to check whether the device is color managed.
5038 case 1024: {
5039 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005040 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005041 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005042 n = data.readInt32();
5043 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005044 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005045 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005046 reply->writeInt32(NO_ERROR);
5047 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005048 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005049 mTracingEnabledChanged = mTracing.disable();
5050 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005051 reply->writeInt32(mTracing.writeToFile());
5052 } else {
5053 reply->writeInt32(NO_ERROR);
5054 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005055 }
5056 return NO_ERROR;
5057 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005058 case 1026: { // Get layer tracing status
5059 reply->writeBool(mTracing.isEnabled());
5060 return NO_ERROR;
5061 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005062 // Is a DisplayColorSetting supported?
5063 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005064 const auto display = getDefaultDisplayDevice();
5065 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005066 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005067 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005068
5069 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5070 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005071 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005072 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005073 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005074 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005075 reply->writeBool(true);
5076 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005077 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005078 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005079 break;
5080 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005081 reply->writeBool(
5082 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005083 break;
5084 }
5085 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005086 }
Alec Mouri643053a2020-09-09 18:57:07 -07005087 case 1028: { // Unused.
5088 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005089 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005090 // Set buffer size for SF tracing (value in KB)
5091 case 1029: {
5092 n = data.readInt32();
5093 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5094 ALOGW("Invalid buffer size: %d KB", n);
5095 reply->writeInt32(BAD_VALUE);
5096 return BAD_VALUE;
5097 }
5098
5099 ALOGD("Updating trace buffer to %d KB", n);
5100 mTracing.setBufferSize(n * 1024);
5101 reply->writeInt32(NO_ERROR);
5102 return NO_ERROR;
5103 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005104 // Is device color managed?
5105 case 1030: {
5106 reply->writeBool(useColorManagement);
5107 return NO_ERROR;
5108 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005109 // Override default composition data space
5110 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5111 // && adb shell stop zygote && adb shell start zygote
5112 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5113 // adb shell stop zygote && adb shell start zygote
5114 case 1031: {
5115 Mutex::Autolock _l(mStateLock);
5116 n = data.readInt32();
5117 if (n) {
5118 n = data.readInt32();
5119 if (n) {
5120 Dataspace dataspace = static_cast<Dataspace>(n);
5121 if (!validateCompositionDataspace(dataspace)) {
5122 return BAD_VALUE;
5123 }
5124 mDefaultCompositionDataspace = dataspace;
5125 }
5126 n = data.readInt32();
5127 if (n) {
5128 Dataspace dataspace = static_cast<Dataspace>(n);
5129 if (!validateCompositionDataspace(dataspace)) {
5130 return BAD_VALUE;
5131 }
5132 mWideColorGamutCompositionDataspace = dataspace;
5133 }
5134 } else {
5135 // restore composition data space.
5136 mDefaultCompositionDataspace = defaultCompositionDataspace;
5137 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5138 }
5139 return NO_ERROR;
5140 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005141 // Set trace flags
5142 case 1033: {
5143 n = data.readUint32();
5144 ALOGD("Updating trace flags to 0x%x", n);
5145 mTracing.setTraceFlags(n);
5146 reply->writeInt32(NO_ERROR);
5147 return NO_ERROR;
5148 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005149 case 1034: {
Dominik Laskowski20134642020-04-20 22:36:44 -07005150 switch (n = data.readInt32()) {
5151 case 0:
5152 case 1:
5153 enableRefreshRateOverlay(static_cast<bool>(n));
5154 break;
5155 default: {
5156 Mutex::Autolock lock(mStateLock);
5157 reply->writeBool(mRefreshRateOverlay != nullptr);
5158 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005159 }
5160 return NO_ERROR;
5161 }
Ady Abraham34392f72019-04-10 11:29:27 -07005162 case 1035: {
5163 n = data.readInt32();
5164 mDebugDisplayConfigSetByBackdoor = false;
5165 if (n >= 0) {
5166 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005167 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005168 if (result != NO_ERROR) {
5169 return result;
5170 }
5171 mDebugDisplayConfigSetByBackdoor = true;
5172 }
5173 return NO_ERROR;
5174 }
Ady Abraham07e54702020-04-16 15:05:37 -07005175 case 1036: {
5176 if (data.readInt32() > 0) {
5177 status_t result =
5178 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5179 if (result != NO_ERROR) {
5180 return result;
5181 }
5182 } else {
5183 mDebugFrameRateFlexibilityToken = nullptr;
5184 }
5185 return NO_ERROR;
5186 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005187 }
5188 }
5189 return err;
5190}
5191
Steven Thomas6d8110b2017-08-31 18:24:21 -07005192void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005193 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005194 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005195}
5196
Ana Krulec7d1d6832018-12-27 11:10:09 -08005197void SurfaceFlinger::repaintEverythingForHWC() {
5198 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005199 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005200 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005201}
5202
Ady Abrahama09852a2020-02-20 14:23:42 -08005203void SurfaceFlinger::kernelTimerChanged(bool expired) {
5204 static bool updateOverlay =
5205 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005206 if (!updateOverlay) return;
5207 if (Mutex::Autolock lock(mStateLock); !mRefreshRateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005208
5209 // Update the overlay on the main thread to avoid race conditions with
5210 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowski20134642020-04-20 22:36:44 -07005211 static_cast<void>(schedule([=] {
5212 const auto desiredActiveConfig = getDesiredActiveConfig();
5213 const auto& current = desiredActiveConfig
5214 ? mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId)
5215 : mRefreshRateConfigs->getCurrentRefreshRate();
5216 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5217
5218 if (current != min) {
Ana Krulecb9afd792020-06-11 13:16:15 -07005219 const bool timerExpired = mKernelIdleTimerEnabled && expired;
Ady Abrahama09852a2020-02-20 14:23:42 -08005220
Dominik Laskowski20134642020-04-20 22:36:44 -07005221 if (Mutex::Autolock lock(mStateLock); mRefreshRateOverlay) {
Ady Abrahama09852a2020-02-20 14:23:42 -08005222 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
Ady Abrahama09852a2020-02-20 14:23:42 -08005223 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005224 mEventQueue->invalidate();
Ady Abrahama09852a2020-02-20 14:23:42 -08005225 }
5226 }));
5227}
5228
Ana Krulecb9afd792020-06-11 13:16:15 -07005229void SurfaceFlinger::toggleKernelIdleTimer() {
5230 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
5231
5232 // If the support for kernel idle timer is disabled in SF code, don't do anything.
5233 if (!mSupportKernelIdleTimer) {
5234 return;
5235 }
5236 const KernelIdleTimerAction action = mRefreshRateConfigs->getIdleTimerAction();
5237
5238 switch (action) {
5239 case KernelIdleTimerAction::TurnOff:
5240 if (mKernelIdleTimerEnabled) {
5241 ATRACE_INT("KernelIdleTimer", 0);
5242 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "false");
5243 mKernelIdleTimerEnabled = false;
5244 }
5245 break;
5246 case KernelIdleTimerAction::TurnOn:
5247 if (!mKernelIdleTimerEnabled) {
5248 ATRACE_INT("KernelIdleTimer", 1);
5249 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "true");
5250 mKernelIdleTimerEnabled = true;
5251 }
5252 break;
5253 case KernelIdleTimerAction::NoChange:
5254 break;
5255 }
5256}
5257
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005258// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5259class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005260public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005261 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5262 ~WindowDisconnector() {
5263 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005264 }
5265
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005266private:
5267 ANativeWindow* mWindow;
5268 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005269};
5270
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005271status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005272 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005273 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5274 const Rect& sourceCrop, uint32_t reqWidth,
5275 uint32_t reqHeight, bool useIdentityTransform,
5276 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005277 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005278
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005279 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005280
Dominik Laskowski718f9602019-11-09 20:01:35 -08005281 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5282 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5283 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5284 renderAreaRotation = ui::Transform::ROT_0;
5285 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005286
Chia-I Wu20261cb2018-08-23 12:55:44 -07005287 sp<DisplayDevice> display;
5288 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005289 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005290
Chia-I Wu20261cb2018-08-23 12:55:44 -07005291 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005292 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005293
Chia-I Wucb023152018-08-28 12:57:23 -07005294 // set the requested width/height to the logical display viewport size
5295 // by default
5296 if (reqWidth == 0 || reqHeight == 0) {
5297 reqWidth = uint32_t(display->getViewport().width());
5298 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005299 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005300 }
5301
Peiyong Lin0e003c92018-09-17 11:09:51 -07005302 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005303 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005304 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5305 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005306 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005307 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005308}
5309
chaviw93df2ea2019-04-30 16:45:12 -07005310static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5311 switch (colorMode) {
5312 case ColorMode::DISPLAY_P3:
5313 case ColorMode::BT2100_PQ:
5314 case ColorMode::BT2100_HLG:
5315 case ColorMode::DISPLAY_BT2020:
5316 return Dataspace::DISPLAY_P3;
5317 default:
5318 return Dataspace::V0_SRGB;
5319 }
5320}
5321
Martin Liu4a322352020-03-24 21:30:38 +08005322status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5323 static constexpr int kFifoPriority = 2;
5324 static constexpr int kOtherPriority = 0;
5325
5326 struct sched_param param = {0};
5327 int sched_policy;
5328 if (enabled) {
5329 sched_policy = SCHED_FIFO;
5330 param.sched_priority = kFifoPriority;
5331 } else {
5332 sched_policy = SCHED_OTHER;
5333 param.sched_priority = kOtherPriority;
5334 }
5335
5336 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5337 return -errno;
5338 }
5339 return NO_ERROR;
5340}
5341
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005342sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005343 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5344 if (displayToken) {
5345 return getDisplayDeviceLocked(displayToken);
5346 }
5347 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5348 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005349 return getDisplayByLayerStack(displayOrLayerStack);
5350}
5351
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005352sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005353 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005354 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005355 return display;
5356 }
5357 }
5358 return nullptr;
5359}
5360
5361status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5362 sp<GraphicBuffer>* outBuffer) {
5363 sp<DisplayDevice> display;
5364 uint32_t width;
5365 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005366 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005367 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005368 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005369 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5370 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005371 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005372 }
5373
5374 width = uint32_t(display->getViewport().width());
5375 height = uint32_t(display->getViewport().height());
5376
Dominik Laskowski718f9602019-11-09 20:01:35 -08005377 const auto orientation = display->getOrientation();
5378 captureOrientation = ui::Transform::toRotationFlags(orientation);
5379
5380 switch (captureOrientation) {
5381 case ui::Transform::ROT_90:
5382 captureOrientation = ui::Transform::ROT_270;
5383 break;
5384
5385 case ui::Transform::ROT_270:
5386 captureOrientation = ui::Transform::ROT_90;
5387 break;
5388
5389 case ui::Transform::ROT_INVALID:
5390 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5391 captureOrientation = ui::Transform::ROT_0;
5392 break;
5393
5394 default:
5395 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005396 }
chaviw93df2ea2019-04-30 16:45:12 -07005397 *outDataspace =
5398 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5399 }
5400
5401 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5402 false /* captureSecureLayers */);
5403
5404 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5405 std::placeholders::_1);
5406 bool ignored = false;
5407 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5408 false /* useIdentityTransform */,
5409 ignored /* outCapturedSecureLayers */);
5410}
5411
Robert Carr866455f2019-04-02 16:28:26 -07005412status_t SurfaceFlinger::captureLayers(
5413 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5414 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5415 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5416 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005417 ATRACE_CALL();
5418
5419 class LayerRenderArea : public RenderArea {
5420 public:
Robert Carr578038f2018-03-09 12:25:24 -08005421 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005422 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005423 bool childrenOnly, const Rect& displayViewport)
5424 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005425 mLayer(layer),
5426 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005427 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005428 mFlinger(flinger),
5429 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005430 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005431 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005432 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005433 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005434 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005435 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005436 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005437 }
chaviwa76b2712017-09-20 12:02:26 -07005438 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005439 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005440 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005441 Rect getSourceCrop() const override {
5442 if (mCrop.isEmpty()) {
5443 return getBounds();
5444 } else {
5445 return mCrop;
5446 }
5447 }
Robert Carr578038f2018-03-09 12:25:24 -08005448 class ReparentForDrawing {
5449 public:
5450 const sp<Layer>& oldParent;
5451 const sp<Layer>& newParent;
5452
Vishnu Nair4351ad52019-02-11 14:13:02 -08005453 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5454 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005455 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005456 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005457 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5458 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005459 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005460 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005461 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005462 };
5463
5464 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005465 const Rect sourceCrop = getSourceCrop();
5466 // no need to check rotation because there is none
5467 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5468 sourceCrop.height() != getReqHeight();
5469
Robert Carr578038f2018-03-09 12:25:24 -08005470 if (!mChildrenOnly) {
5471 mTransform = mLayer->getTransform().inverse();
5472 drawLayers();
5473 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005474 uint32_t w = static_cast<uint32_t>(getWidth());
5475 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005476 // In the "childrenOnly" case we reparent the children to a screenshot
5477 // layer which has no properties set and which does not draw.
5478 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005479 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5480 "Screenshot Parent"s, w, h, 0,
5481 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005482
Vishnu Nair4351ad52019-02-11 14:13:02 -08005483 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005484 drawLayers();
5485 }
5486 }
chaviwa76b2712017-09-20 12:02:26 -07005487
chaviwa76b2712017-09-20 12:02:26 -07005488 private:
chaviw7206d492017-11-10 16:16:12 -08005489 const sp<Layer> mLayer;
5490 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005491
Peiyong Linefefaac2018-08-17 12:27:51 -07005492 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005493 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005494
5495 SurfaceFlinger* mFlinger;
5496 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005497 };
5498
Robert Carrc0df3122019-04-11 13:18:21 -07005499 int reqWidth = 0;
5500 int reqHeight = 0;
5501 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005502 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005503 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005504 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005505 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005506 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005507
Alec Mouri9a02eda2020-04-21 17:39:34 -07005508 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005509 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5510 ALOGE("captureLayers called with an invalid or removed parent");
5511 return NAME_NOT_FOUND;
5512 }
5513
5514 const int uid = IPCThreadState::self()->getCallingUid();
5515 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5516 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5517 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5518 return PERMISSION_DENIED;
5519 }
5520
Vishnu Nairefc42e22019-12-03 17:36:12 -08005521 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005522 if (sourceCrop.width() <= 0) {
5523 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005524 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005525 }
5526
5527 if (sourceCrop.height() <= 0) {
5528 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005529 crop.bottom = parentSourceBounds.getHeight();
5530 }
5531
5532 if (crop.isEmpty() || frameScale <= 0.0f) {
5533 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5534 // crop was not specified, or an invalid frame scale was provided.
5535 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005536 }
5537 reqWidth = crop.width() * frameScale;
5538 reqHeight = crop.height() * frameScale;
5539
5540 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005541 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005542 if (excludeLayer != nullptr) {
5543 excludeLayers.emplace(excludeLayer);
5544 } else {
5545 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5546 return NAME_NOT_FOUND;
5547 }
5548 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005549
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005550 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005551 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005552 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005553 }
5554
5555 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005556 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005557
Chia-I Wu20261cb2018-08-23 12:55:44 -07005558 // really small crop or frameScale
5559 if (reqWidth <= 0) {
5560 reqWidth = 1;
5561 }
5562 if (reqHeight <= 0) {
5563 reqHeight = 1;
5564 }
5565
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005566 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5567 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005568 auto traverseLayers = [parent, childrenOnly,
5569 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005570 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5571 if (!layer->isVisible()) {
5572 return;
Robert Carr578038f2018-03-09 12:25:24 -08005573 } else if (childrenOnly && layer == parent.get()) {
5574 return;
chaviwa76b2712017-09-20 12:02:26 -07005575 }
Robert Carr866455f2019-04-02 16:28:26 -07005576
5577 sp<Layer> p = layer;
5578 while (p != nullptr) {
5579 if (excludeLayers.count(p) != 0) {
5580 return;
5581 }
5582 p = p->getParent();
5583 }
5584
chaviwa76b2712017-09-20 12:02:26 -07005585 visitor(layer);
5586 });
5587 };
Robert Carr108b2c72019-04-02 16:32:58 -07005588
5589 bool outCapturedSecureLayers = false;
5590 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5591 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005592}
5593
5594status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5595 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005596 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005597 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005598 bool useIdentityTransform,
5599 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005600 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005601
Peiyong Lin0e003c92018-09-17 11:09:51 -07005602 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005603 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
Richard Liu11a11052020-04-08 10:51:55 +00005604 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_COMPOSER;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005605 *outBuffer =
5606 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5607 static_cast<android_pixel_format>(reqPixelFormat), 1,
5608 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005609
Robert Carr108b2c72019-04-02 16:32:58 -07005610 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005611 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005612}
5613
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005614status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5615 TraverseLayersFunction traverseLayers,
5616 const sp<GraphicBuffer>& buffer,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005617 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005618 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005619 const int uid = IPCThreadState::self()->getCallingUid();
5620 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5621
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005622 status_t result;
5623 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005624
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005625 do {
5626 std::tie(result, syncFd) =
5627 schedule([&] {
5628 if (mRefreshPending) {
5629 ATRACE_NAME("Skipping screenshot for now");
5630 return std::make_pair(EAGAIN, -1);
5631 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005632
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005633 status_t result = NO_ERROR;
5634 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005635
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005636 Mutex::Autolock lock(mStateLock);
5637 renderArea.render([&] {
5638 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5639 useIdentityTransform, forSystem, &fd,
5640 regionSampling, outCapturedSecureLayers);
5641 });
5642
5643 return std::make_pair(result, fd);
5644 }).get();
5645 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005646
5647 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005648 sync_wait(syncFd, -1);
5649 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005650 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005651
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005652 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005653}
5654
chaviwa76b2712017-09-20 12:02:26 -07005655void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005656 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005657 ANativeWindowBuffer* buffer, bool useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005658 bool regionSampling, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005659 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005660
chaviwa76b2712017-09-20 12:02:26 -07005661 const auto reqWidth = renderArea.getReqWidth();
5662 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005663 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005664 const auto transform = renderArea.getTransform();
5665 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005666 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005667
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005668 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005669 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005670
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005671 // assume that bounds are never offset, and that they are the same as the
5672 // buffer bounds.
5673 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005674 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005675 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005676
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005677 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5678 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005679
chaviw50da5042018-04-09 13:49:37 -07005680 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005681
Vishnu Nair9b079a22020-01-21 14:36:08 -08005682 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005683 fillLayer.source.buffer.buffer = nullptr;
5684 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005685 fillLayer.geometry.boundaries =
5686 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005687 fillLayer.alpha = half(alpha);
5688 clientCompositionLayers.push_back(fillLayer);
5689
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005690 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08005691 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005692 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005693 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005694 const bool supportProtectedContent = false;
5695 Region clip(renderArea.getBounds());
5696 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5697 clip,
5698 useIdentityTransform,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005699 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07005700 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005701 renderArea.isSecure(),
5702 supportProtectedContent,
5703 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005704 displayViewport,
5705 clientCompositionDisplay.outputDataspace,
5706 true, /* realContentIsVisible */
5707 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005708 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005709 std::vector<compositionengine::LayerFE::LayerSettings> results =
5710 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005711 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005712 for (auto& settings : results) {
5713 settings.geometry.positionTransform =
5714 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupinf11eba52020-04-20 18:42:31 -07005715 // There's no need to process blurs when we're executing region sampling,
5716 // we're just trying to understand what we're drawing, and doing so without
5717 // blurs is already a pretty good approximation.
5718 if (regionSampling) {
5719 settings.backgroundBlurRadius = 0;
5720 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005721 }
Yichi Chen40773d92020-04-01 10:10:18 +08005722 clientCompositionLayers.insert(clientCompositionLayers.end(),
5723 std::make_move_iterator(results.begin()),
5724 std::make_move_iterator(results.end()));
5725 renderedLayers.push_back(layer);
5726 }
chaviwa76b2712017-09-20 12:02:26 -07005727 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005728
Yichi Chen40773d92020-04-01 10:10:18 +08005729 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5730 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005731 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005732 clientCompositionLayerPointers.begin(),
5733 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005734
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005735 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005736 // Use an empty fence for the buffer fence, since we just created the buffer so
5737 // there is no need for synchronization with the GPU.
5738 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005739 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005740 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005741 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005742 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005743
5744 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005745
5746 if (*outSyncFd >= 0) {
5747 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5748 for (auto* layer : renderedLayers) {
5749 layer->onLayerDisplayed(releaseFence);
5750 }
5751 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005752}
5753
chaviwa76b2712017-09-20 12:02:26 -07005754status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5755 TraverseLayersFunction traverseLayers,
5756 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005757 bool useIdentityTransform, bool forSystem,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005758 int* outSyncFd, bool regionSampling,
5759 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005760 ATRACE_CALL();
5761
chaviwa76b2712017-09-20 12:02:26 -07005762 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005763 outCapturedSecureLayers =
5764 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005765 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005766
Robert Carr03480e22018-01-04 16:02:06 -08005767 // We allow the system server to take screenshots of secure layers for
5768 // use in situations like the Screen-rotation animation and place
5769 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005770 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005771 ALOGW("FB is protected: PERMISSION_DENIED");
5772 return PERMISSION_DENIED;
5773 }
Lucas Dupinf11eba52020-04-20 18:42:31 -07005774 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5775 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005776 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005777}
5778
chaviw95ef3c42019-02-14 10:55:09 -08005779void SurfaceFlinger::setInputWindowsFinished() {
5780 Mutex::Autolock _l(mStateLock);
5781
5782 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005783
chaviw95ef3c42019-02-14 10:55:09 -08005784 mTransactionCV.broadcast();
5785}
chaviw5f21a5e2019-02-14 10:00:34 -08005786
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005787// ---------------------------------------------------------------------------
5788
Edgar Arriaga844fa672020-01-16 14:21:42 -08005789void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5790 layersSortedByZ.traverse(visitor);
5791}
5792
Dan Stoza412903f2017-04-27 13:42:17 -07005793void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5794 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005795}
5796
Dan Stoza412903f2017-04-27 13:42:17 -07005797void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5798 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005799}
5800
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005801void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005802 const LayerVector::Visitor& visitor) {
5803 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005804 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005805 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005806 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005807 continue;
5808 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005809 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005810 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005811 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005812 return;
5813 }
chaviwa76b2712017-09-20 12:02:26 -07005814 if (!layer->isVisible()) {
5815 return;
5816 }
5817 visitor(layer);
5818 });
5819 }
5820}
5821
Steven Thomasd4071902020-03-24 16:02:53 -07005822status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5823 const sp<DisplayDevice>& display,
5824 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005825 Mutex::Autolock lock(mStateLock);
5826
Steven Thomasd4071902020-03-24 16:02:53 -07005827 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5828 "Can only set override policy on the primary display");
5829 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5830
Dominik Laskowski22488f62019-03-28 09:53:04 -07005831 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005832 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5833 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5834 // it should go thru setDesiredActiveConfig, similar to primary display.
5835 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5836 const auto displayId = display->getId();
5837 LOG_ALWAYS_FATAL_IF(!displayId);
5838
Peiyong Line9d809e2020-04-14 13:10:48 -07005839 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005840 constraints.desiredTimeNanos = systemTime();
5841 constraints.seamlessRequired = false;
5842
Peiyong Line9d809e2020-04-14 13:10:48 -07005843 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005844 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5845 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005846 constraints, &timeline) < 0) {
5847 return BAD_VALUE;
5848 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005849 if (timeline.refreshRequired) {
5850 repaintEverythingForHWC();
5851 }
5852
Steven Thomasd4071902020-03-24 16:02:53 -07005853 display->setActiveConfig(policy->defaultConfig);
5854 const nsecs_t vsyncPeriod = getHwComposer()
5855 .getConfigs(*displayId)[policy->defaultConfig.value()]
5856 ->getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07005857 mScheduler->onNonPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
5858 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005859 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005860 }
5861
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005862 if (mDebugDisplayConfigSetByBackdoor) {
5863 // ignore this request as config is overridden by backdoor
5864 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005865 }
5866
Steven Thomasd4071902020-03-24 16:02:53 -07005867 status_t setPolicyResult = overridePolicy
5868 ? mRefreshRateConfigs->setOverridePolicy(policy)
5869 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5870 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005871 return BAD_VALUE;
5872 }
Steven Thomasd4071902020-03-24 16:02:53 -07005873 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005874 return NO_ERROR;
5875 }
Steven Thomasd4071902020-03-24 16:02:53 -07005876 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005877
Steven Thomasf734df42020-04-13 21:09:28 -07005878 ALOGV("Setting desired display config specs: defaultConfig: %d primaryRange: [%.0f %.0f]"
5879 " expandedRange: [%.0f %.0f]",
5880 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
5881 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
5882 currentPolicy.appRequestRange.max);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005883
Ana Krulecb9afd792020-06-11 13:16:15 -07005884 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
5885 // be depending in this callback.
Alec Mouri60aee1c2019-10-28 16:18:59 -07005886 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005887 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5888 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07005889 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
5890 display->getActiveConfig(), vsyncPeriod);
Ana Krulecb9afd792020-06-11 13:16:15 -07005891 toggleKernelIdleTimer();
Ady Abraham838de062019-02-04 10:24:03 -08005892
Ana Krulec3f6a2062020-01-23 15:48:01 -08005893 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005894 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005895 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5896 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005897 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005898 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005899 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005900
Ady Abrahamabc27602020-04-08 17:20:29 -07005901 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5902 ALOGV("switching to Scheduler preferred config %d",
5903 preferredRefreshRate.getConfigId().value());
5904 setDesiredActiveConfig(
5905 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005906 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005907 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5908 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005909 }
5910
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005911 return NO_ERROR;
5912}
5913
Ana Krulec0782b882019-10-15 17:34:54 -07005914status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Steven Thomasf734df42020-04-13 21:09:28 -07005915 int32_t defaultConfig,
5916 float primaryRefreshRateMin,
5917 float primaryRefreshRateMax,
5918 float appRequestRefreshRateMin,
5919 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07005920 ATRACE_CALL();
5921
5922 if (!displayToken) {
5923 return BAD_VALUE;
5924 }
5925
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005926 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005927 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01005928 if (!display) {
5929 ALOGE("Attempt to set desired display configs for invalid display token %p",
5930 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005931 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01005932 } else if (display->isVirtual()) {
5933 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005934 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01005935 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005936 using Policy = scheduler::RefreshRateConfigs::Policy;
Steven Thomasf734df42020-04-13 21:09:28 -07005937 const Policy policy{HwcConfigIndexType(defaultConfig),
5938 {primaryRefreshRateMin, primaryRefreshRateMax},
5939 {appRequestRefreshRateMin, appRequestRefreshRateMax}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005940 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005941
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005942 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
5943 }
5944 });
5945
5946 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01005947}
5948
5949status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005950 int32_t* outDefaultConfig,
Steven Thomasf734df42020-04-13 21:09:28 -07005951 float* outPrimaryRefreshRateMin,
5952 float* outPrimaryRefreshRateMax,
5953 float* outAppRequestRefreshRateMin,
5954 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01005955 ATRACE_CALL();
5956
Steven Thomasf734df42020-04-13 21:09:28 -07005957 if (!displayToken || !outDefaultConfig || !outPrimaryRefreshRateMin ||
5958 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01005959 return BAD_VALUE;
5960 }
5961
5962 Mutex::Autolock lock(mStateLock);
5963 const auto display = getDisplayDeviceLocked(displayToken);
5964 if (!display) {
5965 return NAME_NOT_FOUND;
5966 }
5967
5968 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07005969 scheduler::RefreshRateConfigs::Policy policy =
5970 mRefreshRateConfigs->getDisplayManagerPolicy();
5971 *outDefaultConfig = policy.defaultConfig.value();
Steven Thomasf734df42020-04-13 21:09:28 -07005972 *outPrimaryRefreshRateMin = policy.primaryRange.min;
5973 *outPrimaryRefreshRateMax = policy.primaryRange.max;
5974 *outAppRequestRefreshRateMin = policy.appRequestRange.min;
5975 *outAppRequestRefreshRateMax = policy.appRequestRange.max;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005976 return NO_ERROR;
5977 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005978 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005979 } else {
5980 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005981 LOG_FATAL_IF(!displayId);
5982
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005983 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5984 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
Steven Thomasf734df42020-04-13 21:09:28 -07005985 *outPrimaryRefreshRateMin = 1e9f / vsyncPeriod;
5986 *outPrimaryRefreshRateMax = 1e9f / vsyncPeriod;
5987 *outAppRequestRefreshRateMin = 1e9f / vsyncPeriod;
5988 *outAppRequestRefreshRateMax = 1e9f / vsyncPeriod;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005989 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005990 }
Ana Krulec0782b882019-10-15 17:34:54 -07005991}
5992
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005993void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005994 mFlinger->setInputWindowsFinished();
5995}
5996
Alec Mouri9a02eda2020-04-21 17:39:34 -07005997wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5998 Mutex::Autolock _l(mStateLock);
5999 return fromHandleLocked(handle);
6000}
6001
6002wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006003 BBinder* b = nullptr;
6004 if (handle) {
6005 b = handle->localBinder();
6006 }
Robert Carrc0df3122019-04-11 13:18:21 -07006007 if (b == nullptr) {
6008 return nullptr;
6009 }
6010 auto it = mLayersByLocalBinderToken.find(b);
6011 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006012 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006013 }
6014 return nullptr;
6015}
6016
Dominik Laskowski75848362019-11-11 17:57:20 -08006017void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006018 mNumLayers++;
6019 mScheduler->registerLayer(layer);
6020}
6021
6022void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6023 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006024 removeFromOffscreenLayers(layer);
6025}
6026
6027// WARNING: ONLY CALL THIS FROM LAYER DTOR
6028// Here we add children in the current state to offscreen layers and remove the
6029// layer itself from the offscreen layer list. Since
6030// this is the dtor, it is safe to access the current state. This keeps us
6031// from dangling children layers such that they are not reachable from the
6032// Drawing state nor the offscreen layer list
6033// See b/141111965
6034void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6035 for (auto& child : layer->getCurrentChildren()) {
6036 mOffscreenLayers.emplace(child.get());
6037 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006038 mOffscreenLayers.erase(layer);
6039}
6040
Alec Mouri4545a8a2019-08-08 20:05:32 -07006041void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6042 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6043}
6044
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006045status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6046 float lightPosY, float lightPosZ,
6047 float lightRadius) {
6048 Mutex::Autolock _l(mStateLock);
6049 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6050 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6051 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6052 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6053 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6054
6055 // these values are overridden when calculating the shadow settings for a layer.
6056 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6057 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006058 return NO_ERROR;
6059}
6060
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006061const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6062 const {
6063 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6064 // on the work to remove the table in that bug rather than adding more to
6065 // it.
6066 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006067 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6068 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6069 };
6070 return genericLayerMetadataKeyMap;
6071}
6072
Steven Thomas62a4cf82020-01-31 12:04:03 -08006073status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6074 int8_t compatibility) {
6075 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6076 return BAD_VALUE;
6077 }
6078
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006079 static_cast<void>(schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006080 Mutex::Autolock lock(mStateLock);
6081 if (authenticateSurfaceTextureLocked(surface)) {
6082 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
Ady Abraham4ac93922020-10-08 18:40:47 +00006083 if (layer == nullptr) {
6084 ALOGE("Attempt to set frame rate on a layer that no longer exists");
6085 return BAD_VALUE;
6086 }
6087
Ady Abraham60e42ea2020-03-09 19:17:31 -07006088 if (layer->setFrameRate(
6089 Layer::FrameRate(frameRate,
6090 Layer::FrameRate::convertCompatibility(compatibility)))) {
6091 setTransactionFlags(eTraversalNeeded);
6092 }
6093 } else {
6094 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6095 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006096 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006097 return NO_ERROR;
6098 }));
6099
Steven Thomas62a4cf82020-01-31 12:04:03 -08006100 return NO_ERROR;
6101}
6102
Steven Thomasd4071902020-03-24 16:02:53 -07006103status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6104 if (!outToken) {
6105 return BAD_VALUE;
6106 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006107
6108 auto future = schedule([this] {
6109 status_t result = NO_ERROR;
6110 sp<IBinder> token;
6111
Steven Thomasd4071902020-03-24 16:02:53 -07006112 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006113 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Steven Thomasd4071902020-03-24 16:02:53 -07006114
6115 // This is a little racy, but not in a way that hurts anything. As we grab the
6116 // defaultConfig from the display manager policy, we could be setting a new display
6117 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6118 // matter for the override policy though, since we set allowGroupSwitching to true, so
6119 // it's not a problem.
6120 scheduler::RefreshRateConfigs::Policy overridePolicy;
6121 overridePolicy.defaultConfig =
6122 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6123 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006124 constexpr bool kOverridePolicy = true;
6125 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006126 }
6127
6128 if (result == NO_ERROR) {
6129 mFrameRateFlexibilityTokenCount++;
6130 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6131 // below, is something to consider carefully. The lifetime of the
6132 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6133 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6134 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6135 // in this case, for two reasons:
6136 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6137 // the program exits is via a crash. So we won't have a situation where the
6138 // SurfaceFlinger object is dead but the process is still up.
6139 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6140 // if condition 1 were changed, the problem would only show up when running CTS tests,
6141 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006142 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006143 [this]() { onFrameRateFlexibilityTokenReleased(); });
6144 ALOGD("Frame rate flexibility token acquired. count=%d",
6145 mFrameRateFlexibilityTokenCount);
6146 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006147
6148 return std::make_pair(result, token);
6149 });
6150
6151 status_t result;
6152 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006153 return result;
6154}
6155
6156void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006157 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006158 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6159 "Failed tracking frame rate flexibility tokens");
6160 mFrameRateFlexibilityTokenCount--;
6161 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6162 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006163 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006164 constexpr bool kOverridePolicy = true;
6165 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006166 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6167 }
6168 }));
6169}
6170
Dominik Laskowski20134642020-04-20 22:36:44 -07006171void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
6172 static_cast<void>(schedule([=] {
6173 std::unique_ptr<RefreshRateOverlay> overlay;
6174 if (enable) {
6175 overlay = std::make_unique<RefreshRateOverlay>(*this);
6176 }
6177
6178 {
6179 Mutex::Autolock lock(mStateLock);
6180
6181 // Destroy the layer of the current overlay, if any, outside the lock.
6182 mRefreshRateOverlay.swap(overlay);
6183 if (!mRefreshRateOverlay) return;
6184
6185 if (const auto display = getDefaultDisplayDeviceLocked()) {
6186 mRefreshRateOverlay->setViewport(display->getSize());
6187 }
6188
6189 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
6190 }
6191 }));
6192}
6193
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006194} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006195
Mathias Agopian3f844832013-08-07 21:24:32 -07006196#if defined(__gl_h_)
6197#error "don't include gl/gl.h in this file"
6198#endif
6199
6200#if defined(__gl2_h_)
6201#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006202#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006203
6204// TODO(b/129481165): remove the #pragma below and fix conversion issues
6205#pragma clang diagnostic pop // ignored "-Wconversion"