blob: 46da5cc778591b1e85fa2f5ed9f8f038f4c71947 [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 Mouri5f487d42020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri5f487d42020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
Lais Andrade3a6e47d2020-04-02 11:20:16 +010030#include <android/hardware/power/Boost.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri5f487d42020-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>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri5f487d42020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Lais Andrade3a6e47d2020-04-02 11:20:16 +0100135using android::hardware::power::Boost;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Peiyong Line9d809e2020-04-14 13:10:48 -0700143namespace hal = android::hardware::graphics::composer::hal;
144
Steven Thomasb02664d2017-07-26 18:48:28 -0700145namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700146
147#pragma clang diagnostic push
148#pragma clang diagnostic error "-Wswitch-enum"
149
150bool isWideColorMode(const ColorMode colorMode) {
151 switch (colorMode) {
152 case ColorMode::DISPLAY_P3:
153 case ColorMode::ADOBE_RGB:
154 case ColorMode::DCI_P3:
155 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700156 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700157 case ColorMode::BT2100_PQ:
158 case ColorMode::BT2100_HLG:
159 return true;
160 case ColorMode::NATIVE:
161 case ColorMode::STANDARD_BT601_625:
162 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
163 case ColorMode::STANDARD_BT601_525:
164 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
165 case ColorMode::STANDARD_BT709:
166 case ColorMode::SRGB:
167 return false;
168 }
169 return false;
170}
171
172#pragma clang diagnostic pop
173
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700174template <typename Mutex>
175struct ConditionalLockGuard {
176 ConditionalLockGuard(Mutex& mutex, bool lock) : mutex(mutex), lock(lock) {
177 if (lock) mutex.lock();
Steven Thomasb02664d2017-07-26 18:48:28 -0700178 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700179
180 ~ConditionalLockGuard() {
181 if (lock) mutex.unlock();
182 }
183
184 Mutex& mutex;
185 const bool lock;
Steven Thomasb02664d2017-07-26 18:48:28 -0700186};
Peiyong Linfca547f2018-07-09 13:03:33 -0700187
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700188using ConditionalLock = ConditionalLockGuard<Mutex>;
189
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800190// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
191constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
192
193float getDensityFromProperty(const char* property, bool required) {
194 char value[PROPERTY_VALUE_MAX];
195 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
196 if (!density && required) {
197 ALOGE("%s must be defined as a build property", property);
198 return FALLBACK_DENSITY;
199 }
200 return density / 160.f;
201}
202
Peiyong Lin9d846a52018-11-05 13:18:20 -0800203// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
204bool validateCompositionDataspace(Dataspace dataspace) {
205 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
206}
207
Steven Thomasd4071902020-03-24 16:02:53 -0700208class FrameRateFlexibilityToken : public BBinder {
209public:
210 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
211 virtual ~FrameRateFlexibilityToken() { mCallback(); }
212
213private:
214 std::function<void()> mCallback;
215};
216
Steven Thomasb02664d2017-07-26 18:48:28 -0700217} // namespace anonymous
218
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219// ---------------------------------------------------------------------------
220
Mathias Agopian99b49842011-06-27 16:05:52 -0700221const String16 sHardwareTest("android.permission.HARDWARE_TEST");
222const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
223const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
224const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800225const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700226
227// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700228int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700229bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800230uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800231bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800232bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800233int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100234uint32_t SurfaceFlinger::maxGraphicsWidth;
235uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600236bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800237ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700238bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700239bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700240Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
241ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
242Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
243ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800244bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700245
Kalle Raitaa099a242017-01-11 11:17:29 -0800246std::string getHwcServiceName() {
247 char value[PROPERTY_VALUE_MAX] = {};
248 property_get("debug.sf.hwc_service_name", value, "default");
249 ALOGI("Using HWComposer service: '%s'", value);
250 return std::string(value);
251}
252
253bool useTrebleTestingOverride() {
254 char value[PROPERTY_VALUE_MAX] = {};
255 property_get("debug.sf.treble_testing_override", value, "false");
256 ALOGI("Treble testing override: '%s'", value);
257 return std::string(value) == "true";
258}
259
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800260std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
261 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800262 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700263 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800264 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700265 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800266 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700267 return std::string("Enhanced");
268 default:
269 return std::string("Unknown ") +
270 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800271 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800272}
273
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700274SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800275
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700276SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
277 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700278 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700279 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700280 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700281 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700282 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800283 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
284 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800285
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700286SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800287 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800288
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800296
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800301
Brian Lindahla13f2d52020-03-05 11:54:17 +0100302 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
303 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
304
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700306
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 mDefaultCompositionDataspace =
310 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700311 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
312 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900313 defaultCompositionDataspace = mDefaultCompositionDataspace;
314 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
315 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
316 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
317 wideColorGamutCompositionPixelFormat =
318 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700319
Yichi Chenda901bf2019-06-28 14:58:27 +0800320 mColorSpaceAgnosticDataspace =
321 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800324
Dominik Laskowski718f9602019-11-09 20:01:35 -0800325 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
326 switch (primary_display_orientation(Values::ORIENTATION_0)) {
327 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800329 case Values::ORIENTATION_90:
330 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800332 case Values::ORIENTATION_180:
333 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800335 case Values::ORIENTATION_270:
336 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800339 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800340
Sundong Ahn85131bd2019-02-18 15:51:53 +0900341 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800342
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343 // debugging stuff...
344 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700345
Mathias Agopianb4b17302013-03-20 18:36:41 -0700346 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700347 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700348
Alec Mouri5f487d42020-02-06 09:26:19 -0800349 property_get("ro.build.type", value, "user");
350 mIsUserBuild = strcmp(value, "user") == 0;
351
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352 property_get("debug.sf.showupdates", value, "0");
353 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700355 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000356
357 // DDMS debugging deprecated (b/120782499)
358 property_get("debug.sf.ddms", value, "0");
359 int debugDdms = atoi(value);
360 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700361
362 property_get("debug.sf.disable_backpressure", value, "0");
363 mPropagateBackpressure = !atoi(value);
364 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700365
Ady Abrahamadb9a992019-09-19 21:21:55 +0000366 property_get("debug.sf.enable_gl_backpressure", value, "0");
367 mPropagateBackpressureClientComposition = atoi(value);
368 ALOGI_IF(mPropagateBackpressureClientComposition,
369 "Enabling backpressure propagation for Client Composition");
370
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800371 property_get("debug.sf.enable_hwc_vds", value, "0");
372 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800373 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800374
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800375 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800376 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800377 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700378
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800379 property_get("ro.surface_flinger.supports_background_blur", value, "0");
380 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700381 mSupportsBlur = supportsBlurs;
382 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800383 property_get("ro.sf.blurs_are_expensive", value, "0");
384 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800385
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800386 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700387 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
388 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800389 mGraphicBufferProducerListSizeLogThreshold =
390 std::max(static_cast<int>(0.95 *
391 static_cast<double>(mMaxGraphicBufferProducerListSize)),
392 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700393
Dan Stozaec460082018-12-17 15:35:09 -0800394 property_get("debug.sf.luma_sampling", value, "1");
395 mLumaSampling = atoi(value);
396
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800397 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800398 mDisableClientCompositionCache = atoi(value);
399
Romain Guy11d63f42017-07-20 12:47:14 -0700400 // We should be reading 'persist.sys.sf.color_saturation' here
401 // but since /data may be encrypted, we need to wait until after vold
402 // comes online to attempt to read the property. The property is
403 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800404
405 if (useTrebleTestingOverride()) {
406 // Without the override SurfaceFlinger cannot connect to HIDL
407 // services that are not listed in the manifests. Considered
408 // deriving the setting from the set service name, but it
409 // would be brittle if the name that's not 'default' is used
410 // for production purposes later on.
411 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
412 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800413
414 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415}
416
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417void SurfaceFlinger::onFirstRef()
418{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800419 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420}
421
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700422SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423
Dan Stozac7014012014-02-14 15:03:43 -0800424void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425{
426 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700427 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428
Andy McFadden13a082e2012-08-24 10:16:42 -0700429 // restore initial conditions (default device unblank, etc)
430 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800431
432 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700433 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800434}
435
Robert Carr1db73f62016-12-21 12:58:51 -0800436static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700437 status_t err = client->initCheck();
438 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800439 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800440 }
Robert Carr1db73f62016-12-21 12:58:51 -0800441 return nullptr;
442}
443
444sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
445 return initClient(new Client(this));
446}
447
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700448sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
449 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700450{
451 class DisplayToken : public BBinder {
452 sp<SurfaceFlinger> flinger;
453 virtual ~DisplayToken() {
454 // no more references, this display must be terminated
455 Mutex::Autolock _l(flinger->mStateLock);
456 flinger->mCurrentState.displays.removeItem(this);
457 flinger->setTransactionFlags(eDisplayTransactionNeeded);
458 }
459 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700460 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461 : flinger(flinger) {
462 }
463 };
464
465 sp<BBinder> token = new DisplayToken(this);
466
467 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700468 // Display ID is assigned when virtual display is allocated by HWC.
469 DisplayDeviceState state;
470 state.isSecure = secure;
471 state.displayName = displayName;
472 mCurrentState.displays.add(token, state);
473 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700474 return token;
475}
476
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700477void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700478 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700479
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700480 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700482 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700483 return;
484 }
485
Dominik Laskowski075d3172018-05-24 15:50:06 -0700486 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700487 if (state.physical) {
488 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 return;
490 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700491 mInterceptor->saveDisplayDeletion(state.sequenceId);
492 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 setTransactionFlags(eDisplayTransactionNeeded);
494}
495
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800496std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
497 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800499 const auto internalDisplayId = getInternalDisplayIdLocked();
500 if (!internalDisplayId) {
501 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502 }
503
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800504 std::vector<PhysicalDisplayId> displayIds;
505 displayIds.reserve(mPhysicalDisplayTokens.size());
506 displayIds.push_back(internalDisplayId->value);
507
508 for (const auto& [id, token] : mPhysicalDisplayTokens) {
509 if (id != *internalDisplayId) {
510 displayIds.push_back(id.value);
511 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700512 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700513
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800514 return displayIds;
515}
516
517sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
518 Mutex::Autolock lock(mStateLock);
519 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700520}
521
Ady Abraham37965d42018-11-01 13:43:32 -0700522status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
523 if (!outGetColorManagement) {
524 return BAD_VALUE;
525 }
526 *outGetColorManagement = useColorManagement;
527 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700528}
529
Lloyd Pique441d5042018-10-18 16:49:51 -0700530HWComposer& SurfaceFlinger::getHwComposer() const {
531 return mCompositionEngine->getHwComposer();
532}
533
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700534renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
535 return mCompositionEngine->getRenderEngine();
536}
537
Lloyd Pique70d91362018-10-18 16:02:55 -0700538compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
539 return *mCompositionEngine.get();
540}
541
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800542void SurfaceFlinger::bootFinished()
543{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700544 if (mBootFinished == true) {
545 ALOGE("Extra call to bootFinished");
546 return;
547 }
548 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700549 if (mStartPropertySetThread->join() != NO_ERROR) {
550 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800551 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800552 const nsecs_t now = systemTime();
553 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000554 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555
Mikael Pessa90092f42019-08-26 17:22:04 -0700556 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000557 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700558
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 // wait patiently for the window manager death
560 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700561 mWindowManager = defaultServiceManager()->getService(name);
562 if (mWindowManager != 0) {
563 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700564 }
Robert Carr720e5062018-07-30 17:45:14 -0700565 sp<IBinder> input(defaultServiceManager()->getService(
566 String16("inputflinger")));
567 if (input == nullptr) {
568 ALOGE("Failed to link to input service");
569 } else {
570 mInputFlinger = interface_cast<IInputFlinger>(input);
571 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700572
Steven Thomas050b2c82017-03-06 11:45:16 -0800573 if (mVrFlinger) {
574 mVrFlinger->OnBootFinished();
575 }
576
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700577 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700578 // formerly we would just kill the process, but we now ask it to exit so it
579 // can choose where to stop the animation.
580 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700581
582 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
583 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
584 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700585
Ana Krulecbd6654b2019-02-15 15:18:15 -0800586 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800587 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700588 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800589 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800590
Ady Abraham8a82ba62020-01-17 12:43:17 -0800591 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
592 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
593 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
594 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800595 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800596}
597
Dan Stoza436ccf32018-06-21 12:10:12 -0700598uint32_t SurfaceFlinger::getNewTexture() {
599 {
600 std::lock_guard lock(mTexturePoolMutex);
601 if (!mTexturePool.empty()) {
602 uint32_t name = mTexturePool.back();
603 mTexturePool.pop_back();
604 ATRACE_INT("TexturePoolSize", mTexturePool.size());
605 return name;
606 }
607
608 // The pool was too small, so increase it for the future
609 ++mTexturePoolSize;
610 }
611
612 // The pool was empty, so we need to get a new texture name directly using a
613 // blocking call to the main thread
614 uint32_t name = 0;
615 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
616 return name;
617}
618
Mathias Agopian3f844832013-08-07 21:24:32 -0700619void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700620 std::lock_guard lock(mTexturePoolMutex);
621 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
622 // to actually delete this or not based on mTexturePoolSize
623 mTexturePool.push_back(texture);
624 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700625}
626
Wei Wangf9b05ee2017-07-19 20:59:39 -0700627// Do not call property_set on main thread which will be blocked by init
628// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700629void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700630 ALOGI( "SurfaceFlinger's main thread ready to run. "
631 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700632 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800633
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700635 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800636 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700637 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
638 renderengine::RenderEngineCreationArgs::Builder()
639 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
640 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
641 .setUseColorManagerment(useColorManagement)
642 .setEnableProtectedContext(enable_protected_contents(false))
643 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700644 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700645 .setContextPriority(useContextPriority
646 ? renderengine::RenderEngine::ContextPriority::HIGH
647 : renderengine::RenderEngine::ContextPriority::MEDIUM)
648 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800649 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700650
651 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
652 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700653 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800654 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800655 // Process any initial hotplug and resulting display changes.
656 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700657 const auto display = getDefaultDisplayDeviceLocked();
658 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700659 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700660 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800661
Steven Thomas050b2c82017-03-06 11:45:16 -0800662 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700663 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700664 // This callback is called from the vr flinger dispatch thread. We
665 // need to call signalTransaction(), which requires holding
666 // mStateLock when we're not on the main thread. Acquiring
667 // mStateLock from the vr flinger dispatch thread might trigger a
668 // deadlock in surface flinger (see b/66916578), so post a message
669 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700670 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700671 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
672 mVrFlingerRequestsDisplay = requestDisplay;
673 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700674 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700676 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
677 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700678 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700679 .value_or(0),
680 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800681 if (!mVrFlinger) {
682 ALOGE("Failed to start vrflinger");
683 }
684 }
685
Mathias Agopian92a979a2012-08-02 18:32:23 -0700686 // initialize our drawing state
687 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700688
Andy McFadden13a082e2012-08-24 10:16:42 -0700689 // set initial conditions (e.g. unblank default device)
690 initializeDisplays();
691
Steven Thomas137d4bc2019-07-25 16:55:14 -0700692 char primeShaderCache[PROPERTY_VALUE_MAX];
693 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
694 if (atoi(primeShaderCache)) {
695 getRenderEngine().primeCache();
696 }
Dan Stoza4e637772016-07-28 13:31:51 -0700697
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700699
700 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700701 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700702 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700703
704 if (mStartPropertySetThread->Start() != NO_ERROR) {
705 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800706 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800707
Dan Stoza9e56aa02015-11-02 13:00:03 -0800708 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700709}
710
Romain Guy11d63f42017-07-20 12:47:14 -0700711void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700712 Mutex::Autolock _l(mStateLock);
713
Romain Guy11d63f42017-07-20 12:47:14 -0700714 char value[PROPERTY_VALUE_MAX];
715
716 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800717 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700718 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800719 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100720
721 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700722 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800723
724 property_get("persist.sys.sf.color_mode", value, "0");
725 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700726
727 property_get("persist.sys.sf.disable_blurs", value, "0");
728 bool disableBlurs = atoi(value);
729 mDisableBlurs = disableBlurs;
730 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700731}
732
Mathias Agopiana67e4182012-06-19 17:26:12 -0700733void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800734 // Start boot animation service by setting a property mailbox
735 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700736 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800737 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738 if (mStartPropertySetThread->join() != NO_ERROR) {
739 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800740 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700741}
742
Mathias Agopian875d8e12013-06-07 15:35:48 -0700743size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700744 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700745}
746
Mathias Agopian875d8e12013-06-07 15:35:48 -0700747size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700748 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700749}
750
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800751// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800752
Jamie Gennis582270d2011-08-17 18:19:00 -0700753bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800754 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800755 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800756 return authenticateSurfaceTextureLocked(bufferProducer);
757}
758
759bool SurfaceFlinger::authenticateSurfaceTextureLocked(
760 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800761 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800762 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800763}
764
Brian Anderson6b376712017-04-04 10:51:39 -0700765status_t SurfaceFlinger::getSupportedFrameTimestamps(
766 std::vector<FrameEvent>* outSupported) const {
767 *outSupported = {
768 FrameEvent::REQUESTED_PRESENT,
769 FrameEvent::ACQUIRE,
770 FrameEvent::LATCH,
771 FrameEvent::FIRST_REFRESH_START,
772 FrameEvent::LAST_REFRESH_START,
773 FrameEvent::GPU_COMPOSITION_DONE,
774 FrameEvent::DEQUEUE_READY,
775 FrameEvent::RELEASE,
776 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700777 ConditionalLock _l(mStateLock,
778 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700779 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700780 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
781 }
782 return NO_ERROR;
783}
784
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800785status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
786 if (!displayToken || !state) {
787 return BAD_VALUE;
788 }
789
790 Mutex::Autolock lock(mStateLock);
791
792 const auto display = getDisplayDeviceLocked(displayToken);
793 if (!display) {
794 return NAME_NOT_FOUND;
795 }
796
797 state->layerStack = display->getLayerStack();
798 state->orientation = display->getOrientation();
799
800 const Rect viewport = display->getViewport();
801 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
802
803 return NO_ERROR;
804}
805
806status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
807 if (!displayToken || !info) {
808 return BAD_VALUE;
809 }
810
811 Mutex::Autolock lock(mStateLock);
812
813 const auto display = getDisplayDeviceLocked(displayToken);
814 if (!display) {
815 return NAME_NOT_FOUND;
816 }
817
Dominik Laskowski55c85402020-01-21 16:25:47 -0800818 if (const auto connectionType = display->getConnectionType())
819 info->connectionType = *connectionType;
820 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800821 return INVALID_OPERATION;
822 }
823
824 if (mEmulatedDisplayDensity) {
825 info->density = mEmulatedDisplayDensity;
826 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800827 info->density = info->connectionType == DisplayConnectionType::Internal
828 ? mInternalDisplayDensity
829 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800830 }
831
832 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200833 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800834
835 return NO_ERROR;
836}
837
Dominik Laskowski22488f62019-03-28 09:53:04 -0700838status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800839 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700840 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 return BAD_VALUE;
842 }
843
Dominik Laskowski22488f62019-03-28 09:53:04 -0700844 Mutex::Autolock lock(mStateLock);
845
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800846 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700847 if (!displayId) {
848 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700849 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800851 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700852
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700854
Dominik Laskowski075d3172018-05-24 15:50:06 -0700855 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800856 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700857
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800858 auto width = hwConfig->getWidth();
859 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700860
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800861 auto xDpi = hwConfig->getDpiX();
862 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700863
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800864 if (isInternal &&
865 (internalDisplayOrientation == ui::ROTATION_90 ||
866 internalDisplayOrientation == ui::ROTATION_270)) {
867 std::swap(width, height);
868 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 }
870
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800871 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800872
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800873 if (mEmulatedDisplayDensity) {
874 config.xDpi = mEmulatedDisplayDensity;
875 config.yDpi = mEmulatedDisplayDensity;
876 } else {
877 config.xDpi = xDpi;
878 config.yDpi = yDpi;
879 }
880
881 const nsecs_t period = hwConfig->getVsyncPeriod();
882 config.refreshRate = 1e9f / period;
883
884 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
885 config.appVsyncOffset = offsets.late.app;
886 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800887 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888
Andy McFadden91b2ca82014-06-13 14:04:23 -0700889 // This is how far in advance a buffer must be queued for
890 // presentation at a given time. If you want a buffer to appear
891 // on the screen at time N, you must submit the buffer before
892 // (N - presentationDeadline).
893 //
894 // Normally it's one full refresh period (to give SF a chance to
895 // latch the buffer), but this can be reduced by configuring a
896 // DispSync offset. Any additional delays introduced by the hardware
897 // composer or panel must be accounted for here.
898 //
899 // We add an additional 1ms to allow for processing time and
900 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800901 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700902
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800903 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700904 }
905
Dan Stoza7f7da322014-05-02 15:26:25 -0700906 return NO_ERROR;
907}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700908
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700909status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
910 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700911 return BAD_VALUE;
912 }
913
Ana Krulecc2870422019-01-29 19:00:58 -0800914 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700915 return NO_ERROR;
916}
917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700919 int activeConfig;
920 bool isPrimary;
921
922 {
923 Mutex::Autolock lock(mStateLock);
924
925 if (const auto display = getDisplayDeviceLocked(displayToken)) {
926 activeConfig = display->getActiveConfig().value();
927 isPrimary = display->isPrimary();
928 } else {
929 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
930 return NAME_NOT_FOUND;
931 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800932 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700933
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700934 if (isPrimary) {
Steven Thomasc9098452019-09-30 17:15:05 -0700935 std::lock_guard<std::mutex> lock(mActiveConfigLock);
936 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800937 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700938 }
Steven Thomasc9098452019-09-30 17:15:05 -0700939 }
Ady Abraham2139f732019-11-13 18:56:40 -0800940
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700941 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700942}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700943
Ady Abraham03b02dd2019-03-21 15:40:11 -0700944void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800945 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800946 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700947 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800948
Ady Abrahamb838aed2019-02-12 15:30:16 -0800949 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800950 if (mDesiredActiveConfigChanged) {
951 // If a config change is pending, just cache the latest request in
952 // mDesiredActiveConfig
953 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
954 mDesiredActiveConfig = info;
955 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
956 } else {
957 // Check is we are already at the desired config
958 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700959 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800960 return;
961 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800962
Ady Abraham59db0a32020-03-02 18:04:20 -0800963 // Initiate a config change.
964 mDesiredActiveConfigChanged = true;
965 mDesiredActiveConfig = info;
966
Ady Abrahamb838aed2019-02-12 15:30:16 -0800967 // This will trigger HWC refresh without resetting the idle timer.
968 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700969 // Start receiving vsync samples now, so that we can detect a period
970 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700971 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700972 // As we called to set period, we will call to onRefreshRateChangeCompleted once
973 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700974 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800975
Ady Abrahamabc27602020-04-08 17:20:29 -0700976 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800977 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700979
980 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800981 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700982 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983}
984
985status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
986 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800987
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100988 if (!displayToken) {
989 return BAD_VALUE;
990 }
Ady Abraham838de062019-02-04 10:24:03 -0800991
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700992 status_t result = NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100993
994 postMessageSync(new LambdaMessage([&]() {
995 const auto display = getDisplayDeviceLocked(displayToken);
996 if (!display) {
997 ALOGE("Attempt to set allowed display configs for invalid display token %p",
998 displayToken.get());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100999 } else if (display->isVirtual()) {
1000 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001001 result = INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001002 } else {
1003 HwcConfigIndexType config(mode);
1004 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
Steven Thomasd4071902020-03-24 16:02:53 -07001005 result = setDesiredDisplayConfigSpecsInternal(display,
1006 scheduler::RefreshRateConfigs::
Ady Abrahamabc27602020-04-08 17:20:29 -07001007 Policy{config,
1008 refreshRate.getFps(),
1009 refreshRate.getFps()},
Steven Thomasd4071902020-03-24 16:02:53 -07001010 /*overridePolicy=*/false);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001011 }
1012 }));
1013
1014 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001015}
1016
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001017void SurfaceFlinger::setActiveConfigInternal() {
1018 ATRACE_CALL();
1019
Dominik Laskowski22488f62019-03-28 09:53:04 -07001020 const auto display = getDefaultDisplayDeviceLocked();
1021 if (!display) {
1022 return;
1023 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001024
Alec Mouri8de697e2020-03-19 10:52:01 -07001025 auto& oldRefreshRate =
1026 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1027
Dominik Laskowski22488f62019-03-28 09:53:04 -07001028 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001029 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001030 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001031 display->setActiveConfig(mUpcomingActiveConfig.configId);
1032
Ady Abraham2e1dd892020-03-05 13:48:36 -08001033 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001034 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001035 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001036 mTimeStats->incrementRefreshRateSwitches();
1037 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001038 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001039 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001040 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001041
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001042 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001043 const nsecs_t vsyncPeriod =
1044 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001045 .getVsyncPeriod();
Ady Abraham447052e2019-02-13 16:07:27 -08001046 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001047 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001048 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001049}
1050
Ady Abraham53852a52019-05-28 18:07:44 -07001051void SurfaceFlinger::desiredActiveConfigChangeDone() {
1052 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1053 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1054 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001055
Ady Abraham2e1dd892020-03-05 13:48:36 -08001056 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001057 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001058 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1059 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001060 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001061}
1062
Ady Abraham27cbed72020-04-10 12:56:59 -07001063void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001064 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001065 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001066 // Store the local variable to release the lock.
Ady Abraham27cbed72020-04-10 12:56:59 -07001067 const auto desiredActiveConfig = [&]() -> std::optional<ActiveConfigInfo> {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001068 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham27cbed72020-04-10 12:56:59 -07001069 if (mDesiredActiveConfigChanged) {
1070 return mDesiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001071 }
Ady Abraham27cbed72020-04-10 12:56:59 -07001072 return std::nullopt;
1073 }();
1074
1075 if (!desiredActiveConfig) {
1076 // No desired active config pending to be applied
1077 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001078 }
1079
Ady Abraham2e1dd892020-03-05 13:48:36 -08001080 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001081 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001082 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1083 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001084 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001085 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001086 // display is not valid or we are already in the requested mode
1087 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001088 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001089 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001090 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001091
Ady Abraham838de062019-02-04 10:24:03 -08001092 // Desired active config was set, it is different than the config currently in use, however
1093 // allowed configs might have change by the time we process the refresh.
1094 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001095 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001096 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001097 return;
Ady Abraham838de062019-02-04 10:24:03 -08001098 }
Alec Mouri7f015182019-07-11 13:56:22 -07001099
Ady Abraham27cbed72020-04-10 12:56:59 -07001100 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001101 const auto displayId = display->getId();
1102 LOG_ALWAYS_FATAL_IF(!displayId);
1103
Ady Abrahamabc27602020-04-08 17:20:29 -07001104 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001105
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001106 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001107 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001108 constraints.desiredTimeNanos = systemTime();
1109 constraints.seamlessRequired = false;
1110
Peiyong Line9d809e2020-04-14 13:10:48 -07001111 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001112 auto status =
1113 getHwComposer().setActiveConfigWithConstraints(*displayId,
1114 mUpcomingActiveConfig.configId.value(),
1115 constraints, &outTimeline);
1116 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001117 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1118 // to be sent. We just log the error in this case.
1119 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001120 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001121 }
1122
1123 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1124 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001125 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001126}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001127
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1129 Vector<ColorMode>* outColorModes) {
1130 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001131 return BAD_VALUE;
1132 }
1133
Peiyong Lina52f0292018-03-14 17:26:31 -07001134 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001135 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001136 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001137 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1138
1139 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1140 if (!displayId) {
1141 return NAME_NOT_FOUND;
1142 }
1143
Dominik Laskowski075d3172018-05-24 15:50:06 -07001144 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001145 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001146 }
Michael Wright28f24d02016-07-12 13:30:53 -07001147 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001148
1149 // If it's built-in display and the configuration claims it's not wide color capable,
1150 // filter out all wide color modes. The typical reason why this happens is that the
1151 // hardware is not good enough to support GPU composition of wide color, and thus the
1152 // OEMs choose to disable this capability.
1153 if (isInternalDisplay && !hasWideColorDisplay) {
1154 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1155 isWideColorMode);
1156 } else {
1157 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1158 }
Michael Wright28f24d02016-07-12 13:30:53 -07001159
1160 return NO_ERROR;
1161}
1162
Daniel Solomon42d04562019-01-20 21:03:19 -08001163status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1164 ui::DisplayPrimaries &primaries) {
1165 if (!displayToken) {
1166 return BAD_VALUE;
1167 }
1168
1169 // Currently we only support this API for a single internal display.
1170 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001171 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001172 }
1173
1174 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1175 return NO_ERROR;
1176}
1177
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001178ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001179 Mutex::Autolock lock(mStateLock);
1180
1181 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001182 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001183 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001184 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001185}
1186
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001187status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001188 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001189 Vector<ColorMode> modes;
1190 getDisplayColorModes(displayToken, &modes);
1191 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1192 if (mode < ColorMode::NATIVE || !exists) {
1193 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1194 decodeColorMode(mode).c_str(), mode, displayToken.get());
1195 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001196 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001197 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001198 if (!display) {
1199 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1200 decodeColorMode(mode).c_str(), mode, displayToken.get());
1201 } else if (display->isVirtual()) {
1202 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1203 decodeColorMode(mode).c_str(), mode);
1204 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001205 display->getCompositionDisplay()->setColorProfile(
1206 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1207 RenderIntent::COLORIMETRIC,
1208 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001209 }
1210 }));
1211
Michael Wright28f24d02016-07-12 13:30:53 -07001212 return NO_ERROR;
1213}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001214
Galia Peycheva5492cb52019-10-30 14:13:16 +01001215status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1216 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001217 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001218 return BAD_VALUE;
1219 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001220
1221 Mutex::Autolock lock(mStateLock);
1222
Galia Peycheva5492cb52019-10-30 14:13:16 +01001223 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1224 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001225 return NAME_NOT_FOUND;
1226 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001227 *outSupport =
1228 getHwComposer().hasDisplayCapability(*displayId,
1229 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001230 return NO_ERROR;
1231}
1232
1233void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001234 postMessageAsync(new LambdaMessage([=] {
1235 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1236 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1237 } else {
1238 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1239 }
1240 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001241}
1242
1243status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1244 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001245 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001246 return BAD_VALUE;
1247 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001248
1249 Mutex::Autolock lock(mStateLock);
1250
Galia Peycheva5492cb52019-10-30 14:13:16 +01001251 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1252 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001253 return NAME_NOT_FOUND;
1254 }
1255
Peiyong Line9d809e2020-04-14 13:10:48 -07001256 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001257 getHwComposer().getSupportedContentTypes(*displayId, &types);
1258
1259 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001260 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001261 return NO_ERROR;
1262}
1263
1264void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001265 postMessageAsync(new LambdaMessage([=] {
1266 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001267 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001268 getHwComposer().setContentType(*displayId, type);
1269 } else {
1270 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1271 }
1272 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001273}
1274
Svetoslavd85084b2014-03-20 10:28:31 -07001275status_t SurfaceFlinger::clearAnimationFrameStats() {
1276 Mutex::Autolock _l(mStateLock);
1277 mAnimFrameTracker.clearStats();
1278 return NO_ERROR;
1279}
1280
1281status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1282 Mutex::Autolock _l(mStateLock);
1283 mAnimFrameTracker.getStats(outStats);
1284 return NO_ERROR;
1285}
1286
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001287status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1288 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001289 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001290
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001291 const auto display = getDisplayDeviceLocked(displayToken);
1292 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001293 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1294 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001295 }
1296
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001297 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001298 // meaning the luminance information is already queried from
1299 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001300 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001301 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1302 capabilities.getDesiredMaxLuminance(),
1303 capabilities.getDesiredMaxAverageLuminance(),
1304 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001305
1306 return NO_ERROR;
1307}
1308
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001309std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1310 const DisplayDevice& display) const {
1311 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1312 // avoid repetitive HAL IPC and EDID parsing.
1313 const auto displayId = display.getId();
1314 LOG_FATAL_IF(!displayId);
1315
1316 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1317 LOG_FATAL_IF(!hwcDisplayId);
1318
1319 uint8_t port;
1320 DisplayIdentificationData data;
1321 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1322 ALOGV("%s: No identification data.", __FUNCTION__);
1323 return {};
1324 }
1325
1326 const auto info = parseDisplayIdentificationData(port, data);
1327 if (!info) {
1328 return {};
1329 }
1330 return info->deviceProductInfo;
1331}
1332
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001333status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1334 ui::PixelFormat* outFormat,
1335 ui::Dataspace* outDataspace,
1336 uint8_t* outComponentMask) const {
1337 if (!outFormat || !outDataspace || !outComponentMask) {
1338 return BAD_VALUE;
1339 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001340
1341 Mutex::Autolock lock(mStateLock);
1342
1343 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1344 if (!displayId) {
1345 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001346 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001347
1348 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001349 outDataspace, outComponentMask);
1350}
1351
Kevin DuBois74e53772018-11-19 10:52:38 -08001352status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1353 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001354 uint64_t maxFrames) {
1355 status_t result = NAME_NOT_FOUND;
Kevin DuBois74e53772018-11-19 10:52:38 -08001356
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001357 postMessageSync(new LambdaMessage([&] {
1358 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1359 result = getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1360 componentMask, maxFrames);
1361 } else {
1362 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1363 }
1364 }));
1365
1366 return result;
Kevin DuBois74e53772018-11-19 10:52:38 -08001367}
1368
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001369status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1370 uint64_t maxFrames, uint64_t timestamp,
1371 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001372 Mutex::Autolock lock(mStateLock);
1373
1374 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1375 if (!displayId) {
1376 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001377 }
1378
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001379 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001380}
1381
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001382status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1383 if (!outSupported) {
1384 return BAD_VALUE;
1385 }
1386 *outSupported = getRenderEngine().supportsProtectedContent();
1387 return NO_ERROR;
1388}
1389
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001390status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1391 bool* outIsWideColorDisplay) const {
1392 if (!displayToken || !outIsWideColorDisplay) {
1393 return BAD_VALUE;
1394 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001395
1396 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001397 const auto display = getDisplayDeviceLocked(displayToken);
1398 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001399 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001400 }
Peiyong Linff84a152019-05-17 18:36:19 -07001401
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001402 *outIsWideColorDisplay =
1403 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001404 return NO_ERROR;
1405}
1406
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001407status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001408 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001409 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001410
Dominik Laskowski6505f792019-09-18 11:10:05 -07001411 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1412 mEventQueue->setEventConnection(
1413 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001414 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001415 }));
1416
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001417 return NO_ERROR;
1418}
1419
1420status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001421 Mutex::Autolock lock(mStateLock);
1422 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001423}
1424
Lloyd Pique755e3192018-01-31 16:46:15 -08001425status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1426 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001427 // Try to acquire a lock for 1s, fail gracefully
1428 const status_t err = mStateLock.timedLock(s2ns(1));
1429 const bool locked = (err == NO_ERROR);
1430 if (!locked) {
1431 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1432 return TIMED_OUT;
1433 }
1434
1435 outLayers->clear();
1436 mCurrentState.traverseInZOrder([&](Layer* layer) {
1437 outLayers->push_back(layer->getLayerDebugInfo());
1438 });
1439
1440 mStateLock.unlock();
1441 return NO_ERROR;
1442}
1443
Peiyong Linc6780972018-10-28 15:24:08 -07001444status_t SurfaceFlinger::getCompositionPreference(
1445 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1446 Dataspace* outWideColorGamutDataspace,
1447 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001448 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001449 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001450 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001451 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001452 return NO_ERROR;
1453}
1454
Dan Stozaec460082018-12-17 15:35:09 -08001455status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1456 const sp<IBinder>& stopLayerHandle,
1457 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001458 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001459 return BAD_VALUE;
1460 }
1461 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001462 return NO_ERROR;
1463}
1464
Dan Stozaec460082018-12-17 15:35:09 -08001465status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001466 if (!listener) {
1467 return BAD_VALUE;
1468 }
Dan Stozaec460082018-12-17 15:35:09 -08001469 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001470 return NO_ERROR;
1471}
Dan Gittik57e63c52019-01-18 16:37:54 +00001472
1473status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1474 bool* outSupport) const {
1475 if (!displayToken || !outSupport) {
1476 return BAD_VALUE;
1477 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001478
1479 Mutex::Autolock lock(mStateLock);
1480
Dan Gittik57e63c52019-01-18 16:37:54 +00001481 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1482 if (!displayId) {
1483 return NAME_NOT_FOUND;
1484 }
1485 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001486 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001487 return NO_ERROR;
1488}
1489
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001490status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001491 if (!displayToken) {
1492 return BAD_VALUE;
1493 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001494
1495 status_t result = NAME_NOT_FOUND;
1496
1497 postMessageSync(new LambdaMessage([&] {
1498 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1499 result = getHwComposer().setDisplayBrightness(*displayId, brightness);
1500 } else {
1501 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1502 }
1503 }));
1504
1505 return result;
Dan Gittik57e63c52019-01-18 16:37:54 +00001506}
1507
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001508status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
1509 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001510
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001511 if (powerBoost == Boost::INTERACTION) {
Ady Abraham8532d012019-05-08 14:50:56 -07001512 mScheduler->notifyTouchEvent();
1513 }
1514
1515 return NO_ERROR;
1516}
1517
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001518// ----------------------------------------------------------------------------
1519
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001520sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001521 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001522 const auto& handle =
1523 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001524
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001525 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001526}
1527
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001528// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001529
1530void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001531 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001532}
1533
1534void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001535 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001536 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001537 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001538}
1539
1540void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001541 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001542 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001543 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001544}
1545
1546void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001547 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001548 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001549}
1550
1551status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001552 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001553 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001554}
1555
1556status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001557 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001558 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001559 if (res == NO_ERROR) {
1560 msg->wait();
1561 }
1562 return res;
1563}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001564
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001565void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001566 do {
1567 waitForEvent();
1568 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001569}
1570
Dominik Laskowski83b88212018-12-11 13:34:06 -08001571nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001572 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001573 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1574 return 0;
1575 }
1576
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001577 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001578}
1579
Peiyong Line9d809e2020-04-14 13:10:48 -07001580void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001581 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001582 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001583 ATRACE_NAME("SF onVsync");
1584
Steven Thomas3cfac282017-02-06 12:29:30 -08001585 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001586 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001587 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001588 return;
1589 }
1590
Dominik Laskowski075d3172018-05-24 15:50:06 -07001591 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001592 return;
1593 }
1594
Dominik Laskowski075d3172018-05-24 15:50:06 -07001595 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001596 // For now, we don't do anything with external display vsyncs.
1597 return;
1598 }
1599
Alec Mourif8e689c2019-05-20 18:32:22 -07001600 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001601 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001602 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001603 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001604 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001605}
1606
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001607void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001608 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1609 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001610}
1611
Ady Abraham2139f732019-11-13 18:56:40 -08001612bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001613 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001614}
1615
Ady Abraham2139f732019-11-13 18:56:40 -08001616void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1617 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001618 const auto display = getDefaultDisplayDeviceLocked();
1619 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001620 return;
1621 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001622 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001623
Ana Krulec7d1d6832018-12-27 11:10:09 -08001624 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001625 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001626 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001627 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001628 return;
1629 }
1630
Ady Abrahamabc27602020-04-08 17:20:29 -07001631 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001632}
1633
Peiyong Line9d809e2020-04-14 13:10:48 -07001634void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
1635 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001636 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001637 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001638
Lloyd Piqueba04e622017-12-14 17:11:26 -08001639 // Ignore events that do not have the right sequenceId.
1640 if (sequenceId != getBE().mComposerSequenceId) {
1641 return;
1642 }
1643
Steven Thomasb02664d2017-07-26 18:48:28 -07001644 // Only lock if we're not on the main thread. This function is normally
1645 // called on a hwbinder thread, but for the primary display it's called on
1646 // the main thread with the state lock already held, so don't attempt to
1647 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001648 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001649
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001650 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001651
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001652 if (std::this_thread::get_id() == mMainThreadId) {
1653 // Process all pending hot plug events immediately if we are on the main thread.
1654 processDisplayHotplugEventsLocked();
1655 }
1656
Lloyd Piqueba04e622017-12-14 17:11:26 -08001657 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001658}
1659
Ady Abraham7159f572019-10-11 11:10:18 -07001660void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001661 int32_t sequenceId, hal::HWDisplayId /*display*/,
1662 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001663 Mutex::Autolock lock(mStateLock);
1664 if (sequenceId != getBE().mComposerSequenceId) {
1665 return;
1666 }
1667 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001668}
1669
Peiyong Line9d809e2020-04-14 13:10:48 -07001670void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001671 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1672 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1673}
1674
Peiyong Line9d809e2020-04-14 13:10:48 -07001675void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001676 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001677 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001678 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001679 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001680 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001681}
1682
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001683void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001684 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001685
1686 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1687 // display power state.
1688 postMessageAsync(new LambdaMessage(
1689 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1690}
1691
1692void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1693 ATRACE_CALL();
1694
Peiyong Line9d809e2020-04-14 13:10:48 -07001695 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001696
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001697 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001698 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1699 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001700 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001701 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001702 }
Mathias Agopian86303202012-07-24 22:46:10 -07001703}
1704
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001705// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001706void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001707 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001708 // Clear the drawing state so that the logic inside of
1709 // handleTransactionLocked will fire. It will determine the delta between
1710 // mCurrentState and mDrawingState and re-apply all changes when we make the
1711 // transition.
1712 mDrawingState.displays.clear();
1713 mDisplays.clear();
1714}
1715
Steven Thomas050b2c82017-03-06 11:45:16 -08001716void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001717 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001718 if (!mVrFlinger)
1719 return;
1720 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001721 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001722 return;
1723 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001724
Lloyd Pique441d5042018-10-18 16:49:51 -07001725 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001726 ALOGE("Vr flinger is only supported for remote hardware composer"
1727 " service connections. Ignoring request to transition to vr"
1728 " flinger.");
1729 mVrFlingerRequestsDisplay = false;
1730 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001731 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001732
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001733 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001734
Steven Thomas0123ac62018-07-12 11:32:34 -07001735 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001736 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001737
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001738 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001739
1740 // Clear out all the output layers from the composition engine for all
1741 // displays before destroying the hardware composer interface. This ensures
1742 // any HWC layers are destroyed through that interface before it becomes
1743 // invalid.
1744 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001745 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001746 }
1747
Steven Thomas0123ac62018-07-12 11:32:34 -07001748 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1749 // called below. Clear the reference now so we don't accidentally use it
1750 // later.
1751 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001752
Steven Thomasb02664d2017-07-26 18:48:28 -07001753 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001754 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001755 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001756
Steven Thomasb02664d2017-07-26 18:48:28 -07001757 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001758 // Delete the current instance before creating the new one
1759 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1760 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1761 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001762 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001763
Lloyd Pique441d5042018-10-18 16:49:51 -07001764 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001765 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001766
1767 if (vrFlingerRequestsDisplay) {
1768 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001769 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001770
1771 mVisibleRegionsDirty = true;
1772 invalidateHwcGeometry();
1773
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001774 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001775 display = getDefaultDisplayDeviceLocked();
1776 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001777 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001778
Steven Thomasb02664d2017-07-26 18:48:28 -07001779 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001780 const nsecs_t vsyncPeriod = getVsyncPeriod();
1781 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001782
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001783 // The present fences returned from vr_hwc are not an accurate
1784 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001785 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001786
Steven Thomasb02664d2017-07-26 18:48:28 -07001787 // Use phase of 0 since phase is not known.
1788 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001789 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001790 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001791
Ana Krulecc2870422019-01-29 19:00:58 -08001792 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001793
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001794 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001795 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001796}
1797
Alec Mouri6d414b52020-03-17 11:18:05 -07001798sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001799 // We are storing the last 2 present fences. If sf's phase offset is to be
1800 // woken up before the actual vsync but targeting the next vsync, we need to check
1801 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001802 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1803 : mPreviousPresentFences[1];
1804}
1805
1806bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1807 ATRACE_CALL();
1808 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001809
Ady Abraham11579302019-09-19 12:35:58 -07001810 if (fence == Fence::NO_FENCE) {
1811 return false;
1812 }
1813
1814 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1815 fence->wait(graceTimeMs);
1816 }
1817
1818 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001819}
1820
Alec Mouri6d414b52020-03-17 11:18:05 -07001821nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1822 const sp<Fence>& fence = previousFrameFence();
1823
1824 if (fence == Fence::NO_FENCE) {
1825 return Fence::SIGNAL_TIME_INVALID;
1826 }
1827
1828 return fence->getSignalTime();
1829}
1830
Ady Abraham0ed31c92020-04-16 11:48:45 -07001831void SurfaceFlinger::populateExpectedPresentTime(nsecs_t wakeupTime) {
Alec Mouriaa614192019-06-06 13:28:34 -07001832 DisplayStatInfo stats;
1833 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham0ed31c92020-04-16 11:48:45 -07001834 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(wakeupTime);
Alec Mouriaa614192019-06-06 13:28:34 -07001835 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001836 mExpectedPresentTime.store(
1837 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001838}
1839
Ady Abraham0ed31c92020-04-16 11:48:45 -07001840void SurfaceFlinger::onMessageReceived(int32_t what, nsecs_t when) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001841 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001842 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001843 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001844 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001845 // calculate the expected present time once and use the cached
1846 // value throughout this frame to make sure all layers are
1847 // seeing this same value.
Alec Mouri6d414b52020-03-17 11:18:05 -07001848 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
Ady Abraham0ed31c92020-04-16 11:48:45 -07001849 populateExpectedPresentTime(when);
Ady Abraham7c03ce62019-07-19 10:59:45 -07001850
Ady Abraham11579302019-09-19 12:35:58 -07001851 // When Backpressure propagation is enabled we want to give a small grace period
1852 // for the present fence to fire instead of just giving up on this frame to handle cases
1853 // where present fence is just about to get signaled.
1854 const int graceTimeForPresentFenceMs =
1855 (mPropagateBackpressure &&
1856 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1857 ? 1
1858 : 0;
Alec Mouri6d414b52020-03-17 11:18:05 -07001859
1860 // Pending frames may trigger backpressure propagation.
1861 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1862 previousFramePending(
1863 graceTimeForPresentFenceMs)};
1864
1865 // Frame missed counts for metrics tracking.
1866 // A frame is missed if the prior frame is still pending. If no longer pending,
1867 // then we still count the frame as missed if the predicted present time
1868 // was further in the past than when the fence actually fired.
1869
1870 // Add some slop to correct for drift. This should generally be
1871 // smaller than a typical frame duration, but should not be so small
1872 // that it reports reasonable drift as a missed frame.
1873 DisplayStatInfo stats;
1874 mScheduler->getDisplayStatInfo(&stats);
1875 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1876 const nsecs_t previousPresentTime = previousFramePresentTime();
1877 const TracedOrdinal<bool> frameMissed =
1878 {"PrevFrameMissed",
1879 framePending ||
1880 (previousPresentTime >= 0 &&
1881 (lastExpectedPresentTime < previousPresentTime - frameMissedSlop))};
1882 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001883 mHadDeviceComposition && frameMissed};
Alec Mouri6d414b52020-03-17 11:18:05 -07001884 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001885 mHadClientComposition && frameMissed};
1886
Alec Mouricc0fc602019-02-26 21:45:19 -08001887 if (frameMissed) {
1888 mFrameMissedCount++;
1889 mTimeStats->incrementMissedFrames();
Alec Mouri5f487d42020-02-06 09:26:19 -08001890 if (mMissedFrameJankCount == 0) {
1891 mMissedFrameJankStart = systemTime();
1892 }
1893 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001894 }
1895
Alec Mouri40189b02019-03-05 15:07:54 -08001896 if (hwcFrameMissed) {
1897 mHwcFrameMissedCount++;
1898 }
1899
1900 if (gpuFrameMissed) {
1901 mGpuFrameMissedCount++;
1902 }
1903
Ady Abraham27cbed72020-04-10 12:56:59 -07001904 // If we are in the middle of a config change and the fence hasn't
1905 // fired yet just wait for the next invalidate
1906 if (mSetActiveConfigPending) {
1907 if (framePending) {
1908 mEventQueue->invalidate();
1909 break;
1910 }
1911
1912 // We received the present fence from the HWC, so we assume it successfully updated
1913 // the config, hence we update SF.
1914 mSetActiveConfigPending = false;
1915 setActiveConfigInternal();
1916 }
1917
Alec Mouri6d414b52020-03-17 11:18:05 -07001918 if (framePending && mPropagateBackpressure) {
Ady Abrahamadb9a992019-09-19 21:21:55 +00001919 if ((hwcFrameMissed && !gpuFrameMissed) ||
1920 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001921 signalLayerUpdate();
1922 break;
1923 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001924 }
Dan Stoza50182882016-07-08 12:02:20 -07001925
Alec Mouri5f487d42020-02-06 09:26:19 -08001926 // Our jank window is always at least 100ms since we missed a
1927 // frame...
1928 static constexpr nsecs_t kMinJankyDuration =
1929 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1930 // ...but if it's larger than 1s then we missed the trace cutoff.
1931 static constexpr nsecs_t kMaxJankyDuration =
1932 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1933 // If we're in a user build then don't push any atoms
1934 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1935 const auto displayDevice = getDefaultDisplayDeviceLocked();
1936 // Only report jank when the display is on, as displays in DOZE
1937 // power mode may operate at a different frame rate than is
1938 // reported in their config, which causes noticeable (but less
1939 // severe) jank.
1940 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1941 const nsecs_t currentTime = systemTime();
1942 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1943 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1944 ATRACE_NAME("Jank detected");
1945 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1946 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1947 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1948 jankyDurationMillis, mMissedFrameJankCount);
1949 }
1950
1951 // We either reported a jank event or we missed the trace
1952 // window, so clear counters here.
1953 if (jankDuration > kMinJankyDuration) {
1954 mMissedFrameJankCount = 0;
1955 mMissedFrameJankStart = 0;
1956 }
1957 }
1958 }
1959
Steven Thomas050b2c82017-03-06 11:45:16 -08001960 // Now that we're going to make it to the handleMessageTransaction()
1961 // call below it's safe to call updateVrFlinger(), which will
1962 // potentially trigger a display handoff.
1963 updateVrFlinger();
1964
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001965 if (mTracingEnabledChanged) {
1966 mTracingEnabled = mTracing.isEnabled();
1967 mTracingEnabledChanged = false;
1968 }
1969
Vishnu Nair60db8c02020-04-02 11:55:16 -07001970 bool refreshNeeded;
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001971 {
1972 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1973
Vishnu Nair60db8c02020-04-02 11:55:16 -07001974 refreshNeeded = handleMessageTransaction();
1975 refreshNeeded |= handleMessageInvalidate();
1976 if (mTracingEnabled) {
1977 mAddCompositionStateToTrace =
1978 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1979 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1980 mTracing.notifyLocked("visibleRegionsDirty");
1981 }
1982 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001983 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001984
Ana Krulecc84d09b2019-11-02 23:10:29 +01001985 // Layers need to get updated (in the previous line) before we can use them for
1986 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001987 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1988 // and may eventually call to ~Layer() if it holds the last reference
1989 {
1990 Mutex::Autolock _l(mStateLock);
1991 mScheduler->chooseRefreshRateForContent();
1992 }
1993
Ady Abraham27cbed72020-04-10 12:56:59 -07001994 performSetActiveConfig();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001995
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001996 updateCursorAsync();
1997 updateInputFlinger();
1998
Dan Stoza58784442014-12-02 16:58:17 -08001999 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002000 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08002001 // Signal a refresh if a transaction modified the window state,
2002 // a new buffer was latched, or if HWC has requested a full
2003 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08002004 if (mFrameStartTime <= 0) {
2005 // We should only use the time of the first invalidate
2006 // message that signals a refresh as the beginning of the
2007 // frame. Otherwise the real frame time will be
2008 // underestimated.
2009 mFrameStartTime = frameStart;
2010 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08002011 signalRefresh();
2012 }
2013 break;
2014 }
2015 case MessageQueue::REFRESH: {
2016 handleMessageRefresh();
2017 break;
2018 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002019 }
2020}
2021
Dan Stoza6b9454d2014-11-07 16:00:59 -08002022bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08002023 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002024 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002025
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002026 bool flushedATransaction = flushTransactionQueues();
2027
2028 bool runHandleTransaction = transactionFlags &&
2029 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
2030
2031 if (runHandleTransaction) {
2032 handleTransaction(eTransactionMask);
2033 } else {
2034 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002035 }
2036
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002037 if (transactionFlushNeeded()) {
2038 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002039 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002040
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002041 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002042}
2043
Mathias Agopian4fec8732012-06-29 14:12:52 -07002044void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002045 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002046
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002047 mRefreshPending = false;
2048
Lloyd Piqueab039b52019-02-13 14:22:42 -08002049 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002050 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002051 for (const auto& [_, display] : mDisplays) {
2052 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2053 }
2054 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002055 if (auto layerFE = layer->getCompositionEngineLayerFE())
2056 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002057 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002058 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2059 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002060 if (auto layerFE = layer->getCompositionEngineLayerFE())
2061 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002062 }
2063
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002064 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002065 refreshArgs.outputColorSetting = useColorManagement
2066 ? mDisplayColorSetting
2067 : compositionengine::OutputColorSetting::kUnmanaged;
2068 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2069 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002070
2071 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2072 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002073 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002074
2075 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2076 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2077 mDrawingState.colorMatrixChanged = false;
2078 }
2079
2080 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2081
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002082 if (mDebugRegion != 0) {
2083 refreshArgs.devOptFlashDirtyRegionsDelay =
2084 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2085 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002086
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002087 mGeometryInvalid = false;
2088
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002089 // Store the present time just before calling to the composition engine so we could notify
2090 // the scheduler.
2091 const auto presentTime = systemTime();
2092
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002093 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002094 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2095 // Reset the frame start time now that we've recorded this frame.
2096 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002097
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002098 mScheduler->onDisplayRefreshed(presentTime);
2099
David Sodmanfa9b2af2017-12-24 13:28:59 -08002100 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002101 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002102
Alec Mouri8f7a0102020-04-15 12:11:10 -07002103 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2104
Lloyd Pique66d68602019-02-13 14:23:31 -08002105 mHadClientComposition =
2106 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2107 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002108 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2109 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002110 });
2111 mHadDeviceComposition =
2112 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2113 auto& displayDevice = tokenDisplayPair.second;
2114 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2115 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002116 mReusedClientComposition =
2117 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2118 auto& displayDevice = tokenDisplayPair.second;
2119 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2120 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002121
Alec Mouri8f7a0102020-04-15 12:11:10 -07002122 // Only report a strategy change if we move in and out of composition with hw overlays
2123 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2124 mTimeStats->incrementCompositionStrategyChanges();
2125 }
2126
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002127 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002128
David Sodman7e4ae112018-02-09 15:02:28 -08002129 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002130 if (mVisibleRegionsDirty) {
2131 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002132 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002133 mTracing.notify("visibleRegionsDirty");
2134 }
2135 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002136
2137 if (mCompositionEngine->needsAnotherUpdate()) {
2138 signalLayerUpdate();
2139 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002140}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002141
David Sodmanfa9b2af2017-12-24 13:28:59 -08002142
2143bool SurfaceFlinger::handleMessageInvalidate() {
2144 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002145 bool refreshNeeded = handlePageFlip();
2146
Vishnu Nair4351ad52019-02-11 14:13:02 -08002147 if (mVisibleRegionsDirty) {
2148 computeLayerBounds();
2149 }
2150
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002151 for (auto& layer : mLayersPendingRefresh) {
2152 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002153 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002154 invalidateLayerStack(layer, visibleReg);
2155 }
2156 mLayersPendingRefresh.clear();
2157 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002158}
2159
Ana Krulece588e312018-09-18 12:32:24 -07002160void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2161 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002162 // Update queue of past composite+present times and determine the
2163 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002164 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002165 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002166 while (!getBE().mCompositePresentTimes.empty()) {
2167 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002168 // Cached values should have been updated before calling this method,
2169 // which helps avoid duplicate syscalls.
2170 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2171 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2172 break;
2173 }
2174 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002175 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002176 }
2177
2178 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002179 while (getBE().mCompositePresentTimes.size() > 16) {
2180 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002181 }
2182
Ana Krulece588e312018-09-18 12:32:24 -07002183 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002184}
2185
Ana Krulece588e312018-09-18 12:32:24 -07002186void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2187 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002188 // Integer division and modulo round toward 0 not -inf, so we need to
2189 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002190 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2191 ? (stats.vsyncPeriod -
2192 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2193 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002194
Ady Abraham9e16a482019-12-03 17:19:41 -08002195 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002196 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002197 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002198 }
2199
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002200 // Snap the latency to a value that removes scheduling jitter from the
2201 // composition and present times, which often have >1ms of jitter.
2202 // Reducing jitter is important if an app attempts to extrapolate
2203 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002204 // Snapping also allows an app to precisely calculate
2205 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002206 nsecs_t bias = stats.vsyncPeriod / 2;
2207 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2208 nsecs_t snappedCompositeToPresentLatency =
2209 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002210
David Sodman99974d22017-11-28 12:04:33 -08002211 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002212 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2213 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002214 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002215}
2216
David Sodman2b406362017-12-15 13:33:47 -08002217void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002218{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002219 ATRACE_CALL();
2220 ALOGV("postComposition");
2221
Brian Andersonf6386862016-10-31 16:34:13 -07002222 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002223 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002224 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002225 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002226 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002227 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002228
David Sodman73beded2017-11-15 11:56:06 -08002229 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002230 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002231 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002232 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002233 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2234 ->getRenderSurface()
2235 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002236 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002237 } else {
2238 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2239 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002240
David Sodman73beded2017-11-15 11:56:06 -08002241 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002242 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2243 mPreviousPresentFences[0] = displayDevice
2244 ? getHwComposer().getPresentFence(*displayDevice->getId())
2245 : Fence::NO_FENCE;
2246 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002247 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002248
Ana Krulece588e312018-09-18 12:32:24 -07002249 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002250 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002251
Lloyd Piqueab039b52019-02-13 14:22:42 -08002252 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2253 // be sampled a little later than when we started doing work for this frame,
2254 // but that should be okay since updateCompositorTiming has snapping logic.
2255 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2256 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002257 CompositorTiming compositorTiming;
2258 {
David Sodman99974d22017-11-28 12:04:33 -08002259 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2260 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002261 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002262
Edgar Arriaga844fa672020-01-16 14:21:42 -08002263 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002264 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2265 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002266 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002267 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002268 }
Robert Carr2047fae2016-11-28 14:09:09 -08002269 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002270
Valerie Hau4b678442020-04-14 10:50:42 -07002271 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2272 mTransactionCompletedThread.sendCallbacks();
2273
Ady Abraham92fa2f42020-02-11 15:33:56 -08002274 if (displayDevice && displayDevice->isPrimary() &&
2275 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002276 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002277 }
2278
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002279 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002280 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2281 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002282 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002283 }
2284 }
2285
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002286 if (mAnimCompositionPending) {
2287 mAnimCompositionPending = false;
2288
Brian Anderson4e606e32017-03-16 15:34:57 -07002289 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002290 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002291 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002292 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002293 // The HWC doesn't support present fences, so use the refresh
2294 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002295 const nsecs_t presentTime =
2296 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002297 mAnimFrameTracker.setActualPresentTime(presentTime);
2298 }
2299 mAnimFrameTracker.advanceFrame();
2300 }
Dan Stozab90cf072015-03-05 11:05:59 -08002301
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002302 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002303 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002304 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002305 }
2306
Vishnu Nair9b079a22020-01-21 14:36:08 -08002307 if (mReusedClientComposition) {
2308 mTimeStats->incrementClientCompositionReusedFrames();
2309 }
2310
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002311 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002312
Alec Mouri717bcb62020-02-10 17:07:19 -08002313 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2314 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2315 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2316
Lloyd Pique32cbe282018-10-19 13:09:22 -07002317 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2318 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002319 return;
2320 }
2321
2322 nsecs_t currentTime = systemTime();
2323 if (mHasPoweredOff) {
2324 mHasPoweredOff = false;
2325 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002326 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002327 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002328 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2329 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002330 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002331 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002332 }
David Sodman4a36e932017-11-07 14:29:47 -08002333 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002334 }
David Sodman4a36e932017-11-07 14:29:47 -08002335 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002336
Alec Mourid9c71752019-09-30 17:27:13 -07002337 // Cleanup any outstanding resources due to rendering a prior frame.
2338 getRenderEngine().cleanupPostRender();
2339
Dan Stoza436ccf32018-06-21 12:10:12 -07002340 {
2341 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002342 if (mTexturePool.size() < mTexturePoolSize) {
2343 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002344 const size_t offset = mTexturePool.size();
2345 mTexturePool.resize(mTexturePoolSize);
2346 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2347 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002348 } else if (mTexturePool.size() > mTexturePoolSize) {
2349 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2350 const size_t offset = mTexturePoolSize;
2351 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2352 mTexturePool.resize(mTexturePoolSize);
2353 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002354 }
2355 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002356
Kevin DuBois413287f2019-02-25 08:46:47 -08002357 if (mLumaSampling && mRegionSamplingThread) {
2358 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002359 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002360
2361 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2362 // side-effect of getTotalSize(), so we check that again here
2363 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002364 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002365 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2366 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002367}
2368
Vishnu Nair4351ad52019-02-11 14:13:02 -08002369void SurfaceFlinger::computeLayerBounds() {
2370 for (const auto& pair : mDisplays) {
2371 const auto& displayDevice = pair.second;
2372 const auto display = displayDevice->getCompositionDisplay();
2373 for (const auto& layer : mDrawingState.layersSortedByZ) {
2374 // only consider the layers on the given layer stack
2375 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002376 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002377 }
2378
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002379 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2380 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002381 }
2382 }
2383}
2384
David Sodmanfa9b2af2017-12-24 13:28:59 -08002385void SurfaceFlinger::postFrame()
2386{
2387 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002388 const auto display = getDefaultDisplayDeviceLocked();
2389 if (display && getHwComposer().isConnected(*display->getId())) {
2390 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002391 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2392 logFrameStats();
2393 }
2394 }
2395}
2396
Mathias Agopian87baae12012-07-31 12:38:26 -07002397void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002398{
Mathias Agopian841cde52012-03-01 15:44:37 -08002399 ATRACE_CALL();
2400
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002401 // here we keep a copy of the drawing state (that is the state that's
2402 // going to be overwritten by handleTransactionLocked()) outside of
2403 // mStateLock so that the side-effects of the State assignment
2404 // don't happen with mStateLock held (which can cause deadlocks).
2405 State drawingState(mDrawingState);
2406
Mathias Agopianca4d3602011-05-19 15:38:14 -07002407 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002408 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002409
Mathias Agopianca4d3602011-05-19 15:38:14 -07002410 // Here we're guaranteed that some transaction flags are set
2411 // so we can call handleTransactionLocked() unconditionally.
2412 // We call getTransactionFlags(), which will also clear the flags,
2413 // with mStateLock held to guarantee that mCurrentState won't change
2414 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002415
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002416 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002417 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002418 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002419
Mathias Agopianca4d3602011-05-19 15:38:14 -07002420 mDebugInTransaction = 0;
2421 invalidateHwcGeometry();
2422 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002423}
2424
Lloyd Piqueba04e622017-12-14 17:11:26 -08002425void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2426 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002427 const std::optional<DisplayIdentificationInfo> info =
2428 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002429
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002431 continue;
2432 }
2433
Dominik Laskowski55c85402020-01-21 16:25:47 -08002434 const DisplayId displayId = info->id;
2435 const auto it = mPhysicalDisplayTokens.find(displayId);
2436
Peiyong Line9d809e2020-04-14 13:10:48 -07002437 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002438 if (it == mPhysicalDisplayTokens.end()) {
2439 ALOGV("Creating display %s", to_string(displayId).c_str());
2440
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002441 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002442 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002443 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002444
Dominik Laskowski075d3172018-05-24 15:50:06 -07002445 DisplayDeviceState state;
Marin Shalamanov700e6392020-02-12 20:22:26 +01002446 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2447 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 state.isSecure = true; // All physical displays are currently considered secure.
2449 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002450
2451 sp<IBinder> token = new BBinder();
2452 mCurrentState.displays.add(token, state);
2453 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2454
Dominik Laskowski075d3172018-05-24 15:50:06 -07002455 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002456 } else {
2457 ALOGV("Recreating display %s", to_string(displayId).c_str());
2458
2459 const auto token = it->second;
2460 auto& state = mCurrentState.displays.editValueFor(token);
2461 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002462 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002463 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002464 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002465
Dominik Laskowski55c85402020-01-21 16:25:47 -08002466 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002467 if (index >= 0) {
2468 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2469 mInterceptor->saveDisplayDeletion(state.sequenceId);
2470 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002471 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002472 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002473 }
2474
2475 processDisplayChangesLocked();
2476 }
2477
2478 mPendingHotplugEvents.clear();
2479}
2480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002481void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002482 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2483 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002484}
2485
Lloyd Pique99d3da52018-01-22 17:48:03 -08002486sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002487 const wp<IBinder>& displayToken,
2488 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002489 const DisplayDeviceState& state,
2490 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002491 const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique9370a482019-10-03 17:58:30 -07002492 auto displayId = compositionDisplay->getDisplayId();
2493 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002494 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002495 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002496 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002497 creationArgs.hasWideColorGamut = false;
2498 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002499
Dominik Laskowski55c85402020-01-21 16:25:47 -08002500 if (const auto& physical = state.physical) {
2501 creationArgs.connectionType = physical->type;
2502 }
2503
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002504 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002505 creationArgs.isPrimary = isInternalDisplay;
2506
2507 if (useColorManagement && displayId) {
2508 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002509 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002510 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002511 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002512 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002513
Dominik Laskowski7e045462018-05-30 13:02:02 -07002514 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002515 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002516 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002517 }
tangrobin6753a022018-08-10 10:58:54 +08002518 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002519
Dominik Laskowski075d3172018-05-24 15:50:06 -07002520 if (displayId) {
2521 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002522 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002523 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002524 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002525
Lloyd Pique90c115d2018-09-18 21:39:42 -07002526 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002527 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002528 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002529
Lloyd Pique99d3da52018-01-22 17:48:03 -08002530 // Make sure that composition can never be stalled by a virtual display
2531 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002532 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002533 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002534 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2535 }
2536
Dominik Laskowski718f9602019-11-09 20:01:35 -08002537 creationArgs.physicalOrientation =
2538 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002539
Lloyd Pique99d3da52018-01-22 17:48:03 -08002540 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002541 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002542
Lloyd Pique9370a482019-10-03 17:58:30 -07002543 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002544
2545 if (maxFrameBufferAcquiredBuffers >= 3) {
2546 nativeWindowSurface->preallocateBuffers();
2547 }
2548
2549 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002550 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002551 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002552 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002553 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002554 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002555 display->getCompositionDisplay()->setColorProfile(
2556 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2557 RenderIntent::COLORIMETRIC,
2558 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002559 if (!state.isVirtual()) {
2560 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002561 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2562 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002563 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002564
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002565 display->setLayerStack(state.layerStack);
2566 display->setProjection(state.orientation, state.viewport, state.frame);
2567 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002568
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002569 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002570}
2571
Marin Shalamanovae685592020-02-12 17:12:22 +01002572void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2573 const DisplayDeviceState& state) {
2574 int width = 0;
2575 int height = 0;
2576 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2577 if (state.physical) {
2578 const auto& activeConfig =
2579 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2580 width = activeConfig->getWidth();
2581 height = activeConfig->getHeight();
2582 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2583 } else if (state.surface != nullptr) {
2584 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2585 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2586 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2587 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2588 int intPixelFormat;
2589 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2590 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2591 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2592 } else {
2593 // Virtual displays without a surface are dormant:
2594 // they have external state (layer stack, projection,
2595 // etc.) but no internal state (i.e. a DisplayDevice).
2596 return;
2597 }
2598
2599 compositionengine::DisplayCreationArgsBuilder builder;
2600 if (const auto& physical = state.physical) {
2601 builder.setPhysical({physical->id, physical->type});
2602 }
2603 builder.setPixels(ui::Size(width, height));
2604 builder.setPixelFormat(pixelFormat);
2605 builder.setIsSecure(state.isSecure);
2606 builder.setLayerStackId(state.layerStack);
2607 builder.setPowerAdvisor(&mPowerAdvisor);
2608 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2609 builder.setName(state.displayName);
2610 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2611
2612 sp<compositionengine::DisplaySurface> displaySurface;
2613 sp<IGraphicBufferProducer> producer;
2614 sp<IGraphicBufferProducer> bqProducer;
2615 sp<IGraphicBufferConsumer> bqConsumer;
2616 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2617
2618 std::optional<DisplayId> displayId = compositionDisplay->getId();
2619
2620 if (state.isVirtual()) {
2621 sp<VirtualDisplaySurface> vds =
2622 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2623 bqConsumer, state.displayName);
2624
2625 displaySurface = vds;
2626 producer = vds;
2627 } else {
2628 ALOGE_IF(state.surface != nullptr,
2629 "adding a supported display, but rendering "
2630 "surface is provided (%p), ignoring it",
2631 state.surface.get());
2632
2633 LOG_ALWAYS_FATAL_IF(!displayId);
2634 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2635 maxGraphicsWidth, maxGraphicsHeight);
2636 producer = bqProducer;
2637 }
2638
Marin Shalamanov700e6392020-02-12 20:22:26 +01002639 LOG_FATAL_IF(!displaySurface);
2640 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2641 displaySurface, producer);
2642 mDisplays.emplace(displayToken, display);
2643 if (!state.isVirtual()) {
2644 LOG_FATAL_IF(!displayId);
2645 dispatchDisplayHotplugEvent(displayId->value, true);
2646 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002647
Marin Shalamanov700e6392020-02-12 20:22:26 +01002648 if (display->isPrimary()) {
2649 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanovae685592020-02-12 17:12:22 +01002650 }
2651}
2652
2653void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2654 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2655 // Save display ID before disconnecting.
2656 const auto displayId = display->getId();
2657 display->disconnect();
2658
2659 if (!display->isVirtual()) {
Marin Shalamanov700e6392020-02-12 20:22:26 +01002660 LOG_FATAL_IF(!displayId);
Marin Shalamanovae685592020-02-12 17:12:22 +01002661 dispatchDisplayHotplugEvent(displayId->value, false);
2662 }
2663 }
2664
2665 mDisplays.erase(displayToken);
2666}
2667
2668void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2669 const DisplayDeviceState& currentState,
2670 const DisplayDeviceState& drawingState) {
2671 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2672 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002673 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002674 // changing the surface is like destroying and recreating the DisplayDevice
2675 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2676 display->disconnect();
2677 }
2678 mDisplays.erase(displayToken);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002679 if (const auto& physical = currentState.physical) {
2680 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2681 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002682 processDisplayAdded(displayToken, currentState);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002683 if (currentState.physical) {
2684 initializeDisplays();
2685 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002686 return;
2687 }
2688
2689 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2690 if (currentState.layerStack != drawingState.layerStack) {
2691 display->setLayerStack(currentState.layerStack);
2692 }
2693 if ((currentState.orientation != drawingState.orientation) ||
2694 (currentState.viewport != drawingState.viewport) ||
2695 (currentState.frame != drawingState.frame)) {
2696 display->setProjection(currentState.orientation, currentState.viewport,
2697 currentState.frame);
2698 }
2699 if (currentState.width != drawingState.width ||
2700 currentState.height != drawingState.height) {
2701 display->setDisplaySize(currentState.width, currentState.height);
2702 if (display->isPrimary()) {
2703 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2704 }
2705 }
2706 }
2707}
2708
Lloyd Pique347200f2017-12-14 17:00:15 -08002709void SurfaceFlinger::processDisplayChangesLocked() {
2710 // here we take advantage of Vector's copy-on-write semantics to
2711 // improve performance by skipping the transaction entirely when
2712 // know that the lists are identical
2713 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2714 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2715 if (!curr.isIdenticalTo(draw)) {
2716 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002717
2718 // find the displays that were removed
2719 // (ie: in drawing state but not in current state)
2720 // also handle displays that changed
2721 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01002722 for (size_t i = 0; i < draw.size(); i++) {
2723 const wp<IBinder>& displayToken = draw.keyAt(i);
2724 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 if (j < 0) {
2726 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01002727 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002728 } else {
2729 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01002730 const DisplayDeviceState& currentState = curr[j];
2731 const DisplayDeviceState& drawingState = draw[i];
2732 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002733 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002734 }
2735
2736 // find displays that were added
2737 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01002738 for (size_t i = 0; i < curr.size(); i++) {
2739 const wp<IBinder>& displayToken = curr.keyAt(i);
2740 if (draw.indexOfKey(displayToken) < 0) {
2741 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002742 }
2743 }
2744 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002745
2746 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002747}
2748
Mathias Agopian87baae12012-07-31 12:38:26 -07002749void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002750{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002751 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2752
Dan Stoza7dde5992015-05-22 09:51:44 -07002753 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002754 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002755 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002756 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 /*
2759 * Traversal of the children
2760 * (perform the transaction for each of them if needed)
2761 */
2762
Marissa Wall06255332019-03-27 13:48:27 -07002763 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002764 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002766 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767
2768 const uint32_t flags = layer->doTransaction(0);
2769 if (flags & Layer::eVisibleRegion)
2770 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002771
2772 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002773 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002774 }
Robert Carr2047fae2016-11-28 14:09:09 -08002775 });
Marissa Wall06255332019-03-27 13:48:27 -07002776 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777 }
2778
2779 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002780 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 */
2782
Mathias Agopiane57f2922012-08-09 16:29:12 -07002783 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002784 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002785 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002786 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002788 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002789 // The transform hint might have changed for some layers
2790 // (either because a display has changed, or because a layer
2791 // as changed).
2792 //
2793 // Walk through all the layers in currentLayers,
2794 // and update their transform hint.
2795 //
2796 // If a layer is visible only on a single display, then that
2797 // display is used to calculate the hint, otherwise we use the
2798 // default display.
2799 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002800 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002801 // the hint is set before we acquire a buffer from the surface texture.
2802 //
2803 // NOTE: layer transactions have taken place already, so we use their
2804 // drawing state. However, SurfaceFlinger's own transaction has not
2805 // happened yet, so we must use the current state layer list
2806 // (soon to become the drawing state list).
2807 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002808 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002809 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002810 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002811 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002812 // NOTE: we rely on the fact that layers are sorted by
2813 // layerStack first (so we don't have to traverse the list
2814 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002815 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002816 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002817 currentlayerStack = layerStack;
2818 // figure out if this layerstack is mirrored
2819 // (more than one display) if so, pick the default display,
2820 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002821 hintDisplay = nullptr;
2822 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002823 if (display->getCompositionDisplay()
2824 ->belongsInOutput(layer->getLayerStack(),
2825 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002826 if (hintDisplay) {
2827 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002828 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002829 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002830 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002831 }
2832 }
2833 }
2834 }
Chet Haase91d25932013-04-11 15:24:55 -07002835
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002836 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002837 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2838 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002839
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002840 // could be null when this layer is using a layerStack
2841 // that is not visible on any display. Also can occur at
2842 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002843 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002844 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002845
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002846 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002847 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002848 if (hintDisplay) {
2849 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002850 }
Robert Carr2047fae2016-11-28 14:09:09 -08002851
2852 first = false;
2853 });
Mathias Agopian84300952012-11-21 16:02:13 -08002854 }
2855
2856
Mathias Agopian3559b072012-08-15 13:46:03 -07002857 /*
2858 * Perform our own transaction if needed
2859 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002860
2861 if (mLayersAdded) {
2862 mLayersAdded = false;
2863 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002864 mVisibleRegionsDirty = true;
2865 }
2866
2867 // some layers might have been removed, so
2868 // we need to update the regions they're exposing.
2869 if (mLayersRemoved) {
2870 mLayersRemoved = false;
2871 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002872 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002873 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002874 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002875 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002876 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002877 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002878 }
Robert Carr2047fae2016-11-28 14:09:09 -08002879 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880 }
2881
Vishnu Nairec0ab382019-02-13 15:32:56 -08002882 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002884}
2885
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002886void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002887 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002888 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002889 return;
2890 }
2891
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002892 if (mVisibleRegionsDirty || mInputInfoChanged) {
2893 mInputInfoChanged = false;
2894 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002895 } else if (mInputWindowCommands.syncInputWindows) {
2896 // If the caller requested to sync input windows, but there are no
2897 // changes to input windows, notify immediately.
2898 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002899 }
2900
Arthur Hung6cbb9752019-09-05 16:38:18 +08002901 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002902}
2903
2904void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002905 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002906
2907 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2908 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002909 // When calculating the screen bounds we ignore the transparent region since it may
2910 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002911 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002912 }
2913 });
chaviw291d88a2019-02-14 10:33:58 -08002914
2915 mInputFlinger->setInputWindows(inputHandles,
2916 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2917 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002918}
2919
Vishnu Nairec0ab382019-02-13 15:32:56 -08002920void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002921 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002922 mPendingInputWindowCommands.clear();
2923}
2924
Riley Andrews03414a12014-07-01 14:22:59 -07002925void SurfaceFlinger::updateCursorAsync()
2926{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002927 compositionengine::CompositionRefreshArgs refreshArgs;
2928 for (const auto& [_, display] : mDisplays) {
2929 if (display->getId()) {
2930 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002931 }
2932 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002933
2934 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002935}
2936
Ady Abraham2139f732019-11-13 18:56:40 -08002937void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002938 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2939 // If this is called from the main thread mStateLock must be locked before
2940 // Currently the only way to call this function from the main thread is from
2941 // Sheduler::chooseRefreshRateForContent
2942
2943 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002944 changeRefreshRateLocked(refreshRate, event);
2945}
2946
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002947void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2948 if (mScheduler) {
2949 // In practice it's not allowed to hotplug in/out the primary display once it's been
2950 // connected during startup, but some tests do it, so just warn and return.
2951 ALOGW("Can't re-init scheduler");
2952 return;
2953 }
2954
Ady Abraham2139f732019-11-13 18:56:40 -08002955 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002956 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002957 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002958 primaryDisplayId),
2959 currentConfig);
2960 mRefreshRateStats =
2961 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2962 currentConfig, HWC_POWER_MODE_OFF);
2963 mRefreshRateStats->setConfigMode(currentConfig);
2964
Ady Abraham9e16a482019-12-03 17:19:41 -08002965 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2966
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002967 // start the EventThread
2968 mScheduler =
2969 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002970 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002971 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002972 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002973 impl::EventThread::InterceptVSyncsCallback());
2974 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002975 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002976 [this](nsecs_t timestamp) {
2977 mInterceptor->saveVSyncEvent(timestamp);
2978 });
2979
2980 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2981 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002982 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002983
2984 mRegionSamplingThread =
2985 new RegionSamplingThread(*this, *mScheduler,
2986 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002987 // Dispatch a config change request for the primary display on scheduler
2988 // initialization, so that the EventThreads always contain a reference to a
2989 // prior configuration.
2990 //
2991 // This is a bit hacky, but this avoids a back-pointer into the main SF
2992 // classes from EventThread, and there should be no run-time binder cost
2993 // anyway since there are no connected apps at this point.
2994 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002995 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Alec Mouri60aee1c2019-10-28 16:18:59 -07002996 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2997 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002998}
2999
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000void SurfaceFlinger::commitTransaction()
3001{
Vishnu Nair60db8c02020-04-02 11:55:16 -07003002 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003003 mTransactionPending = false;
3004 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003005 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006}
3007
Lloyd Pique58e24a32019-08-01 15:50:14 -07003008void SurfaceFlinger::commitTransactionLocked() {
3009 if (!mLayersPendingRemoval.isEmpty()) {
3010 // Notify removed layers now that they can't be drawn from
3011 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003012 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003013
3014 // Ensure any buffers set to display on any children are released.
3015 if (l->isRemovedFromCurrentState()) {
3016 l->latchAndReleaseBuffer();
3017 }
3018
3019 // If the layer has been removed and has no parent, then it will not be reachable
3020 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3021 // ensure we can copy its current to drawing state.
3022 if (!l->getParent()) {
3023 mOffscreenLayers.emplace(l.get());
3024 }
3025 }
3026 mLayersPendingRemoval.clear();
3027 }
3028
3029 // If this transaction is part of a window animation then the next frame
3030 // we composite should be considered an animation as well.
3031 mAnimCompositionPending = mAnimTransactionPending;
3032
3033 mDrawingState = mCurrentState;
3034 // clear the "changed" flags in current state
3035 mCurrentState.colorMatrixChanged = false;
3036
Edgar Arriaga844fa672020-01-16 14:21:42 -08003037 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003038 layer->commitChildList();
3039
3040 // If the layer can be reached when traversing mDrawingState, then the layer is no
3041 // longer offscreen. Remove the layer from the offscreenLayer set.
3042 if (mOffscreenLayers.count(layer)) {
3043 mOffscreenLayers.erase(layer);
3044 }
3045 });
3046
3047 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003048 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003049}
3050
chaviw74d90ad2019-04-26 14:45:26 -07003051void SurfaceFlinger::commitOffscreenLayers() {
3052 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003053 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003054 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3055 if (!trFlags) return;
3056
3057 layer->doTransaction(0);
3058 layer->commitChildList();
3059 });
3060 }
3061}
3062
Chia-I Wuab0c3192017-08-01 11:29:00 -07003063void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003064 for (const auto& [token, displayDevice] : mDisplays) {
3065 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003066 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003067 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003068 }
3069 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003070}
3071
Dan Stoza6b9454d2014-11-07 16:00:59 -08003072bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073{
Ady Abraham09bd3922019-04-08 10:44:56 -07003074 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003075 ALOGV("handlePageFlip");
3076
Brian Andersond6927fb2016-07-23 23:37:30 -07003077 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078
Mathias Agopian4fec8732012-06-29 14:12:52 -07003079 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003080 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003081 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003082
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003083 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3084
Eric Penner51c59cd2014-07-28 19:51:58 -07003085 // Store the set of layers that need updates. This set must not change as
3086 // buffers are being latched, as this could result in a deadlock.
3087 // Example: Two producers share the same command stream and:
3088 // 1.) Layer 0 is latched
3089 // 2.) Layer 0 gets a new frame
3090 // 2.) Layer 1 gets a new frame
3091 // 3.) Layer 1 is latched.
3092 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3093 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003094 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003095 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003096 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003097 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003098 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003099 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003100 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003101 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003102 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003103 } else {
3104 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003105 }
Robert Carr2047fae2016-11-28 14:09:09 -08003106 });
3107
chaviw49a108c2019-08-12 11:23:06 -07003108 // The client can continue submitting buffers for offscreen layers, but they will not
3109 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3110 // layers to ensure dequeueBuffer doesn't block indefinitely.
3111 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003112 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003113 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3114 }
3115
Lloyd Piquef2c79392018-12-20 16:23:33 -08003116 if (!mLayersWithQueuedFrames.empty()) {
3117 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3118 // writes to Layer current state. See also b/119481871
3119 Mutex::Autolock lock(mStateLock);
3120
3121 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003122 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003123 mLayersPendingRefresh.push_back(layer);
3124 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003125 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003126 if (layer->isBufferLatched()) {
3127 newDataLatched = true;
3128 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003129 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003130 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003131
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003132 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003133
3134 // If we will need to wake up at some time in the future to deal with a
3135 // queued frame that shouldn't be displayed during this vsync period, wake
3136 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003137 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003138 signalLayerUpdate();
3139 }
3140
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003141 // enter boot animation on first buffer latch
3142 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3143 ALOGI("Enter boot animation");
3144 mBootStage = BootStage::BOOTANIMATION;
3145 }
3146
Edgar Arriaga844fa672020-01-16 14:21:42 -08003147 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003148
Dan Stoza6b9454d2014-11-07 16:00:59 -08003149 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003150 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151}
3152
Mathias Agopianad456f92011-01-13 17:53:01 -08003153void SurfaceFlinger::invalidateHwcGeometry()
3154{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003155 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003156}
3157
Robert Carrc0df3122019-04-11 13:18:21 -07003158status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3159 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3160 const sp<IBinder>& parentHandle,
3161 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003162 // add this layer to the current state list
3163 {
3164 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003165 sp<Layer> parent;
3166 if (parentHandle != nullptr) {
3167 parent = fromHandle(parentHandle);
3168 if (parent == nullptr) {
3169 return NAME_NOT_FOUND;
3170 }
3171 } else {
3172 parent = parentLayer;
3173 }
3174
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003175 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003176 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003177 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003178 return NO_MEMORY;
3179 }
Robert Carrc0df3122019-04-11 13:18:21 -07003180
3181 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3182
Robert Carrb89ea9d2018-12-10 13:01:14 -08003183 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003184 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003185 } else if (parent == nullptr) {
3186 lbc->onRemovedFromCurrentState();
3187 } else if (parent->isRemovedFromCurrentState()) {
3188 parent->addChild(lbc);
3189 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003190 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003191 parent->addChild(lbc);
3192 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003193
Yiwei Zhang243b3782018-05-15 17:40:04 -07003194 if (gbc != nullptr) {
3195 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3196 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3197 mMaxGraphicBufferProducerListSize,
3198 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3199 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003200 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003201 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3202 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3203 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3204 mNumLayers.load());
3205 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003206 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003207 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003208 }
3209
Mathias Agopian96f08192010-06-02 23:28:45 -07003210 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003211 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003212
Dan Stoza7d89d062015-04-30 13:29:25 -07003213 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003214}
3215
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003216uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003217 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003218}
3219
Mathias Agopian3f844832013-08-07 21:24:32 -07003220uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003221 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222}
3223
Mathias Agopian3f844832013-08-07 21:24:32 -07003224uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003225 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003226}
3227
3228uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003229 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003230 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003231 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003233 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234 }
3235 return old;
3236}
3237
Marissa Wall713b63f2018-10-17 15:42:43 -07003238bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003239 // to prevent onHandleDestroyed from being called while the lock is held,
3240 // we must keep a copy of the transactions (specifically the composer
3241 // states) around outside the scope of the lock
3242 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003243 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003244 {
3245 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003246
Valerie Haufce31b82019-04-30 16:41:14 -07003247 auto it = mTransactionQueues.begin();
3248 while (it != mTransactionQueues.end()) {
3249 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003250
Valerie Haufce31b82019-04-30 16:41:14 -07003251 while (!transactionQueue.empty()) {
3252 const auto& transaction = transactionQueue.front();
3253 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003254 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003255 transaction.states)) {
3256 setTransactionFlags(eTransactionFlushNeeded);
3257 break;
3258 }
3259 transactions.push_back(transaction);
3260 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3261 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003262 transaction.buffer, transaction.postTime,
3263 transaction.privileged, transaction.hasListenerCallbacks,
3264 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003265 transactionQueue.pop();
3266 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003267 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003268
Valerie Haufce31b82019-04-30 16:41:14 -07003269 if (transactionQueue.empty()) {
3270 it = mTransactionQueues.erase(it);
3271 mTransactionCV.broadcast();
3272 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003273 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003274 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003275 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003276 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003277 return flushedATransaction;
3278}
3279
3280bool SurfaceFlinger::transactionFlushNeeded() {
3281 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003282}
3283
chaviwca27f252018-02-06 16:46:39 -08003284
Marissa Wall17b4e452018-12-26 16:32:34 -08003285bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003286 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003287 const Vector<ComposerState>& states) {
Ady Abraham0ed31c92020-04-16 11:48:45 -07003288 if (!useCachedExpectedPresentTime) populateExpectedPresentTime(systemTime());
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003289
3290 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003291 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3292 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3293 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3294 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3295 return false;
3296 }
3297
Marissa Wall713b63f2018-10-17 15:42:43 -07003298 for (const ComposerState& state : states) {
3299 const layer_state_t& s = state.state;
3300 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3301 continue;
3302 }
3303 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003304 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003305 }
3306 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003307 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003308}
3309
Valerie Hau9dab9732019-08-20 09:29:25 -07003310void SurfaceFlinger::setTransactionState(
3311 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3312 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3313 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3314 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003315 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003316
Valerie Haubc6ddb12019-03-08 11:10:15 -08003317 const int64_t postTime = systemTime();
3318
Robert Carr14167e02019-02-13 13:50:55 -08003319 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3320
Mathias Agopian698c0872011-06-28 19:09:31 -07003321 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003322
Marissa Wall713b63f2018-10-17 15:42:43 -07003323 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003324 auto itr = mTransactionQueues.find(applyToken);
3325 // if this is an animation frame, wait until prior animation frame has
3326 // been applied by SF
3327 if (flags & eAnimation) {
3328 while (itr != mTransactionQueues.end()) {
3329 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3330 if (CC_UNLIKELY(err != NO_ERROR)) {
3331 ALOGW_IF(err == TIMED_OUT,
3332 "setTransactionState timed out "
3333 "waiting for animation frame to apply");
3334 break;
3335 }
3336 itr = mTransactionQueues.find(applyToken);
3337 }
3338 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003339
3340 // Expected present time is computed and cached on invalidate, so it may be stale.
3341 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3342 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003343 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003344 uncacheBuffer, postTime, privileged,
3345 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003346 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003347 return;
3348 }
3349
Valerie Haubc6ddb12019-03-08 11:10:15 -08003350 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003351 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3352 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003353}
3354
Valerie Hau9dab9732019-08-20 09:29:25 -07003355void SurfaceFlinger::applyTransactionState(
3356 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3357 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3358 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3359 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3360 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003361 uint32_t transactionFlags = 0;
3362
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003363 if (flags & eAnimation) {
3364 // For window updates that are part of an animation we must wait for
3365 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003366 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003367 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003368 if (CC_UNLIKELY(err != NO_ERROR)) {
3369 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003370 // caller after a few seconds.
3371 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3372 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003373 mAnimTransactionPending = false;
3374 break;
3375 }
3376 }
3377 }
3378
chaviwca27f252018-02-06 16:46:39 -08003379 for (const DisplayState& display : displays) {
3380 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003381 }
3382
Valerie Hau9dab9732019-08-20 09:29:25 -07003383 // start and end registration for listeners w/ no surface so they can get their callback. Note
3384 // that listeners with SurfaceControls will start registration during setClientStateLocked
3385 // below.
3386 for (const auto& listener : listenerCallbacks) {
3387 mTransactionCompletedThread.startRegistration(listener);
3388 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003389 }
3390
Valerie Hau9dab9732019-08-20 09:29:25 -07003391 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003392 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003393 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003394 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3395 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003396 }
3397
Valerie Hau9dab9732019-08-20 09:29:25 -07003398 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003399 mTransactionCompletedThread.endRegistration(listenerCallback);
3400 }
3401
Marissa Walle2ffb422018-10-12 11:33:52 -07003402 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003403 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003404 mTransactionCompletedThread.sendCallbacks();
3405 }
3406 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003407
chaviw273171b2018-12-26 11:46:30 -08003408 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3409
Marissa Wall947d34e2019-03-29 14:03:53 -07003410 if (uncacheBuffer.isValid()) {
3411 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003412 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003413 }
3414
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003415 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3416 // anyway. This can be used as a flush mechanism for previous async transactions.
3417 // Empty animation transaction can be used to simulate back-pressure, so also force a
3418 // transaction for empty animation transactions.
3419 if (transactionFlags == 0 &&
3420 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003421 transactionFlags = eTransactionNeeded;
3422 }
3423
Marissa Wall06255332019-03-27 13:48:27 -07003424 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3425 // so we don't have to wake up again next frame to preform an uneeded traversal.
3426 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3427 transactionFlags = transactionFlags & (~eTraversalNeeded);
3428 mTraversalNeededMainThread = true;
3429 }
3430
Mathias Agopian386aa982011-11-07 21:58:03 -08003431 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003432 if (mInterceptor->isEnabled()) {
3433 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003434 }
Irvel468051e2016-06-13 16:44:44 -07003435
Mathias Agopian386aa982011-11-07 21:58:03 -08003436 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003437 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3438 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003439 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003440
3441 // if this is a synchronous transaction, wait for it to take effect
3442 // before returning.
3443 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003444 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003445 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003446 if (flags & eAnimation) {
3447 mAnimTransactionPending = true;
3448 }
chaviw4fe36852019-04-15 16:25:49 -07003449 if (mPendingInputWindowCommands.syncInputWindows) {
3450 mPendingSyncInputWindows = true;
3451 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003452
3453 // applyTransactionState can be called by either the main SF thread or by
3454 // another process through setTransactionState. While a given process may wish
3455 // to wait on synchronous transactions, the main SF thread should never
3456 // be blocked. Therefore, we only wait if isMainThread is false.
3457 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003458 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3459 if (CC_UNLIKELY(err != NO_ERROR)) {
3460 // just in case something goes wrong in SF, return to the
3461 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003462 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3463 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003464 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003465 break;
3466 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003467 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003468 }
3469}
3470
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003471uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3472 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3473 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003474
Mathias Agopiane57f2922012-08-09 16:29:12 -07003475 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003476 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3477
3478 const uint32_t what = s.what;
3479 if (what & DisplayState::eSurfaceChanged) {
3480 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3481 state.surface = s.surface;
3482 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003483 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003484 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003485 if (what & DisplayState::eLayerStackChanged) {
3486 if (state.layerStack != s.layerStack) {
3487 state.layerStack = s.layerStack;
3488 flags |= eDisplayTransactionNeeded;
3489 }
3490 }
3491 if (what & DisplayState::eDisplayProjectionChanged) {
3492 if (state.orientation != s.orientation) {
3493 state.orientation = s.orientation;
3494 flags |= eDisplayTransactionNeeded;
3495 }
3496 if (state.frame != s.frame) {
3497 state.frame = s.frame;
3498 flags |= eDisplayTransactionNeeded;
3499 }
3500 if (state.viewport != s.viewport) {
3501 state.viewport = s.viewport;
3502 flags |= eDisplayTransactionNeeded;
3503 }
3504 }
3505 if (what & DisplayState::eDisplaySizeChanged) {
3506 if (state.width != s.width) {
3507 state.width = s.width;
3508 flags |= eDisplayTransactionNeeded;
3509 }
3510 if (state.height != s.height) {
3511 state.height = s.height;
3512 flags |= eDisplayTransactionNeeded;
3513 }
3514 }
3515
Mathias Agopiane57f2922012-08-09 16:29:12 -07003516 return flags;
3517}
3518
Steven Thomasd4071902020-03-24 16:02:53 -07003519bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003520 IPCThreadState* ipc = IPCThreadState::self();
3521 const int pid = ipc->getCallingPid();
3522 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003523 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003524 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3525 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003526 return false;
3527 }
3528 return true;
3529}
3530
Marissa Wall3dad52d2019-03-22 14:03:19 -07003531uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003532 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3533 bool privileged,
3534 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003535 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003536
Valerie Hau9dab9732019-08-20 09:29:25 -07003537 for (auto& listener : s.listeners) {
3538 // note that startRegistration will not re-register if the listener has
3539 // already be registered for a prior surface control
3540 mTransactionCompletedThread.startRegistration(listener);
3541 listenerCallbacks.insert(listener);
3542 }
3543
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003544 sp<Layer> layer = nullptr;
3545 if (s.surface) {
3546 layer = fromHandle(s.surface);
3547 } else {
3548 // The client may provide us a null handle. Treat it as if the layer was removed.
3549 ALOGW("Attempt to set client state with a null layer handle");
3550 }
chaviw8b3871a2017-11-01 17:41:01 -07003551 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003552 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003553 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003554 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003555 }
chaviw8b3871a2017-11-01 17:41:01 -07003556 return 0;
3557 }
3558
chaviw8b3871a2017-11-01 17:41:01 -07003559 uint32_t flags = 0;
3560
Garfield Tan8a3083e2018-12-03 13:21:07 -08003561 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003562
3563 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3564 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003565 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003566 layer->pushPendingState();
3567 }
3568
Valerie Hau871d6352020-01-29 08:44:02 -08003569 // Only set by BLAST adapter layers
3570 if (what & layer_state_t::eProducerDisconnect) {
3571 layer->onDisconnect();
3572 }
3573
chaviw8b3871a2017-11-01 17:41:01 -07003574 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003575 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003576 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003577 }
chaviw8b3871a2017-11-01 17:41:01 -07003578 }
3579 if (what & layer_state_t::eLayerChanged) {
3580 // NOTE: index needs to be calculated before we update the state
3581 const auto& p = layer->getParent();
3582 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003583 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003584 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003585 mCurrentState.layersSortedByZ.removeAt(idx);
3586 mCurrentState.layersSortedByZ.add(layer);
3587 // we need traversal (state changed)
3588 // AND transaction (list changed)
3589 flags |= eTransactionNeeded|eTraversalNeeded;
3590 }
chaviw8b3871a2017-11-01 17:41:01 -07003591 } else {
3592 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003593 flags |= eTransactionNeeded|eTraversalNeeded;
3594 }
3595 }
chaviw8b3871a2017-11-01 17:41:01 -07003596 }
3597 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003598 // NOTE: index needs to be calculated before we update the state
3599 const auto& p = layer->getParent();
3600 if (p == nullptr) {
3601 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3602 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3603 mCurrentState.layersSortedByZ.removeAt(idx);
3604 mCurrentState.layersSortedByZ.add(layer);
3605 // we need traversal (state changed)
3606 // AND transaction (list changed)
3607 flags |= eTransactionNeeded|eTraversalNeeded;
3608 }
3609 } else {
3610 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3611 flags |= eTransactionNeeded|eTraversalNeeded;
3612 }
chaviw8b3871a2017-11-01 17:41:01 -07003613 }
3614 }
3615 if (what & layer_state_t::eSizeChanged) {
3616 if (layer->setSize(s.w, s.h)) {
3617 flags |= eTraversalNeeded;
3618 }
3619 }
3620 if (what & layer_state_t::eAlphaChanged) {
3621 if (layer->setAlpha(s.alpha))
3622 flags |= eTraversalNeeded;
3623 }
3624 if (what & layer_state_t::eColorChanged) {
3625 if (layer->setColor(s.color))
3626 flags |= eTraversalNeeded;
3627 }
Peiyong Lind3788632018-09-18 16:01:31 -07003628 if (what & layer_state_t::eColorTransformChanged) {
3629 if (layer->setColorTransform(s.colorTransform)) {
3630 flags |= eTraversalNeeded;
3631 }
3632 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003633 if (what & layer_state_t::eBackgroundColorChanged) {
3634 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3635 flags |= eTraversalNeeded;
3636 }
3637 }
chaviw8b3871a2017-11-01 17:41:01 -07003638 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003639 // TODO: b/109894387
3640 //
3641 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3642 // rotation. To see the problem observe that if we have a square parent, and a child
3643 // of the same size, then we rotate the child 45 degrees around it's center, the child
3644 // must now be cropped to a non rectangular 8 sided region.
3645 //
3646 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3647 // private API, and the WindowManager only uses rotation in one case, which is on a top
3648 // level layer in which cropping is not an issue.
3649 //
3650 // However given that abuse of rotation matrices could lead to surfaces extending outside
3651 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3652 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3653 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003654 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003655 flags |= eTraversalNeeded;
3656 }
3657 if (what & layer_state_t::eTransparentRegionChanged) {
3658 if (layer->setTransparentRegionHint(s.transparentRegion))
3659 flags |= eTraversalNeeded;
3660 }
3661 if (what & layer_state_t::eFlagsChanged) {
3662 if (layer->setFlags(s.flags, s.mask))
3663 flags |= eTraversalNeeded;
3664 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003665 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003666 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003667 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003668 if (what & layer_state_t::eCornerRadiusChanged) {
3669 if (layer->setCornerRadius(s.cornerRadius))
3670 flags |= eTraversalNeeded;
3671 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003672 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003673 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3674 }
chaviw8b3871a2017-11-01 17:41:01 -07003675 if (what & layer_state_t::eLayerStackChanged) {
3676 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3677 // We only allow setting layer stacks for top level layers,
3678 // everything else inherits layer stack from its parent.
3679 if (layer->hasParent()) {
3680 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003681 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003682 } else if (idx < 0) {
3683 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003684 "that also does not appear in the top level layer list. Something"
3685 " has gone wrong.",
3686 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003687 } else if (layer->setLayerStack(s.layerStack)) {
3688 mCurrentState.layersSortedByZ.removeAt(idx);
3689 mCurrentState.layersSortedByZ.add(layer);
3690 // we need traversal (state changed)
3691 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003692 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003693 }
3694 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003695 if (what & layer_state_t::eDeferTransaction_legacy) {
3696 if (s.barrierHandle_legacy != nullptr) {
3697 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3698 } else if (s.barrierGbp_legacy != nullptr) {
3699 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003700 if (authenticateSurfaceTextureLocked(gbp)) {
3701 const auto& otherLayer =
3702 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003703 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003704 } else {
3705 ALOGE("Attempt to defer transaction to to an"
3706 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003707 }
3708 }
chaviw8b3871a2017-11-01 17:41:01 -07003709 // We don't trigger a traversal here because if no other state is
3710 // changed, we don't want this to cause any more work
3711 }
chaviw8b3871a2017-11-01 17:41:01 -07003712 if (what & layer_state_t::eReparentChildren) {
3713 if (layer->reparentChildren(s.reparentHandle)) {
3714 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003715 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003716 }
chaviw8b3871a2017-11-01 17:41:01 -07003717 if (what & layer_state_t::eDetachChildren) {
3718 layer->detachChildren();
3719 }
3720 if (what & layer_state_t::eOverrideScalingModeChanged) {
3721 layer->setOverrideScalingMode(s.overrideScalingMode);
3722 // We don't trigger a traversal here because if no other state is
3723 // changed, we don't want this to cause any more work
3724 }
Marissa Wall61c58622018-07-18 10:12:20 -07003725 if (what & layer_state_t::eTransformChanged) {
3726 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3727 }
3728 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3729 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3730 flags |= eTraversalNeeded;
3731 }
3732 if (what & layer_state_t::eCropChanged) {
3733 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3734 }
Marissa Wall861616d2018-10-22 12:52:23 -07003735 if (what & layer_state_t::eFrameChanged) {
3736 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3737 }
Marissa Wall61c58622018-07-18 10:12:20 -07003738 if (what & layer_state_t::eAcquireFenceChanged) {
3739 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3740 }
3741 if (what & layer_state_t::eDataspaceChanged) {
3742 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3743 }
3744 if (what & layer_state_t::eHdrMetadataChanged) {
3745 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3746 }
3747 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3748 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3749 }
3750 if (what & layer_state_t::eApiChanged) {
3751 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3752 }
3753 if (what & layer_state_t::eSidebandStreamChanged) {
3754 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3755 }
Robert Carr720e5062018-07-30 17:45:14 -07003756 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003757 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003758 layer->setInputInfo(s.inputInfo);
3759 flags |= eTraversalNeeded;
3760 } else {
3761 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3762 }
Robert Carr720e5062018-07-30 17:45:14 -07003763 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003764 if (what & layer_state_t::eMetadataChanged) {
3765 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3766 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003767 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3768 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3769 flags |= eTraversalNeeded;
3770 }
3771 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003772 if (what & layer_state_t::eShadowRadiusChanged) {
3773 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3774 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003775 if (what & layer_state_t::eFrameRateSelectionPriority) {
3776 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3777 flags |= eTraversalNeeded;
3778 }
3779 }
Steven Thomas3172e202020-01-06 19:25:30 -08003780 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003781 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3782 "SurfaceFlinger::setClientStateLocked") &&
3783 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3784 Layer::FrameRate::convertCompatibility(
3785 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003786 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003787 }
Steven Thomas3172e202020-01-06 19:25:30 -08003788 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003789 // This has to happen after we reparent children because when we reparent to null we remove
3790 // child layers from current state and remove its relative z. If the children are reparented in
3791 // the same transaction, then we have to make sure we reparent the children first so we do not
3792 // lose its relative z order.
3793 if (what & layer_state_t::eReparent) {
3794 bool hadParent = layer->hasParent();
3795 if (layer->reparent(s.parentHandleForChild)) {
3796 if (!hadParent) {
3797 mCurrentState.layersSortedByZ.remove(layer);
3798 }
3799 flags |= eTransactionNeeded | eTraversalNeeded;
3800 }
3801 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003802 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003803 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3804 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003805 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3806 }
3807 }
Marissa Wall78b72202019-03-15 14:58:34 -07003808 bool bufferChanged = what & layer_state_t::eBufferChanged;
3809 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3810 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003811 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003812 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003813 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3814 if (success) {
3815 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3816 success = ClientCache::getInstance()
3817 .registerErasedRecipient(s.cachedBuffer,
3818 wp<ClientCache::ErasedRecipient>(this));
3819 if (!success) {
3820 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3821 }
3822 }
Marissa Wall78b72202019-03-15 14:58:34 -07003823 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003824 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003825 } else if (bufferChanged) {
3826 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003827 }
Marissa Wall78b72202019-03-15 14:58:34 -07003828 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003829 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3830 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003831 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003832 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003833 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003834 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3835 // Do not put anything that updates layer state or modifies flags after
3836 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003837 return flags;
3838}
3839
chaviw273171b2018-12-26 11:46:30 -08003840uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3841 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003842 if (inputWindowCommands.syncInputWindows) {
3843 flags |= eTraversalNeeded;
3844 }
3845
Vishnu Nairec0ab382019-02-13 15:32:56 -08003846 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003847 return flags;
3848}
3849
chaviwfe94a222019-08-21 13:52:59 -07003850status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3851 sp<IBinder>* outHandle) {
3852 if (!mirrorFromHandle) {
3853 return NAME_NOT_FOUND;
3854 }
3855
3856 sp<Layer> mirrorLayer;
3857 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003858 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003859
3860 {
3861 Mutex::Autolock _l(mStateLock);
3862 mirrorFrom = fromHandle(mirrorFromHandle);
3863 if (!mirrorFrom) {
3864 return NAME_NOT_FOUND;
3865 }
3866
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003867 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3868 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003869 if (result != NO_ERROR) {
3870 return result;
3871 }
3872
3873 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3874 }
3875
3876 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3877}
3878
Marissa Wall2d814fb2019-04-09 18:52:57 +00003879status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3880 uint32_t h, PixelFormat format, uint32_t flags,
3881 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003882 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003883 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3884 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003885 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003886 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003887 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003888 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003889 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003890
Robert Carrc0df3122019-04-11 13:18:21 -07003891 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3892 "Expected only one of parentLayer or parentHandle to be non-null. "
3893 "Programmer error?");
3894
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003895 status_t result = NO_ERROR;
3896
3897 sp<Layer> layer;
3898
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003899 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003900
Evan Roskya1f1e152019-01-24 16:17:46 -08003901 bool primaryDisplayOnly = false;
3902
3903 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3904 // TODO b/64227542
3905 if (metadata.has(METADATA_WINDOW_TYPE)) {
3906 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3907 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003908 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003909 primaryDisplayOnly = true;
3910 }
3911 }
3912
Mathias Agopian3165cc22012-08-08 19:42:09 -07003913 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003914 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003915 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3916 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003917
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003919 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003920 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003921 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003922 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003923 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003924 // check if buffer size is set for color layer.
3925 if (w > 0 || h > 0) {
3926 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3927 int(w), int(h));
3928 return BAD_VALUE;
3929 }
3930
Vishnu Nairfa247b12020-02-11 08:58:26 -08003931 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3932 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003933 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003934 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003935 // check if buffer size is set for container layer.
3936 if (w > 0 || h > 0) {
3937 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3938 int(w), int(h));
3939 return BAD_VALUE;
3940 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003941 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3942 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003943 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003944 default:
3945 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003946 break;
3947 }
3948
Dan Stoza7d89d062015-04-30 13:29:25 -07003949 if (result != NO_ERROR) {
3950 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003951 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003952
Evan Roskya1f1e152019-01-24 16:17:46 -08003953 if (primaryDisplayOnly) {
3954 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003955 }
3956
Robert Carrb89ea9d2018-12-10 13:01:14 -08003957 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003958 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3959 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003960 if (result != NO_ERROR) {
3961 return result;
3962 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003963 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003964
3965 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003966 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003967}
3968
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003969std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3970 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003971
3972 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003973 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003974
Dan Stoza436ccf32018-06-21 12:10:12 -07003975 // Grab the state lock since we're accessing mCurrentState
3976 Mutex::Autolock lock(mStateLock);
3977
Cody Northropbc755282017-03-31 12:00:08 -06003978 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003979 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003980 while (matchFound) {
3981 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003982 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003983 if (layer->getName() == uniqueName) {
3984 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003985 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003986 }
3987 });
3988 }
3989
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003990 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003991 return uniqueName;
3992}
3993
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003994status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003995 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003996 LayerMetadata metadata, PixelFormat& format,
3997 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003998 sp<IGraphicBufferProducer>* gbp,
3999 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004000 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004001 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004002 case PIXEL_FORMAT_TRANSPARENT:
4003 case PIXEL_FORMAT_TRANSLUCENT:
4004 format = PIXEL_FORMAT_RGBA_8888;
4005 break;
4006 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004007 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004008 break;
4009 }
4010
chaviwb4c6e582019-08-16 14:35:07 -07004011 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004012 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004013 args.textureName = getNewTexture();
4014 {
4015 // Grab the SF state lock during this since it's the only safe way to access
4016 // RenderEngine when creating a BufferLayerConsumer
4017 // TODO: Check if this lock is still needed here
4018 Mutex::Autolock lock(mStateLock);
4019 layer = getFactory().createBufferQueueLayer(args);
4020 }
4021
Marissa Wallfd668622018-05-10 10:21:13 -07004022 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004023 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004024 *handle = layer->getHandle();
4025 *gbp = layer->getProducer();
4026 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004027 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004028
Marissa Wallfd668622018-05-10 10:21:13 -07004029 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004030 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004031}
4032
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004033status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004034 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004035 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004036 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004037 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004038 args.displayDevice = getDefaultDisplayDevice();
4039 args.textureName = getNewTexture();
4040 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004041 if (outTransformHint) {
4042 *outTransformHint = layer->getTransformHint();
4043 }
Marissa Wall61c58622018-07-18 10:12:20 -07004044 *handle = layer->getHandle();
4045 *outLayer = layer;
4046
4047 return NO_ERROR;
4048}
4049
Vishnu Nairfa247b12020-02-11 08:58:26 -08004050status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4051 uint32_t h, uint32_t flags, LayerMetadata metadata,
4052 sp<IBinder>* handle, sp<Layer>* outLayer) {
4053 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004054 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004055 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004056 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004057}
4058
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004059status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004060 uint32_t w, uint32_t h, uint32_t flags,
4061 LayerMetadata metadata, sp<IBinder>* handle,
4062 sp<Layer>* outLayer) {
4063 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004064 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004065 *handle = (*outLayer)->getHandle();
4066 return NO_ERROR;
4067}
4068
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004069void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004070 mLayersPendingRemoval.add(layer);
4071 mLayersRemoved = true;
4072 setTransactionFlags(eTransactionNeeded);
4073}
4074
Robert Carr695d5282018-12-18 15:27:58 -08004075void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004076{
Robert Carr2e102c92018-10-23 12:11:15 -07004077 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004078 // If a layer has a parent, we allow it to out-live it's handle
4079 // with the idea that the parent holds a reference and will eventually
4080 // be cleaned up. However no one cleans up the top-level so we do so
4081 // here.
4082 if (layer->getParent() == nullptr) {
4083 mCurrentState.layersSortedByZ.remove(layer);
4084 }
4085 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004086
4087 auto it = mLayersByLocalBinderToken.begin();
4088 while (it != mLayersByLocalBinderToken.end()) {
4089 if (it->second == layer) {
4090 it = mLayersByLocalBinderToken.erase(it);
4091 } else {
4092 it++;
4093 }
4094 }
4095
Robert Carr695d5282018-12-18 15:27:58 -08004096 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004097}
4098
Mathias Agopianb60314a2012-04-10 22:09:54 -07004099// ---------------------------------------------------------------------------
4100
Andy McFadden13a082e2012-08-24 10:16:42 -07004101void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004102 const auto display = getDefaultDisplayDeviceLocked();
4103 if (!display) return;
4104
4105 const sp<IBinder> token = display->getDisplayToken().promote();
4106 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004107
Jesse Hall01e29052013-02-19 16:13:35 -08004108 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004109 Vector<ComposerState> state;
4110 Vector<DisplayState> displays;
4111 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004112 d.what = DisplayState::eDisplayProjectionChanged |
4113 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004114 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004115 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004116 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004117 d.frame.makeInvalid();
4118 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004119 d.width = 0;
4120 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004121 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004122 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4123 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004124
Dominik Laskowskie9774092018-12-11 10:04:24 -08004125 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004126
Dominik Laskowski83b88212018-12-11 13:34:06 -08004127 const nsecs_t vsyncPeriod = getVsyncPeriod();
4128 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004129
Brian Andersond0010582017-03-07 13:20:31 -08004130 // Use phase of 0 since phase is not known.
4131 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004132 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004133 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004134}
4135
4136void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004137 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004138 postMessageAsync(
4139 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004140}
4141
Peiyong Line9d809e2020-04-14 13:10:48 -07004142void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, hal::Vsync enabled) {
Ady Abraham27c70212019-06-11 10:52:26 -07004143 if (mHWCVsyncState != enabled) {
4144 getHwComposer().setVsyncEnabled(displayId, enabled);
4145 mHWCVsyncState = enabled;
4146 }
4147}
4148
Dominik Laskowskie9774092018-12-11 10:04:24 -08004149void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004150 if (display->isVirtual()) {
4151 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004152 return;
4153 }
4154
Dominik Laskowski075d3172018-05-24 15:50:06 -07004155 const auto displayId = display->getId();
4156 LOG_ALWAYS_FATAL_IF(!displayId);
4157
Dominik Laskowski34157762018-10-31 13:07:19 -07004158 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004159
4160 int currentMode = display->getPowerMode();
4161 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004162 return;
4163 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004164
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004165 display->setPowerMode(mode);
4166
Lloyd Pique4dccc412018-01-22 17:21:36 -08004167 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004168 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004169 }
4170
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004171 if (currentMode == HWC_POWER_MODE_OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004172 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4173 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4174 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004175 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004176 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004177 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004178 mScheduler->onScreenAcquired(mAppConnectionHandle);
4179 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004180 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004181
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004182 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004183 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004184 repaintEverything();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004185 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004186 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004187 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4188 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004189 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004190 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004191 mScheduler->disableHardwareVsync(true);
4192 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004193 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004194
Ady Abraham27c70212019-06-11 10:52:26 -07004195 // Make sure HWVsync is disabled before turning off the display
Peiyong Line9d809e2020-04-14 13:10:48 -07004196 setVsyncEnabledInHWC(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004197
Dominik Laskowski075d3172018-05-24 15:50:06 -07004198 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004199 mVisibleRegionsDirty = true;
4200 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004201 } else if (mode == HWC_POWER_MODE_DOZE ||
4202 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004203 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004204 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004205 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004206 mScheduler->onScreenAcquired(mAppConnectionHandle);
4207 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004208 }
4209 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4210 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004211 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004212 mScheduler->disableHardwareVsync(true);
4213 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004214 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004215 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004216 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004217 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004218 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004219 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004220
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004221 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004222 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004223 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004224 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004225 }
4226
Dominik Laskowski34157762018-10-31 13:07:19 -07004227 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004228}
4229
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004230void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004231 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004232 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004233 if (!display) {
4234 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4235 displayToken.get());
4236 } else if (display->isVirtual()) {
4237 ALOGW("Attempt to set power mode %d for virtual display", mode);
4238 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004239 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004240 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004241 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004242}
4243
4244// ---------------------------------------------------------------------------
4245
Dominik Laskowskic2867142019-01-21 11:33:38 -08004246status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4247 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004248 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004249
Mathias Agopianbd115332013-04-18 16:41:04 -07004250 IPCThreadState* ipc = IPCThreadState::self();
4251 const int pid = ipc->getCallingPid();
4252 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004253
Mathias Agopianbd115332013-04-18 16:41:04 -07004254 if ((uid != AID_SHELL) &&
4255 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004256 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4257 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004258 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004259 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004260 // (this would indicate SF is stuck, but we want to be able to
4261 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004262 status_t err = mStateLock.timedLock(s2ns(1));
4263 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004264 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004265 StringAppendF(&result,
4266 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4267 "(no locks held)\n",
4268 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004269 }
4270
Dominik Laskowskic2867142019-01-21 11:33:38 -08004271 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004272 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004273 {"--dispsync"s,
4274 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004275 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004276 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4277 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4278 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4279 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4280 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4281 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004282 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004283 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4284 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004285
Dominik Laskowskic2867142019-01-21 11:33:38 -08004286 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004287
Dominik Laskowski46470112019-08-02 13:13:11 -07004288 const auto it = dumpers.find(flag);
4289 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004290 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004291 } else if (!asProto) {
4292 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004293 }
4294
Mathias Agopian9795c422009-08-26 16:36:26 -07004295 if (locked) {
4296 mStateLock.unlock();
4297 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004298
Dominik Laskowski46470112019-08-02 13:13:11 -07004299 if (it == dumpers.end()) {
4300 const LayersProto layersProto = dumpProtoFromMainThread();
4301 if (asProto) {
4302 result.append(layersProto.SerializeAsString());
4303 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004304 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004305 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4306 result.append(LayerProtoParser::layerTreeToString(layerTree));
4307 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004308 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004309 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004310 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004311 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004312 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004313 return NO_ERROR;
4314}
4315
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004316status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4317 if (asProto && mTracing.isEnabled()) {
4318 mTracing.writeToFileAsync();
4319 }
4320
4321 return doDump(fd, DumpArgs(), asProto);
4322}
4323
Dominik Laskowskic2867142019-01-21 11:33:38 -08004324void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004325 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004326 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004327}
4328
Dominik Laskowskic2867142019-01-21 11:33:38 -08004329void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004330 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004331
Dominik Laskowskic2867142019-01-21 11:33:38 -08004332 if (args.size() > 1) {
4333 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004334 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004335 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004336 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004337 }
Robert Carr2047fae2016-11-28 14:09:09 -08004338 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004339 } else {
4340 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004341 }
4342}
4343
Dominik Laskowskic2867142019-01-21 11:33:38 -08004344void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004345 const bool clearAll = args.size() < 2;
4346 const auto name = clearAll ? String8() : String8(args[1]);
4347
Edgar Arriaga844fa672020-01-16 14:21:42 -08004348 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004349 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004350 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004351 }
Robert Carr2047fae2016-11-28 14:09:09 -08004352 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004353
Svetoslavd85084b2014-03-20 10:28:31 -07004354 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004355}
4356
Dominik Laskowskic2867142019-01-21 11:33:38 -08004357void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4358 mTimeStats->parseArgs(asProto, args, result);
4359}
4360
Jamie Gennis6547ff42013-07-16 20:12:42 -07004361// This should only be called from the main thread. Otherwise it would need
4362// the lock and should use mCurrentState rather than mDrawingState.
4363void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004364 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004365 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004366 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004367
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004368 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004369}
4370
Yiwei Zhang5434a782018-12-05 18:06:32 -08004371void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004372 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004373
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004374 if (isLayerTripleBufferingDisabled())
4375 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004376
Yiwei Zhang5434a782018-12-05 18:06:32 -08004377 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4378 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4379 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4380 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4381 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4382 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004383 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004384}
4385
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004386void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004387 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004388
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004389 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004390 result.append("\n");
4391
Ady Abraham9e16a482019-12-03 17:19:41 -08004392 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004393 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004394 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004395 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004396
Steven Thomasd4071902020-03-24 16:02:53 -07004397 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004398 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004399 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004400 ", min: %.2f Hz, max: %.2f Hz",
Steven Thomasd4071902020-03-24 16:02:53 -07004401 policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004402 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4403 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004404 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4405 if (currentPolicy != policy) {
4406 StringAppendF(&result,
4407 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
4408 ", min: %.2f Hz, max: %.2f Hz\n\n",
4409 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
4410 currentPolicy.maxRefreshRate);
4411 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004412
Ana Krulecc2870422019-01-29 19:00:58 -08004413 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004414 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004415}
4416
Yiwei Zhang5434a782018-12-05 18:06:32 -08004417void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4418 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004419 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4420 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004421 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004422 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004423 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004424 }
David Sodman4a36e932017-11-07 14:29:47 -08004425 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004426 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004427 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004428 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4429 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004430}
4431
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004432void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4433 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004434 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4435 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004436 for (const auto& segment : history) {
4437 if (!segment.usedThirdBuffer) {
4438 stats.twoBufferTime += segment.totalTime;
4439 }
4440 if (segment.occupancyAverage < 1.0f) {
4441 stats.doubleBufferedTime += segment.totalTime;
4442 } else if (segment.occupancyAverage < 2.0f) {
4443 stats.tripleBufferedTime += segment.totalTime;
4444 }
4445 ++stats.numSegments;
4446 stats.totalTime += segment.totalTime;
4447 }
4448}
4449
Yiwei Zhang5434a782018-12-05 18:06:32 -08004450void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4451 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004452
4453 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4454 const size_t count = currentLayers.size();
4455 for (size_t i=0 ; i<count ; i++) {
4456 currentLayers[i]->dumpFrameEvents(result);
4457 }
4458}
4459
Yiwei Zhang5434a782018-12-05 18:06:32 -08004460void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004461 result.append("Buffering stats:\n");
4462 result.append(" [Layer name] <Active time> <Two buffer> "
4463 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004464 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004465 typedef std::tuple<std::string, float, float, float> BufferTuple;
4466 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004467 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004468 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004469 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004470 if (stats.numSegments == 0) {
4471 continue;
4472 }
4473 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4474 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4475 stats.totalTime;
4476 float doubleBufferRatio = static_cast<float>(
4477 stats.doubleBufferedTime) / stats.totalTime;
4478 float tripleBufferRatio = static_cast<float>(
4479 stats.tripleBufferedTime) / stats.totalTime;
4480 sorted.insert({activeTime, {name, twoBufferRatio,
4481 doubleBufferRatio, tripleBufferRatio}});
4482 }
4483 for (const auto& sortedPair : sorted) {
4484 float activeTime = sortedPair.first;
4485 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004486 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4487 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004488 }
4489 result.append("\n");
4490}
4491
Yiwei Zhang5434a782018-12-05 18:06:32 -08004492void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004493 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004494 const auto displayId = display->getId();
4495 if (!displayId) {
4496 continue;
4497 }
4498 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004499 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004500 continue;
4501 }
4502
Yiwei Zhang5434a782018-12-05 18:06:32 -08004503 StringAppendF(&result,
4504 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4505 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004506 uint8_t port;
4507 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004508 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004509 result.append("no identification data\n");
4510 continue;
4511 }
4512
4513 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004514 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004515 continue;
4516 }
4517
4518 const auto edid = parseEdid(data);
4519 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004520 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004521 continue;
4522 }
4523
Yiwei Zhang5434a782018-12-05 18:06:32 -08004524 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004525 result.append(edid->displayName.data(), edid->displayName.length());
4526 result.append("\"\n");
4527 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004528}
4529
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004530void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4531 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004532 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004533 uint8_t port;
4534 DisplayIdentificationData data;
4535
4536 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4537 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4538 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4539 }
4540}
4541
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004543 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004544 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4545 StringAppendF(&result, "DisplayColorSetting: %s\n",
4546 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004547
4548 // TODO: print out if wide-color mode is active or not
4549
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004550 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004551 const auto displayId = display->getId();
4552 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004553 continue;
4554 }
4555
Yiwei Zhang5434a782018-12-05 18:06:32 -08004556 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004557 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004558 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004559 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004560 }
4561
Lloyd Pique32cbe282018-10-19 13:09:22 -07004562 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004563 StringAppendF(&result, " Current color mode: %s (%d)\n",
4564 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004565 }
4566 result.append("\n");
4567}
4568
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004569LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4570 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
4571 const auto display = getDefaultDisplayDeviceLocked();
4572
chaviw1d044282017-09-27 12:19:28 -07004573 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004574 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004575 layer->writeToProto(layersProto, traceFlags, display);
chaviw08f3cb22020-01-13 13:17:21 -08004576 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004577
chaviw1d044282017-09-27 12:19:28 -07004578 return layersProto;
4579}
4580
Alec Mouri6b9e9912020-01-21 10:50:24 -08004581void SurfaceFlinger::dumpHwc(std::string& result) const {
4582 getHwComposer().dump(result);
4583}
4584
Vishnu Nair0f085c62019-08-30 08:49:12 -07004585void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4586 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4587 // it.
4588 LayerProto* rootProto = layersProto.add_layers();
4589 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4590 rootProto->set_id(offscreenRootLayerId);
4591 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004592 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004593
4594 for (Layer* offscreenLayer : mOffscreenLayers) {
4595 // Add layer as child of the fake root
4596 rootProto->add_children(offscreenLayer->sequence);
4597
4598 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004599 LayerProto* layerProto =
4600 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004601 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004602 }
4603}
4604
Vishnu Nair8406fd72019-07-30 11:29:31 -07004605LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4606 LayersProto layersProto;
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004607 postMessageSync(new LambdaMessage([&] { layersProto = dumpDrawingStateProto(traceFlags); }));
Vishnu Nair8406fd72019-07-30 11:29:31 -07004608 return layersProto;
4609}
4610
Vishnu Nair0f085c62019-08-30 08:49:12 -07004611void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4612 result.append("Offscreen Layers:\n");
4613 postMessageSync(new LambdaMessage([&]() {
4614 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004615 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004616 layer->dumpCallingUidPid(result);
4617 });
4618 }
4619 }));
4620}
4621
Dominik Laskowskic2867142019-01-21 11:33:38 -08004622void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4623 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004624 Colorizer colorizer(colorize);
4625
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004626 // figure out if we're stuck somewhere
4627 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004628 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004629 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4630
4631 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004632 * Dump library configuration.
4633 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004634
4635 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004636 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004637 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004638 appendSfConfigString(result);
4639 appendUiConfigString(result);
4640 appendGuiConfigString(result);
4641 result.append("\n");
4642
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004643 result.append("\nDisplay identification data:\n");
4644 dumpDisplayIdentificationData(result);
4645
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004646 result.append("\nWide-Color information:\n");
4647 dumpWideColorInfo(result);
4648
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004649 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004650 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004651 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004652 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004653 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004654
Andy McFadden41d67d72014-04-25 16:58:34 -07004655 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004656 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004657 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004658 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004659 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004660
Dan Stozab90cf072015-03-05 11:05:59 -08004661 dumpStaticScreenStats(result);
4662 result.append("\n");
4663
Alec Mouri40189b02019-03-05 15:07:54 -08004664 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4665 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4666 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004667
Dan Stozae77c7662016-05-13 11:37:28 -07004668 dumpBufferingStats(result);
4669
Andy McFadden4803b742012-09-24 19:07:20 -07004670 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004671 * Dump the visible layer list
4672 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004673 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004674 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4676 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004677 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004678
Chia-I Wu2f884132018-09-13 15:17:58 -07004679 {
Lloyd Pique207def92019-02-28 16:09:52 -08004680 StringAppendF(&result, "Composition layers\n");
4681 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004682 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08004683 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08004684
4685 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4686 layer->getDebugName() ? layer->getDebugName()
4687 : "<unknown>");
4688 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004689 });
4690 }
4691
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004692 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004693 * Dump Display state
4694 */
4695
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004696 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004697 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004698 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004699 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004700 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004701 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004702 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004703
4704 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004705 * Dump CompositionEngine state
4706 */
4707
4708 mCompositionEngine->dump(result);
4709
4710 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004711 * Dump SurfaceFlinger global state
4712 */
4713
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004714 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004715 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004716 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004717
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004718 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004719
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004720 DebugEGLImageTracker::getInstance()->dump(result);
4721
Dominik Laskowski075d3172018-05-24 15:50:06 -07004722 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004723 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4724 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004725 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4726 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004727 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004728 StringAppendF(&result,
4729 " transaction-flags : %08x\n"
4730 " gpu_to_cpu_unsupported : %d\n",
4731 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004732
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004733 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004734 displayId && getHwComposer().isConnected(*displayId)) {
4735 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004736 StringAppendF(&result,
4737 " refresh-rate : %f fps\n"
4738 " x-dpi : %f\n"
4739 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004740 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4741 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004742 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004743
Yiwei Zhang5434a782018-12-05 18:06:32 -08004744 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004745
Dan Stozae22aec72016-08-01 13:20:59 -07004746 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004747 * Tracing state
4748 */
4749 mTracing.dump(result);
4750 result.append("\n");
4751
4752 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004753 * HWC layer minidump
4754 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004755 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004756 const auto displayId = display->getId();
4757 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004758 continue;
4759 }
4760
Yiwei Zhang5434a782018-12-05 18:06:32 -08004761 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004762 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004763 const sp<DisplayDevice> displayDevice = display;
4764 mCurrentState.traverseInZOrder(
4765 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004766 result.append("\n");
4767 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004768
4769 /*
4770 * Dump HWComposer state
4771 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004772 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004773 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004774 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004775 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004776 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004777 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004778
4779 /*
4780 * Dump gralloc state
4781 */
4782 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4783 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004784
4785 /*
4786 * Dump VrFlinger state if in use.
4787 */
4788 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4789 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004790 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004791 result.append("\n");
4792 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004793
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004794 result.append(mTimeStats->miniDump());
4795 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004796}
4797
Chia-I Wu28f320b2018-05-03 11:02:56 -07004798void SurfaceFlinger::updateColorMatrixLocked() {
4799 mat4 colorMatrix;
4800 if (mGlobalSaturationFactor != 1.0f) {
4801 // Rec.709 luma coefficients
4802 float3 luminance{0.213f, 0.715f, 0.072f};
4803 luminance *= 1.0f - mGlobalSaturationFactor;
4804 mat4 saturationMatrix = mat4(
4805 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4806 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4807 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4808 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4809 );
4810 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4811 } else {
4812 colorMatrix = mClientColorMatrix * mDaltonizer();
4813 }
4814
4815 if (mCurrentState.colorMatrix != colorMatrix) {
4816 mCurrentState.colorMatrix = colorMatrix;
4817 mCurrentState.colorMatrixChanged = true;
4818 setTransactionFlags(eTransactionNeeded);
4819 }
4820}
4821
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004822status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004823#pragma clang diagnostic push
4824#pragma clang diagnostic error "-Wswitch-enum"
4825 switch (static_cast<ISurfaceComposerTag>(code)) {
4826 // These methods should at minimum make sure that the client requested
4827 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004828 case BOOT_FINISHED:
4829 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004830 case CREATE_DISPLAY:
4831 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004832 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004833 case GET_ANIMATION_FRAME_STATS:
4834 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004835 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004836 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004837 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004838 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4839 case SET_AUTO_LOW_LATENCY_MODE:
4840 case GET_GAME_CONTENT_TYPE_SUPPORT:
4841 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004842 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004843 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004844 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004845 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004846 case GET_DISPLAYED_CONTENT_SAMPLE:
Lais Andrade3a6e47d2020-04-02 11:20:16 +01004847 case NOTIFY_POWER_BOOST:
Steven Thomasd4071902020-03-24 16:02:53 -07004848 case SET_GLOBAL_SHADOW_SETTINGS:
4849 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4850 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4851 // necessary permission dynamically. Don't use the permission cache for this check.
4852 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4853 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004854 IPCThreadState* ipc = IPCThreadState::self();
4855 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4856 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004857 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004858 }
Robert Carr1db73f62016-12-21 12:58:51 -08004859 return OK;
4860 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004861 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004862 IPCThreadState* ipc = IPCThreadState::self();
4863 const int pid = ipc->getCallingPid();
4864 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004865 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4866 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004867 return PERMISSION_DENIED;
4868 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004869 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004870 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004871 // Used by apps to hook Choreographer to SurfaceFlinger.
4872 case CREATE_DISPLAY_EVENT_CONNECTION:
4873 // The following calls are currently used by clients that do not
4874 // request necessary permissions. However, they do not expose any secret
4875 // information, so it is OK to pass them.
4876 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004877 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004878 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004879 case GET_PHYSICAL_DISPLAY_IDS:
4880 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004881 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004882 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004883 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004884 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004885 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004886 case GET_DISPLAY_STATS:
4887 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4888 // Calling setTransactionState is safe, because you need to have been
4889 // granted a reference to Client* and Handle* to do anything with it.
4890 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004891 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004892 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004893 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004894 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004895 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004896 // setFrameRate() is deliberately available for apps to call without any
4897 // special permissions.
4898 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004899 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4900 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004901 return OK;
4902 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004903 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004904 case CAPTURE_SCREEN:
4905 case ADD_REGION_SAMPLING_LISTENER:
4906 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004907 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004908 IPCThreadState* ipc = IPCThreadState::self();
4909 const int pid = ipc->getCallingPid();
4910 const int uid = ipc->getCallingUid();
4911 if ((uid != AID_GRAPHICS) &&
4912 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4913 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4914 return PERMISSION_DENIED;
4915 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004916 return OK;
4917 }
chaviw93df2ea2019-04-30 16:45:12 -07004918 case CAPTURE_SCREEN_BY_ID: {
4919 IPCThreadState* ipc = IPCThreadState::self();
4920 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004921 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004922 return OK;
4923 }
4924 return PERMISSION_DENIED;
4925 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004926 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004927
4928 // These codes are used for the IBinder protocol to either interrogate the recipient
4929 // side of the transaction for its canonical interface descriptor or to dump its state.
4930 // We let them pass by default.
4931 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4932 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4933 code == IBinder::SYSPROPS_TRANSACTION) {
4934 return OK;
4935 }
Ady Abraham07e54702020-04-16 15:05:37 -07004936 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004937 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004938 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004939 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4940 return OK;
4941 }
4942 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4943 return PERMISSION_DENIED;
4944#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004945}
4946
Ana Krulec13be8ad2018-08-21 02:43:56 +00004947status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4948 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004949 status_t credentialCheck = CheckTransactCodeCredentials(code);
4950 if (credentialCheck != OK) {
4951 return credentialCheck;
4952 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004953
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004954 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4955 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004956 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004957 IPCThreadState* ipc = IPCThreadState::self();
4958 const int uid = ipc->getCallingUid();
4959 if (CC_UNLIKELY(uid != AID_SYSTEM
4960 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004961 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004962 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004963 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004964 return PERMISSION_DENIED;
4965 }
4966 int n;
4967 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004968 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004969 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 return NO_ERROR;
4971 case 1002: // SHOW_UPDATES
4972 n = data.readInt32();
4973 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004974 invalidateHwcGeometry();
4975 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004976 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004977 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004978 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004979 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004980 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004981 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004982 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004983 setTransactionFlags(
4984 eTransactionNeeded|
4985 eDisplayTransactionNeeded|
4986 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004987 return NO_ERROR;
4988 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004989 case 1006:{ // send empty update
4990 signalRefresh();
4991 return NO_ERROR;
4992 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004993 case 1008: // toggle use of hw composer
4994 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004995 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004996 invalidateHwcGeometry();
4997 repaintEverything();
4998 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004999 case 1009: // toggle use of transform hint
5000 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005001 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005002 invalidateHwcGeometry();
5003 repaintEverything();
5004 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005005 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005006 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005007 reply->writeInt32(0);
5008 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005009 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005010 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005011 return NO_ERROR;
5012 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005013 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005014 if (!display) {
5015 return NAME_NOT_FOUND;
5016 }
5017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005018 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005019 return NO_ERROR;
5020 }
5021 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005022 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005023 // daltonize
5024 n = data.readInt32();
5025 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005026 case 1:
5027 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5028 break;
5029 case 2:
5030 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5031 break;
5032 case 3:
5033 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5034 break;
5035 default:
5036 mDaltonizer.setType(ColorBlindnessType::None);
5037 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005038 }
5039 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005040 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005041 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005042 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005043 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005044
5045 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005046 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005047 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005048 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005049 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005050 // apply a color matrix
5051 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005052 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005053 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005054 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005055 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005056 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005057 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005058 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005059 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005060 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005061 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005062
5063 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5064 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005065 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005066 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5067 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5068 }
5069
Chia-I Wu28f320b2018-05-03 11:02:56 -07005070 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005071 return NO_ERROR;
5072 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005073 case 1016: { // Unused.
5074 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005075 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005076 case 1017: {
5077 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005078 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005079 return NO_ERROR;
5080 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005081 case 1018: { // Modify Choreographer's phase offset
5082 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005083 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005084 return NO_ERROR;
5085 }
5086 case 1019: { // Modify SurfaceFlinger's phase offset
5087 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005088 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005089 return NO_ERROR;
5090 }
Irvel468051e2016-06-13 16:44:44 -07005091 case 1020: { // Layer updates interceptor
5092 n = data.readInt32();
5093 if (n) {
5094 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005095 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005096 }
5097 else{
5098 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005099 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005100 }
5101 return NO_ERROR;
5102 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005103 case 1021: { // Disable HWC virtual displays
5104 n = data.readInt32();
5105 mUseHwcVirtualDisplays = !n;
5106 return NO_ERROR;
5107 }
Romain Guy0147a172017-06-01 13:53:56 -07005108 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005109 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005110 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005111
Chia-I Wu28f320b2018-05-03 11:02:56 -07005112 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005113 return NO_ERROR;
5114 }
Romain Guy54f154a2017-10-24 21:40:32 +01005115 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005116 int32_t colorMode;
5117
Chia-I Wu0d711262018-05-21 15:19:35 -07005118 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005119 if (data.readInt32(&colorMode) == NO_ERROR) {
5120 mForceColorMode = static_cast<ColorMode>(colorMode);
5121 }
Romain Guy54f154a2017-10-24 21:40:32 +01005122 invalidateHwcGeometry();
5123 repaintEverything();
5124 return NO_ERROR;
5125 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005126 // Deprecate, use 1030 to check whether the device is color managed.
5127 case 1024: {
5128 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005129 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005130 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005131 n = data.readInt32();
5132 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005133 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005134 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005135 reply->writeInt32(NO_ERROR);
5136 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005137 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005138 mTracingEnabledChanged = mTracing.disable();
5139 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005140 reply->writeInt32(mTracing.writeToFile());
5141 } else {
5142 reply->writeInt32(NO_ERROR);
5143 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005144 }
5145 return NO_ERROR;
5146 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005147 case 1026: { // Get layer tracing status
5148 reply->writeBool(mTracing.isEnabled());
5149 return NO_ERROR;
5150 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005151 // Is a DisplayColorSetting supported?
5152 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005153 const auto display = getDefaultDisplayDevice();
5154 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005155 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005156 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005157
5158 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5159 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005160 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005161 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005162 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005163 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005164 reply->writeBool(true);
5165 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005166 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005167 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005168 break;
5169 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005170 reply->writeBool(
5171 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005172 break;
5173 }
5174 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005175 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005176 // Is VrFlinger active?
5177 case 1028: {
5178 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005179 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005180 return NO_ERROR;
5181 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005182 // Set buffer size for SF tracing (value in KB)
5183 case 1029: {
5184 n = data.readInt32();
5185 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5186 ALOGW("Invalid buffer size: %d KB", n);
5187 reply->writeInt32(BAD_VALUE);
5188 return BAD_VALUE;
5189 }
5190
5191 ALOGD("Updating trace buffer to %d KB", n);
5192 mTracing.setBufferSize(n * 1024);
5193 reply->writeInt32(NO_ERROR);
5194 return NO_ERROR;
5195 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005196 // Is device color managed?
5197 case 1030: {
5198 reply->writeBool(useColorManagement);
5199 return NO_ERROR;
5200 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005201 // Override default composition data space
5202 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5203 // && adb shell stop zygote && adb shell start zygote
5204 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5205 // adb shell stop zygote && adb shell start zygote
5206 case 1031: {
5207 Mutex::Autolock _l(mStateLock);
5208 n = data.readInt32();
5209 if (n) {
5210 n = data.readInt32();
5211 if (n) {
5212 Dataspace dataspace = static_cast<Dataspace>(n);
5213 if (!validateCompositionDataspace(dataspace)) {
5214 return BAD_VALUE;
5215 }
5216 mDefaultCompositionDataspace = dataspace;
5217 }
5218 n = data.readInt32();
5219 if (n) {
5220 Dataspace dataspace = static_cast<Dataspace>(n);
5221 if (!validateCompositionDataspace(dataspace)) {
5222 return BAD_VALUE;
5223 }
5224 mWideColorGamutCompositionDataspace = dataspace;
5225 }
5226 } else {
5227 // restore composition data space.
5228 mDefaultCompositionDataspace = defaultCompositionDataspace;
5229 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5230 }
5231 return NO_ERROR;
5232 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005233 // Set trace flags
5234 case 1033: {
5235 n = data.readUint32();
5236 ALOGD("Updating trace flags to 0x%x", n);
5237 mTracing.setTraceFlags(n);
5238 reply->writeInt32(NO_ERROR);
5239 return NO_ERROR;
5240 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005241 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005242 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005243 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005244 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005245 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005246 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005247 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005248 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005249 } else {
5250 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005251 }
5252 return NO_ERROR;
5253 }
Ady Abraham34392f72019-04-10 11:29:27 -07005254 case 1035: {
5255 n = data.readInt32();
5256 mDebugDisplayConfigSetByBackdoor = false;
5257 if (n >= 0) {
5258 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005259 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005260 if (result != NO_ERROR) {
5261 return result;
5262 }
5263 mDebugDisplayConfigSetByBackdoor = true;
5264 }
5265 return NO_ERROR;
5266 }
Ady Abraham07e54702020-04-16 15:05:37 -07005267 case 1036: {
5268 if (data.readInt32() > 0) {
5269 status_t result =
5270 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5271 if (result != NO_ERROR) {
5272 return result;
5273 }
5274 } else {
5275 mDebugFrameRateFlexibilityToken = nullptr;
5276 }
5277 return NO_ERROR;
5278 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005279 }
5280 }
5281 return err;
5282}
5283
Steven Thomas6d8110b2017-08-31 18:24:21 -07005284void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005285 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005286 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005287}
5288
Ana Krulec7d1d6832018-12-27 11:10:09 -08005289void SurfaceFlinger::repaintEverythingForHWC() {
5290 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005291 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005292 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005293}
5294
Ady Abrahama09852a2020-02-20 14:23:42 -08005295void SurfaceFlinger::kernelTimerChanged(bool expired) {
5296 static bool updateOverlay =
5297 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5298 if (!updateOverlay || !mRefreshRateOverlay) return;
5299
5300 // Update the overlay on the main thread to avoid race conditions with
5301 // mRefreshRateConfigs->getCurrentRefreshRate()
5302 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5303 if (mRefreshRateOverlay) {
5304 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5305 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005306 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005307 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5308 if (mDesiredActiveConfigChanged) {
5309 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5310 mDesiredActiveConfig.configId);
5311 }
5312
5313 return mRefreshRateConfigs->getCurrentRefreshRate();
5314 }();
5315 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5316
5317 if (current != min) {
5318 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5319 mEventQueue->invalidate();
5320 }
5321 }
5322 }));
5323}
5324
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005325// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5326class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005327public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005328 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5329 ~WindowDisconnector() {
5330 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005331 }
5332
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005333private:
5334 ANativeWindow* mWindow;
5335 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005336};
5337
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005338status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005339 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005340 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5341 const Rect& sourceCrop, uint32_t reqWidth,
5342 uint32_t reqHeight, bool useIdentityTransform,
5343 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005344 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005345
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005346 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005347
Dominik Laskowski718f9602019-11-09 20:01:35 -08005348 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5349 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5350 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5351 renderAreaRotation = ui::Transform::ROT_0;
5352 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005353
Chia-I Wu20261cb2018-08-23 12:55:44 -07005354 sp<DisplayDevice> display;
5355 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005356 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005357
Chia-I Wu20261cb2018-08-23 12:55:44 -07005358 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005359 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005360
Chia-I Wucb023152018-08-28 12:57:23 -07005361 // set the requested width/height to the logical display viewport size
5362 // by default
5363 if (reqWidth == 0 || reqHeight == 0) {
5364 reqWidth = uint32_t(display->getViewport().width());
5365 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005366 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005367 }
5368
Peiyong Lin0e003c92018-09-17 11:09:51 -07005369 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005370 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005371 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5372 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005373 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005374 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005375}
5376
chaviw93df2ea2019-04-30 16:45:12 -07005377static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5378 switch (colorMode) {
5379 case ColorMode::DISPLAY_P3:
5380 case ColorMode::BT2100_PQ:
5381 case ColorMode::BT2100_HLG:
5382 case ColorMode::DISPLAY_BT2020:
5383 return Dataspace::DISPLAY_P3;
5384 default:
5385 return Dataspace::V0_SRGB;
5386 }
5387}
5388
Martin Liu4a322352020-03-24 21:30:38 +08005389status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5390 static constexpr int kFifoPriority = 2;
5391 static constexpr int kOtherPriority = 0;
5392
5393 struct sched_param param = {0};
5394 int sched_policy;
5395 if (enabled) {
5396 sched_policy = SCHED_FIFO;
5397 param.sched_priority = kFifoPriority;
5398 } else {
5399 sched_policy = SCHED_OTHER;
5400 param.sched_priority = kOtherPriority;
5401 }
5402
5403 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5404 return -errno;
5405 }
5406 return NO_ERROR;
5407}
5408
chaviw93df2ea2019-04-30 16:45:12 -07005409const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5410 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5411 if (displayToken) {
5412 return getDisplayDeviceLocked(displayToken);
5413 }
5414 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5415 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005416 return getDisplayByLayerStack(displayOrLayerStack);
5417}
5418
5419const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005420 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005421 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005422 return display;
5423 }
5424 }
5425 return nullptr;
5426}
5427
5428status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5429 sp<GraphicBuffer>* outBuffer) {
5430 sp<DisplayDevice> display;
5431 uint32_t width;
5432 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005433 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005434 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005435 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005436 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5437 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005438 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005439 }
5440
5441 width = uint32_t(display->getViewport().width());
5442 height = uint32_t(display->getViewport().height());
5443
Dominik Laskowski718f9602019-11-09 20:01:35 -08005444 const auto orientation = display->getOrientation();
5445 captureOrientation = ui::Transform::toRotationFlags(orientation);
5446
5447 switch (captureOrientation) {
5448 case ui::Transform::ROT_90:
5449 captureOrientation = ui::Transform::ROT_270;
5450 break;
5451
5452 case ui::Transform::ROT_270:
5453 captureOrientation = ui::Transform::ROT_90;
5454 break;
5455
5456 case ui::Transform::ROT_INVALID:
5457 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5458 captureOrientation = ui::Transform::ROT_0;
5459 break;
5460
5461 default:
5462 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005463 }
chaviw93df2ea2019-04-30 16:45:12 -07005464 *outDataspace =
5465 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5466 }
5467
5468 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5469 false /* captureSecureLayers */);
5470
5471 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5472 std::placeholders::_1);
5473 bool ignored = false;
5474 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5475 false /* useIdentityTransform */,
5476 ignored /* outCapturedSecureLayers */);
5477}
5478
Robert Carr866455f2019-04-02 16:28:26 -07005479status_t SurfaceFlinger::captureLayers(
5480 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5481 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5482 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5483 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005484 ATRACE_CALL();
5485
5486 class LayerRenderArea : public RenderArea {
5487 public:
Robert Carr578038f2018-03-09 12:25:24 -08005488 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005489 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005490 bool childrenOnly, const Rect& displayViewport)
5491 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005492 mLayer(layer),
5493 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005494 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005495 mFlinger(flinger),
5496 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005497 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005498 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005499 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005500 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005501 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005502 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005503 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005504 }
chaviwa76b2712017-09-20 12:02:26 -07005505 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005506 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005507 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005508 Rect getSourceCrop() const override {
5509 if (mCrop.isEmpty()) {
5510 return getBounds();
5511 } else {
5512 return mCrop;
5513 }
5514 }
Robert Carr578038f2018-03-09 12:25:24 -08005515 class ReparentForDrawing {
5516 public:
5517 const sp<Layer>& oldParent;
5518 const sp<Layer>& newParent;
5519
Vishnu Nair4351ad52019-02-11 14:13:02 -08005520 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5521 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005522 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005523 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005524 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5525 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005526 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005527 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005528 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005529 };
5530
5531 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005532 const Rect sourceCrop = getSourceCrop();
5533 // no need to check rotation because there is none
5534 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5535 sourceCrop.height() != getReqHeight();
5536
Robert Carr578038f2018-03-09 12:25:24 -08005537 if (!mChildrenOnly) {
5538 mTransform = mLayer->getTransform().inverse();
5539 drawLayers();
5540 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005541 uint32_t w = static_cast<uint32_t>(getWidth());
5542 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005543 // In the "childrenOnly" case we reparent the children to a screenshot
5544 // layer which has no properties set and which does not draw.
5545 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005546 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5547 "Screenshot Parent"s, w, h, 0,
5548 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005549
Vishnu Nair4351ad52019-02-11 14:13:02 -08005550 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005551 drawLayers();
5552 }
5553 }
chaviwa76b2712017-09-20 12:02:26 -07005554
chaviwa76b2712017-09-20 12:02:26 -07005555 private:
chaviw7206d492017-11-10 16:16:12 -08005556 const sp<Layer> mLayer;
5557 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005558
Peiyong Linefefaac2018-08-17 12:27:51 -07005559 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005560 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005561
5562 SurfaceFlinger* mFlinger;
5563 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005564 };
5565
Robert Carrc0df3122019-04-11 13:18:21 -07005566 int reqWidth = 0;
5567 int reqHeight = 0;
5568 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005569 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005570 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005571 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005572 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005573 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005574
Robert Carrc0df3122019-04-11 13:18:21 -07005575 parent = fromHandle(layerHandleBinder);
5576 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5577 ALOGE("captureLayers called with an invalid or removed parent");
5578 return NAME_NOT_FOUND;
5579 }
5580
5581 const int uid = IPCThreadState::self()->getCallingUid();
5582 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5583 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5584 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5585 return PERMISSION_DENIED;
5586 }
5587
Vishnu Nairefc42e22019-12-03 17:36:12 -08005588 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005589 if (sourceCrop.width() <= 0) {
5590 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005591 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005592 }
5593
5594 if (sourceCrop.height() <= 0) {
5595 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005596 crop.bottom = parentSourceBounds.getHeight();
5597 }
5598
5599 if (crop.isEmpty() || frameScale <= 0.0f) {
5600 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5601 // crop was not specified, or an invalid frame scale was provided.
5602 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005603 }
5604 reqWidth = crop.width() * frameScale;
5605 reqHeight = crop.height() * frameScale;
5606
5607 for (const auto& handle : excludeHandles) {
5608 sp<Layer> excludeLayer = fromHandle(handle);
5609 if (excludeLayer != nullptr) {
5610 excludeLayers.emplace(excludeLayer);
5611 } else {
5612 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5613 return NAME_NOT_FOUND;
5614 }
5615 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005616
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005617 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005618 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005619 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005620 }
5621
5622 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005623 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005624
Chia-I Wu20261cb2018-08-23 12:55:44 -07005625 // really small crop or frameScale
5626 if (reqWidth <= 0) {
5627 reqWidth = 1;
5628 }
5629 if (reqHeight <= 0) {
5630 reqHeight = 1;
5631 }
5632
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005633 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5634 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005635 auto traverseLayers = [parent, childrenOnly,
5636 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005637 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5638 if (!layer->isVisible()) {
5639 return;
Robert Carr578038f2018-03-09 12:25:24 -08005640 } else if (childrenOnly && layer == parent.get()) {
5641 return;
chaviwa76b2712017-09-20 12:02:26 -07005642 }
Robert Carr866455f2019-04-02 16:28:26 -07005643
5644 sp<Layer> p = layer;
5645 while (p != nullptr) {
5646 if (excludeLayers.count(p) != 0) {
5647 return;
5648 }
5649 p = p->getParent();
5650 }
5651
chaviwa76b2712017-09-20 12:02:26 -07005652 visitor(layer);
5653 });
5654 };
Robert Carr108b2c72019-04-02 16:32:58 -07005655
5656 bool outCapturedSecureLayers = false;
5657 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5658 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005659}
5660
5661status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5662 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005663 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005664 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005665 bool useIdentityTransform,
5666 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005667 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005668
Peiyong Lin0e003c92018-09-17 11:09:51 -07005669 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005670 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5671 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005672 *outBuffer =
5673 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5674 static_cast<android_pixel_format>(reqPixelFormat), 1,
5675 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005676
Robert Carr108b2c72019-04-02 16:32:58 -07005677 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5678 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005679}
5680
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005681status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5682 TraverseLayersFunction traverseLayers,
5683 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005684 bool useIdentityTransform,
5685 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005686 // This mutex protects syncFd and captureResult for communication of the return values from the
5687 // main thread back to this Binder thread
5688 std::mutex captureMutex;
5689 std::condition_variable captureCondition;
5690 std::unique_lock<std::mutex> captureLock(captureMutex);
5691 int syncFd = -1;
5692 std::optional<status_t> captureResult;
5693
Robert Carr03480e22018-01-04 16:02:06 -08005694 const int uid = IPCThreadState::self()->getCallingUid();
5695 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5696
Dominik Laskowski8c001672018-05-30 16:52:06 -07005697 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005698 // If there is a refresh pending, bug out early and tell the binder thread to try again
5699 // after the refresh.
5700 if (mRefreshPending) {
5701 ATRACE_NAME("Skipping screenshot for now");
5702 std::unique_lock<std::mutex> captureLock(captureMutex);
5703 captureResult = std::make_optional<status_t>(EAGAIN);
5704 captureCondition.notify_one();
5705 return;
5706 }
5707
5708 status_t result = NO_ERROR;
5709 int fd = -1;
5710 {
5711 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005712 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005713 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005714 useIdentityTransform, forSystem, &fd,
5715 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005716 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005717 }
5718
5719 {
5720 std::unique_lock<std::mutex> captureLock(captureMutex);
5721 syncFd = fd;
5722 captureResult = std::make_optional<status_t>(result);
5723 captureCondition.notify_one();
5724 }
5725 });
5726
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005727 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005728 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005729 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005730 while (*captureResult == EAGAIN) {
5731 captureResult.reset();
5732 result = postMessageAsync(message);
5733 if (result != NO_ERROR) {
5734 return result;
5735 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005736 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005737 }
5738 result = *captureResult;
5739 }
5740
5741 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005742 sync_wait(syncFd, -1);
5743 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005744 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005745
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005746 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005747}
5748
chaviwa76b2712017-09-20 12:02:26 -07005749void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005750 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005751 const sp<GraphicBuffer>& buffer,
5752 bool useIdentityTransform, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005753 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005754
chaviwa76b2712017-09-20 12:02:26 -07005755 const auto reqWidth = renderArea.getReqWidth();
5756 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005757 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005758 const auto transform = renderArea.getTransform();
5759 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005760 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005761
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005762 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005763 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005764
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005765 // assume that bounds are never offset, and that they are the same as the
5766 // buffer bounds.
5767 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005768 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005769 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005770
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005771 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5772 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005773
chaviw50da5042018-04-09 13:49:37 -07005774 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005775
Vishnu Nair9b079a22020-01-21 14:36:08 -08005776 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005777 fillLayer.source.buffer.buffer = nullptr;
5778 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005779 fillLayer.geometry.boundaries =
5780 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005781 fillLayer.alpha = half(alpha);
5782 clientCompositionLayers.push_back(fillLayer);
5783
Yichi Chen40773d92020-04-01 10:10:18 +08005784 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005785 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005786 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005787 const bool supportProtectedContent = false;
5788 Region clip(renderArea.getBounds());
5789 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5790 clip,
5791 useIdentityTransform,
Alec Mouri5a6d8572020-03-23 23:56:15 -07005792 layer->needsFilteringForScreenshots(renderArea.getDisplayDevice(), transform) ||
5793 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005794 renderArea.isSecure(),
5795 supportProtectedContent,
5796 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005797 displayViewport,
5798 clientCompositionDisplay.outputDataspace,
5799 true, /* realContentIsVisible */
5800 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005801 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005802 std::vector<compositionengine::LayerFE::LayerSettings> results =
5803 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005804 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005805 for (auto& settings : results) {
5806 settings.geometry.positionTransform =
5807 transform.asMatrix4() * settings.geometry.positionTransform;
5808 }
Yichi Chen40773d92020-04-01 10:10:18 +08005809 clientCompositionLayers.insert(clientCompositionLayers.end(),
5810 std::make_move_iterator(results.begin()),
5811 std::make_move_iterator(results.end()));
5812 renderedLayers.push_back(layer);
5813 }
chaviwa76b2712017-09-20 12:02:26 -07005814 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005815
Yichi Chen40773d92020-04-01 10:10:18 +08005816 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5817 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005818 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005819 clientCompositionLayerPointers.begin(),
5820 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005821
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005822 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005823 // Use an empty fence for the buffer fence, since we just created the buffer so
5824 // there is no need for synchronization with the GPU.
5825 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005826 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005827 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005828 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005829 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005830
5831 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005832
5833 if (*outSyncFd >= 0) {
5834 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5835 for (auto* layer : renderedLayers) {
5836 layer->onLayerDisplayed(releaseFence);
5837 }
5838 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005839}
5840
chaviwa76b2712017-09-20 12:02:26 -07005841status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5842 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005843 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005844 bool useIdentityTransform, bool forSystem,
5845 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005846 ATRACE_CALL();
5847
chaviwa76b2712017-09-20 12:02:26 -07005848 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005849 outCapturedSecureLayers =
5850 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005851 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005852
Robert Carr03480e22018-01-04 16:02:06 -08005853 // We allow the system server to take screenshots of secure layers for
5854 // use in situations like the Screen-rotation animation and place
5855 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005856 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005857 ALOGW("FB is protected: PERMISSION_DENIED");
5858 return PERMISSION_DENIED;
5859 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005860 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005861 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005862}
5863
chaviw95ef3c42019-02-14 10:55:09 -08005864void SurfaceFlinger::setInputWindowsFinished() {
5865 Mutex::Autolock _l(mStateLock);
5866
5867 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005868
chaviw95ef3c42019-02-14 10:55:09 -08005869 mTransactionCV.broadcast();
5870}
chaviw5f21a5e2019-02-14 10:00:34 -08005871
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005872// ---------------------------------------------------------------------------
5873
Edgar Arriaga844fa672020-01-16 14:21:42 -08005874void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5875 layersSortedByZ.traverse(visitor);
5876}
5877
Dan Stoza412903f2017-04-27 13:42:17 -07005878void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5879 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005880}
5881
Dan Stoza412903f2017-04-27 13:42:17 -07005882void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5883 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005884}
5885
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005886void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005887 const LayerVector::Visitor& visitor) {
5888 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005889 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005890 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005891 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005892 continue;
5893 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005894 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005895 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005896 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005897 return;
5898 }
chaviwa76b2712017-09-20 12:02:26 -07005899 if (!layer->isVisible()) {
5900 return;
5901 }
5902 visitor(layer);
5903 });
5904 }
5905}
5906
Steven Thomasd4071902020-03-24 16:02:53 -07005907status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5908 const sp<DisplayDevice>& display,
5909 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005910 Mutex::Autolock lock(mStateLock);
5911
Steven Thomasd4071902020-03-24 16:02:53 -07005912 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5913 "Can only set override policy on the primary display");
5914 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5915
Dominik Laskowski22488f62019-03-28 09:53:04 -07005916 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005917 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5918 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5919 // it should go thru setDesiredActiveConfig, similar to primary display.
5920 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5921 const auto displayId = display->getId();
5922 LOG_ALWAYS_FATAL_IF(!displayId);
5923
Peiyong Line9d809e2020-04-14 13:10:48 -07005924 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005925 constraints.desiredTimeNanos = systemTime();
5926 constraints.seamlessRequired = false;
5927
Peiyong Line9d809e2020-04-14 13:10:48 -07005928 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005929 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5930 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005931 constraints, &timeline) < 0) {
5932 return BAD_VALUE;
5933 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005934 if (timeline.refreshRequired) {
5935 repaintEverythingForHWC();
5936 }
5937
Steven Thomasd4071902020-03-24 16:02:53 -07005938 display->setActiveConfig(policy->defaultConfig);
5939 const nsecs_t vsyncPeriod = getHwComposer()
5940 .getConfigs(*displayId)[policy->defaultConfig.value()]
5941 ->getVsyncPeriod();
5942 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5943 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005944 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005945 }
5946
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005947 if (mDebugDisplayConfigSetByBackdoor) {
5948 // ignore this request as config is overridden by backdoor
5949 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005950 }
5951
Steven Thomasd4071902020-03-24 16:02:53 -07005952 status_t setPolicyResult = overridePolicy
5953 ? mRefreshRateConfigs->setOverridePolicy(policy)
5954 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5955 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005956 return BAD_VALUE;
5957 }
Steven Thomasd4071902020-03-24 16:02:53 -07005958 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005959 return NO_ERROR;
5960 }
Steven Thomasd4071902020-03-24 16:02:53 -07005961 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005962
5963 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
Steven Thomasd4071902020-03-24 16:02:53 -07005964 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
5965 currentPolicy.maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005966
5967 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5968 // that listeners that care about a change in allowed configs can get the notification.
5969 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005970 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005971 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5972 .getVsyncPeriod();
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005973 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005974 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005975
Ana Krulec3f6a2062020-01-23 15:48:01 -08005976 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005977 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005978 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5979 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005980 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005981 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005982 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005983
Ady Abrahamabc27602020-04-08 17:20:29 -07005984 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5985 ALOGV("switching to Scheduler preferred config %d",
5986 preferredRefreshRate.getConfigId().value());
5987 setDesiredActiveConfig(
5988 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005989 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005990 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5991 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005992 }
5993
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005994 return NO_ERROR;
5995}
5996
Ana Krulec0782b882019-10-15 17:34:54 -07005997status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005998 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005999 float maxRefreshRate) {
6000 ATRACE_CALL();
6001
6002 if (!displayToken) {
6003 return BAD_VALUE;
6004 }
6005
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006006 status_t result = NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006007
Ana Krulec234bb162019-11-10 22:55:55 +01006008 postMessageSync(new LambdaMessage([&]() {
6009 const auto display = getDisplayDeviceLocked(displayToken);
6010 if (!display) {
6011 ALOGE("Attempt to set desired display configs for invalid display token %p",
6012 displayToken.get());
6013 } else if (display->isVirtual()) {
6014 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006015 result = INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006016 } else {
Steven Thomasd4071902020-03-24 16:02:53 -07006017 result = setDesiredDisplayConfigSpecsInternal(display,
6018 scheduler::RefreshRateConfigs::
6019 Policy{HwcConfigIndexType(
6020 defaultConfig),
6021 minRefreshRate,
6022 maxRefreshRate},
6023 /*overridePolicy=*/false);
Ana Krulec234bb162019-11-10 22:55:55 +01006024 }
6025 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006026
6027 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01006028}
6029
6030status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006031 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01006032 float* outMinRefreshRate,
6033 float* outMaxRefreshRate) {
6034 ATRACE_CALL();
6035
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006036 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01006037 return BAD_VALUE;
6038 }
6039
6040 Mutex::Autolock lock(mStateLock);
6041 const auto display = getDisplayDeviceLocked(displayToken);
6042 if (!display) {
6043 return NAME_NOT_FOUND;
6044 }
6045
6046 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006047 scheduler::RefreshRateConfigs::Policy policy =
6048 mRefreshRateConfigs->getDisplayManagerPolicy();
6049 *outDefaultConfig = policy.defaultConfig.value();
6050 *outMinRefreshRate = policy.minRefreshRate;
6051 *outMaxRefreshRate = policy.maxRefreshRate;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006052 return NO_ERROR;
6053 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006054 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006055 } else {
6056 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006057 LOG_FATAL_IF(!displayId);
6058
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006059 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6060 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6061 *outMinRefreshRate = 1e9f / vsyncPeriod;
6062 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6063 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006064 }
Ana Krulec0782b882019-10-15 17:34:54 -07006065}
6066
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006067void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006068 mFlinger->setInputWindowsFinished();
6069}
6070
Robert Carrc0df3122019-04-11 13:18:21 -07006071sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006072 BBinder* b = nullptr;
6073 if (handle) {
6074 b = handle->localBinder();
6075 }
Robert Carrc0df3122019-04-11 13:18:21 -07006076 if (b == nullptr) {
6077 return nullptr;
6078 }
6079 auto it = mLayersByLocalBinderToken.find(b);
6080 if (it != mLayersByLocalBinderToken.end()) {
6081 return it->second.promote();
6082 }
6083 return nullptr;
6084}
6085
Dominik Laskowski75848362019-11-11 17:57:20 -08006086void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006087 mNumLayers++;
6088 mScheduler->registerLayer(layer);
6089}
6090
6091void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6092 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006093 removeFromOffscreenLayers(layer);
6094}
6095
6096// WARNING: ONLY CALL THIS FROM LAYER DTOR
6097// Here we add children in the current state to offscreen layers and remove the
6098// layer itself from the offscreen layer list. Since
6099// this is the dtor, it is safe to access the current state. This keeps us
6100// from dangling children layers such that they are not reachable from the
6101// Drawing state nor the offscreen layer list
6102// See b/141111965
6103void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6104 for (auto& child : layer->getCurrentChildren()) {
6105 mOffscreenLayers.emplace(child.get());
6106 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006107 mOffscreenLayers.erase(layer);
6108}
6109
Alec Mouri4545a8a2019-08-08 20:05:32 -07006110void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6111 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6112}
6113
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006114status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6115 float lightPosY, float lightPosZ,
6116 float lightRadius) {
6117 Mutex::Autolock _l(mStateLock);
6118 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6119 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6120 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6121 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6122 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6123
6124 // these values are overridden when calculating the shadow settings for a layer.
6125 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6126 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006127 return NO_ERROR;
6128}
6129
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006130const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6131 const {
6132 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6133 // on the work to remove the table in that bug rather than adding more to
6134 // it.
6135 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6136 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6137 // supported, and exposed via the
6138 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6139 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6140 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6141 };
6142 return genericLayerMetadataKeyMap;
6143}
6144
Steven Thomas62a4cf82020-01-31 12:04:03 -08006145status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6146 int8_t compatibility) {
6147 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6148 return BAD_VALUE;
6149 }
6150
Ady Abraham60e42ea2020-03-09 19:17:31 -07006151 postMessageAsync(new LambdaMessage([=]() NO_THREAD_SAFETY_ANALYSIS {
6152 Mutex::Autolock lock(mStateLock);
6153 if (authenticateSurfaceTextureLocked(surface)) {
6154 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6155 if (layer->setFrameRate(
6156 Layer::FrameRate(frameRate,
6157 Layer::FrameRate::convertCompatibility(compatibility)))) {
6158 setTransactionFlags(eTraversalNeeded);
6159 }
6160 } else {
6161 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6162 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006163 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006164 return NO_ERROR;
6165 }));
6166
Steven Thomas62a4cf82020-01-31 12:04:03 -08006167 return NO_ERROR;
6168}
6169
Steven Thomasd4071902020-03-24 16:02:53 -07006170status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6171 if (!outToken) {
6172 return BAD_VALUE;
6173 }
6174 status_t result = NO_ERROR;
6175 postMessageSync(new LambdaMessage([&]() {
6176 if (mFrameRateFlexibilityTokenCount == 0) {
6177 // |mStateLock| not needed as we are on the main thread
6178 const auto display = getDefaultDisplayDeviceLocked();
6179
6180 // This is a little racy, but not in a way that hurts anything. As we grab the
6181 // defaultConfig from the display manager policy, we could be setting a new display
6182 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6183 // matter for the override policy though, since we set allowGroupSwitching to true, so
6184 // it's not a problem.
6185 scheduler::RefreshRateConfigs::Policy overridePolicy;
6186 overridePolicy.defaultConfig =
6187 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6188 overridePolicy.allowGroupSwitching = true;
6189 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy,
6190 /*overridePolicy=*/true);
6191 }
6192
6193 if (result == NO_ERROR) {
6194 mFrameRateFlexibilityTokenCount++;
6195 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6196 // below, is something to consider carefully. The lifetime of the
6197 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6198 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6199 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6200 // in this case, for two reasons:
6201 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6202 // the program exits is via a crash. So we won't have a situation where the
6203 // SurfaceFlinger object is dead but the process is still up.
6204 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6205 // if condition 1 were changed, the problem would only show up when running CTS tests,
6206 // not on end user devices, so we could spot it and fix it without serious impact.
6207 *outToken = new FrameRateFlexibilityToken(
6208 [this]() { onFrameRateFlexibilityTokenReleased(); });
6209 ALOGD("Frame rate flexibility token acquired. count=%d",
6210 mFrameRateFlexibilityTokenCount);
6211 }
6212 }));
6213 return result;
6214}
6215
6216void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
6217 postMessageAsync(new LambdaMessage([&]() {
6218 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6219 "Failed tracking frame rate flexibility tokens");
6220 mFrameRateFlexibilityTokenCount--;
6221 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6222 if (mFrameRateFlexibilityTokenCount == 0) {
6223 // |mStateLock| not needed as we are on the main thread
6224 const auto display = getDefaultDisplayDeviceLocked();
6225 status_t result =
6226 setDesiredDisplayConfigSpecsInternal(display, {}, /*overridePolicy=*/true);
6227 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6228 }
6229 }));
6230}
6231
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006232} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006233
Mathias Agopian3f844832013-08-07 21:24:32 -07006234#if defined(__gl_h_)
6235#error "don't include gl/gl.h in this file"
6236#endif
6237
6238#if defined(__gl2_h_)
6239#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006240#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006241
6242// TODO(b/129481165): remove the #pragma below and fix conversion issues
6243#pragma clang diagnostic pop // ignored "-Wconversion"