blob: 794e8a7a44e8075b12d6e0bfc0c9e687ee5b7493 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri989ddbe2020-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>
30#include <android/hardware/power/1.0/IPower.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 Piqueaad4ebf2019-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 Mouri989ddbe2020-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 Mouri989ddbe2020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
Dominik Laskowski5690bde2020-04-23 19:04:22 -0700111#include "Promise.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800112#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700113#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700114#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700115#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700116#include "Scheduler/EventControlThread.h"
117#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700118#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700119#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700120#include "Scheduler/Scheduler.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800121#include "StartPropertySetThread.h"
122#include "SurfaceFlingerProperties.h"
123#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800124#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700125#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800126#include "android-base/stringprintf.h"
127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700129
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700130using namespace std::string_literals;
131
Jaesoo Lee43518572017-01-23 19:03:16 +0900132using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900133using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900134using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800135
Ady Abraham8532d012019-05-08 14:50:56 -0700136using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800137using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700138using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700139using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800140using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700141using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700142using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900143
Peiyong Line9d809e2020-04-14 13:10:48 -0700144namespace hal = android::hardware::graphics::composer::hal;
145
Steven Thomasb02664d2017-07-26 18:48:28 -0700146namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700147
148#pragma clang diagnostic push
149#pragma clang diagnostic error "-Wswitch-enum"
150
151bool isWideColorMode(const ColorMode colorMode) {
152 switch (colorMode) {
153 case ColorMode::DISPLAY_P3:
154 case ColorMode::ADOBE_RGB:
155 case ColorMode::DCI_P3:
156 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700157 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700158 case ColorMode::BT2100_PQ:
159 case ColorMode::BT2100_HLG:
160 return true;
161 case ColorMode::NATIVE:
162 case ColorMode::STANDARD_BT601_625:
163 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
164 case ColorMode::STANDARD_BT601_525:
165 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
166 case ColorMode::STANDARD_BT709:
167 case ColorMode::SRGB:
168 return false;
169 }
170 return false;
171}
172
173#pragma clang diagnostic pop
174
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700175template <typename Mutex>
176struct ConditionalLockGuard {
177 ConditionalLockGuard(Mutex& mutex, bool lock) : mutex(mutex), lock(lock) {
178 if (lock) mutex.lock();
Steven Thomasb02664d2017-07-26 18:48:28 -0700179 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700180
181 ~ConditionalLockGuard() {
182 if (lock) mutex.unlock();
183 }
184
185 Mutex& mutex;
186 const bool lock;
Steven Thomasb02664d2017-07-26 18:48:28 -0700187};
Peiyong Linfca547f2018-07-09 13:03:33 -0700188
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700189using ConditionalLock = ConditionalLockGuard<Mutex>;
190
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800191// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
192constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
193
194float getDensityFromProperty(const char* property, bool required) {
195 char value[PROPERTY_VALUE_MAX];
196 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
197 if (!density && required) {
198 ALOGE("%s must be defined as a build property", property);
199 return FALLBACK_DENSITY;
200 }
201 return density / 160.f;
202}
203
Peiyong Lin9d846a52018-11-05 13:18:20 -0800204// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
205bool validateCompositionDataspace(Dataspace dataspace) {
206 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
207}
208
Steven Thomasd4071902020-03-24 16:02:53 -0700209class FrameRateFlexibilityToken : public BBinder {
210public:
211 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
212 virtual ~FrameRateFlexibilityToken() { mCallback(); }
213
214private:
215 std::function<void()> mCallback;
216};
217
Steven Thomasb02664d2017-07-26 18:48:28 -0700218} // namespace anonymous
219
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220// ---------------------------------------------------------------------------
221
Mathias Agopian99b49842011-06-27 16:05:52 -0700222const String16 sHardwareTest("android.permission.HARDWARE_TEST");
223const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
224const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
225const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800226const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700227
228// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700229int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700230bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800231uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800232bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800233bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800234int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100235uint32_t SurfaceFlinger::maxGraphicsWidth;
236uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600237bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800238ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700239bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700240bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700241Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
242ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
243Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
244ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800245bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700246
Kalle Raitaa099a242017-01-11 11:17:29 -0800247std::string getHwcServiceName() {
248 char value[PROPERTY_VALUE_MAX] = {};
249 property_get("debug.sf.hwc_service_name", value, "default");
250 ALOGI("Using HWComposer service: '%s'", value);
251 return std::string(value);
252}
253
254bool useTrebleTestingOverride() {
255 char value[PROPERTY_VALUE_MAX] = {};
256 property_get("debug.sf.treble_testing_override", value, "false");
257 ALOGI("Treble testing override: '%s'", value);
258 return std::string(value) == "true";
259}
260
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800261std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
262 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800263 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700264 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800265 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700266 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800267 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700268 return std::string("Enhanced");
269 default:
270 return std::string("Unknown ") +
271 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800272 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800273}
274
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700275SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800276
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700277SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
278 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700279 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700280 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700281 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700282 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700283 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800284 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
285 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800286
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700287SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800288 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700293
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900294 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700295
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900296 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800297
Steven Thomas050b2c82017-03-06 11:45:16 -0800298 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800302
Brian Lindahla13f2d52020-03-05 11:54:17 +0100303 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
304 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 mDefaultCompositionDataspace =
311 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700312 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
313 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 defaultCompositionDataspace = mDefaultCompositionDataspace;
315 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
316 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
317 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
318 wideColorGamutCompositionPixelFormat =
319 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700320
Yichi Chenda901bf2019-06-28 14:58:27 +0800321 mColorSpaceAgnosticDataspace =
322 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
323
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900324 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800325
Dominik Laskowski718f9602019-11-09 20:01:35 -0800326 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
327 switch (primary_display_orientation(Values::ORIENTATION_0)) {
328 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800329 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800330 case Values::ORIENTATION_90:
331 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800332 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800333 case Values::ORIENTATION_180:
334 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800336 case Values::ORIENTATION_270:
337 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800338 break;
339 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800340 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800341
Sundong Ahn85131bd2019-02-18 15:51:53 +0900342 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344 // debugging stuff...
345 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700346
Mathias Agopianb4b17302013-03-20 18:36:41 -0700347 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700348 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700349
Alec Mouri989ddbe2020-02-06 09:26:19 -0800350 property_get("ro.build.type", value, "user");
351 mIsUserBuild = strcmp(value, "user") == 0;
352
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353 property_get("debug.sf.showupdates", value, "0");
354 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700355
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700356 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000357
358 // DDMS debugging deprecated (b/120782499)
359 property_get("debug.sf.ddms", value, "0");
360 int debugDdms = atoi(value);
361 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700362
363 property_get("debug.sf.disable_backpressure", value, "0");
364 mPropagateBackpressure = !atoi(value);
365 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700366
Ady Abrahamadb9a992019-09-19 21:21:55 +0000367 property_get("debug.sf.enable_gl_backpressure", value, "0");
368 mPropagateBackpressureClientComposition = atoi(value);
369 ALOGI_IF(mPropagateBackpressureClientComposition,
370 "Enabling backpressure propagation for Client Composition");
371
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800372 property_get("debug.sf.enable_hwc_vds", value, "0");
373 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800374 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800375
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800376 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800377 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800378 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700379
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800380 property_get("ro.surface_flinger.supports_background_blur", value, "0");
381 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700382 mSupportsBlur = supportsBlurs;
383 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800384 property_get("ro.sf.blurs_are_expensive", value, "0");
385 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800386
Ady Abraham0a525092020-03-03 12:51:24 -0800387 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700388 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
389 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
390
Dan Stozaec460082018-12-17 15:35:09 -0800391 property_get("debug.sf.luma_sampling", value, "1");
392 mLumaSampling = atoi(value);
393
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800394 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800395 mDisableClientCompositionCache = atoi(value);
396
Romain Guy11d63f42017-07-20 12:47:14 -0700397 // We should be reading 'persist.sys.sf.color_saturation' here
398 // but since /data may be encrypted, we need to wait until after vold
399 // comes online to attempt to read the property. The property is
400 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800401
402 if (useTrebleTestingOverride()) {
403 // Without the override SurfaceFlinger cannot connect to HIDL
404 // services that are not listed in the manifests. Considered
405 // deriving the setting from the set service name, but it
406 // would be brittle if the name that's not 'default' is used
407 // for production purposes later on.
408 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
409 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800410
411 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412}
413
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700414SurfaceFlinger::~SurfaceFlinger() = default;
415
416void SurfaceFlinger::onFirstRef() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800417 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418}
419
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700420void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700422 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423
Andy McFadden13a082e2012-08-24 10:16:42 -0700424 // restore initial conditions (default device unblank, etc)
425 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426
427 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700428 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429}
430
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700431void SurfaceFlinger::run() {
432 while (true) {
433 mEventQueue->waitMessage();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700435}
436
437template <typename F, typename T>
438inline std::future<T> SurfaceFlinger::schedule(F&& f) {
439 auto [task, future] = makeTask(std::move(f));
440 mEventQueue->postMessage(std::move(task));
441 return std::move(future);
Robert Carr1db73f62016-12-21 12:58:51 -0800442}
443
444sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700445 const sp<Client> client = new Client(this);
446 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800447}
448
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700449sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700450 class DisplayToken : public BBinder {
451 sp<SurfaceFlinger> flinger;
452 virtual ~DisplayToken() {
453 // no more references, this display must be terminated
454 Mutex::Autolock _l(flinger->mStateLock);
455 flinger->mCurrentState.displays.removeItem(this);
456 flinger->setTransactionFlags(eDisplayTransactionNeeded);
457 }
458 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700459 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700460 : flinger(flinger) {
461 }
462 };
463
464 sp<BBinder> token = new DisplayToken(this);
465
466 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700467 // Display ID is assigned when virtual display is allocated by HWC.
468 DisplayDeviceState state;
469 state.isSecure = secure;
470 state.displayName = displayName;
471 mCurrentState.displays.add(token, state);
472 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473 return token;
474}
475
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700476void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700477 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700478
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700479 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700480 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700481 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700482 return;
483 }
484
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700486 if (state.physical) {
487 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700488 return;
489 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490 mInterceptor->saveDisplayDeletion(state.sequenceId);
491 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 setTransactionFlags(eDisplayTransactionNeeded);
493}
494
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800495std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
496 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700497
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800498 const auto internalDisplayId = getInternalDisplayIdLocked();
499 if (!internalDisplayId) {
500 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700501 }
502
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800503 std::vector<PhysicalDisplayId> displayIds;
504 displayIds.reserve(mPhysicalDisplayTokens.size());
505 displayIds.push_back(internalDisplayId->value);
506
507 for (const auto& [id, token] : mPhysicalDisplayTokens) {
508 if (id != *internalDisplayId) {
509 displayIds.push_back(id.value);
510 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700511 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700512
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800513 return displayIds;
514}
515
516sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
517 Mutex::Autolock lock(mStateLock);
518 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519}
520
Ady Abraham37965d42018-11-01 13:43:32 -0700521status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
522 if (!outGetColorManagement) {
523 return BAD_VALUE;
524 }
525 *outGetColorManagement = useColorManagement;
526 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700527}
528
Lloyd Pique441d5042018-10-18 16:49:51 -0700529HWComposer& SurfaceFlinger::getHwComposer() const {
530 return mCompositionEngine->getHwComposer();
531}
532
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700533renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
534 return mCompositionEngine->getRenderEngine();
535}
536
Lloyd Pique70d91362018-10-18 16:02:55 -0700537compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
538 return *mCompositionEngine.get();
539}
540
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541void SurfaceFlinger::bootFinished()
542{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700543 if (mBootFinished == true) {
544 ALOGE("Extra call to bootFinished");
545 return;
546 }
547 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700548 if (mStartPropertySetThread->join() != NO_ERROR) {
549 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800550 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551 const nsecs_t now = systemTime();
552 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000553 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554
Mikael Pessa90092f42019-08-26 17:22:04 -0700555 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000556 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700557
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700558 // wait patiently for the window manager death
559 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700560 mWindowManager = defaultServiceManager()->getService(name);
561 if (mWindowManager != 0) {
562 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700563 }
Robert Carr720e5062018-07-30 17:45:14 -0700564 sp<IBinder> input(defaultServiceManager()->getService(
565 String16("inputflinger")));
566 if (input == nullptr) {
567 ALOGE("Failed to link to input service");
568 } else {
569 mInputFlinger = interface_cast<IInputFlinger>(input);
570 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700571
Steven Thomas050b2c82017-03-06 11:45:16 -0800572 if (mVrFlinger) {
573 mVrFlinger->OnBootFinished();
574 }
575
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700576 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700577 // formerly we would just kill the process, but we now ask it to exit so it
578 // can choose where to stop the animation.
579 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700580
581 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
582 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
583 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700584
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700585 static_cast<void>(schedule([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800586 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700587 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800588 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800589
Ady Abraham8a82ba62020-01-17 12:43:17 -0800590 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
591 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
592 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
593 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800594 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800595}
596
Dan Stoza436ccf32018-06-21 12:10:12 -0700597uint32_t SurfaceFlinger::getNewTexture() {
598 {
599 std::lock_guard lock(mTexturePoolMutex);
600 if (!mTexturePool.empty()) {
601 uint32_t name = mTexturePool.back();
602 mTexturePool.pop_back();
603 ATRACE_INT("TexturePoolSize", mTexturePool.size());
604 return name;
605 }
606
607 // The pool was too small, so increase it for the future
608 ++mTexturePoolSize;
609 }
610
611 // The pool was empty, so we need to get a new texture name directly using a
612 // blocking call to the main thread
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700613 return schedule([this] {
614 uint32_t name = 0;
615 getRenderEngine().genTextures(1, &name);
616 return name;
617 })
618 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700619}
620
Mathias Agopian3f844832013-08-07 21:24:32 -0700621void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700622 std::lock_guard lock(mTexturePoolMutex);
623 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
624 // to actually delete this or not based on mTexturePoolSize
625 mTexturePool.push_back(texture);
626 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700627}
628
Wei Wangf9b05ee2017-07-19 20:59:39 -0700629// Do not call property_set on main thread which will be blocked by init
630// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700631void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700632 ALOGI( "SurfaceFlinger's main thread ready to run. "
633 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800635
Steven Thomasb02664d2017-07-26 18:48:28 -0700636 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700637 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800638 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700639 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
640 renderengine::RenderEngineCreationArgs::Builder()
641 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
642 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
643 .setUseColorManagerment(useColorManagement)
644 .setEnableProtectedContext(enable_protected_contents(false))
645 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700646 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700647 .setContextPriority(useContextPriority
648 ? renderengine::RenderEngine::ContextPriority::HIGH
649 : renderengine::RenderEngine::ContextPriority::MEDIUM)
650 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800651 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700652
653 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
654 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700655 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800656 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800657 // Process any initial hotplug and resulting display changes.
658 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700659 const auto display = getDefaultDisplayDeviceLocked();
660 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700661 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700662 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800663
Steven Thomas050b2c82017-03-06 11:45:16 -0800664 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700665 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700666 // This callback is called from the vr flinger dispatch thread. We
667 // need to call signalTransaction(), which requires holding
668 // mStateLock when we're not on the main thread. Acquiring
669 // mStateLock from the vr flinger dispatch thread might trigger a
670 // deadlock in surface flinger (see b/66916578), so post a message
671 // to be handled on the main thread instead.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700672 static_cast<void>(schedule([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700673 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
674 mVrFlingerRequestsDisplay = requestDisplay;
675 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700676 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800677 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700678 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
679 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700680 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700681 .value_or(0),
682 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800683 if (!mVrFlinger) {
684 ALOGE("Failed to start vrflinger");
685 }
686 }
687
Mathias Agopian92a979a2012-08-02 18:32:23 -0700688 // initialize our drawing state
689 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700690
Andy McFadden13a082e2012-08-24 10:16:42 -0700691 // set initial conditions (e.g. unblank default device)
692 initializeDisplays();
693
Steven Thomas137d4bc2019-07-25 16:55:14 -0700694 char primeShaderCache[PROPERTY_VALUE_MAX];
695 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
696 if (atoi(primeShaderCache)) {
697 getRenderEngine().primeCache();
698 }
Dan Stoza4e637772016-07-28 13:31:51 -0700699
Wei Wangf9b05ee2017-07-19 20:59:39 -0700700 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700701
702 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700703 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700704 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700705
706 if (mStartPropertySetThread->Start() != NO_ERROR) {
707 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800708 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800709
Dan Stoza9e56aa02015-11-02 13:00:03 -0800710 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700711}
712
Romain Guy11d63f42017-07-20 12:47:14 -0700713void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700714 Mutex::Autolock _l(mStateLock);
715
Romain Guy11d63f42017-07-20 12:47:14 -0700716 char value[PROPERTY_VALUE_MAX];
717
718 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800719 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700720 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800721 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100722
723 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700724 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800725
726 property_get("persist.sys.sf.color_mode", value, "0");
727 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700728
729 property_get("persist.sys.sf.disable_blurs", value, "0");
730 bool disableBlurs = atoi(value);
731 mDisableBlurs = disableBlurs;
732 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700733}
734
Mathias Agopiana67e4182012-06-19 17:26:12 -0700735void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800736 // Start boot animation service by setting a property mailbox
737 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800739 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700740 if (mStartPropertySetThread->join() != NO_ERROR) {
741 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800742 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700743}
744
Mathias Agopian875d8e12013-06-07 15:35:48 -0700745size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700746 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700747}
748
Mathias Agopian875d8e12013-06-07 15:35:48 -0700749size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700750 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700751}
752
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800753// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800754
Jamie Gennis582270d2011-08-17 18:19:00 -0700755bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800756 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800757 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800758 return authenticateSurfaceTextureLocked(bufferProducer);
759}
760
761bool SurfaceFlinger::authenticateSurfaceTextureLocked(
762 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800763 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800764 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800765}
766
Brian Anderson6b376712017-04-04 10:51:39 -0700767status_t SurfaceFlinger::getSupportedFrameTimestamps(
768 std::vector<FrameEvent>* outSupported) const {
769 *outSupported = {
770 FrameEvent::REQUESTED_PRESENT,
771 FrameEvent::ACQUIRE,
772 FrameEvent::LATCH,
773 FrameEvent::FIRST_REFRESH_START,
774 FrameEvent::LAST_REFRESH_START,
775 FrameEvent::GPU_COMPOSITION_DONE,
776 FrameEvent::DEQUEUE_READY,
777 FrameEvent::RELEASE,
778 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700779 ConditionalLock _l(mStateLock,
780 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700781 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700782 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
783 }
784 return NO_ERROR;
785}
786
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800787status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
788 if (!displayToken || !state) {
789 return BAD_VALUE;
790 }
791
792 Mutex::Autolock lock(mStateLock);
793
794 const auto display = getDisplayDeviceLocked(displayToken);
795 if (!display) {
796 return NAME_NOT_FOUND;
797 }
798
799 state->layerStack = display->getLayerStack();
800 state->orientation = display->getOrientation();
801
802 const Rect viewport = display->getViewport();
803 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
804
805 return NO_ERROR;
806}
807
808status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
809 if (!displayToken || !info) {
810 return BAD_VALUE;
811 }
812
813 Mutex::Autolock lock(mStateLock);
814
815 const auto display = getDisplayDeviceLocked(displayToken);
816 if (!display) {
817 return NAME_NOT_FOUND;
818 }
819
Dominik Laskowski55c85402020-01-21 16:25:47 -0800820 if (const auto connectionType = display->getConnectionType())
821 info->connectionType = *connectionType;
822 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800823 return INVALID_OPERATION;
824 }
825
826 if (mEmulatedDisplayDensity) {
827 info->density = mEmulatedDisplayDensity;
828 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800829 info->density = info->connectionType == DisplayConnectionType::Internal
830 ? mInternalDisplayDensity
831 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800832 }
833
834 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200835 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800836
837 return NO_ERROR;
838}
839
Dominik Laskowski22488f62019-03-28 09:53:04 -0700840status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800841 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700842 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 return BAD_VALUE;
844 }
845
Dominik Laskowski22488f62019-03-28 09:53:04 -0700846 Mutex::Autolock lock(mStateLock);
847
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800848 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700849 if (!displayId) {
850 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700851 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700852
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800853 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700854
Dan Stoza7f7da322014-05-02 15:26:25 -0700855 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700856
Dominik Laskowski075d3172018-05-24 15:50:06 -0700857 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800858 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700859
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800860 auto width = hwConfig->getWidth();
861 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700862
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800863 auto xDpi = hwConfig->getDpiX();
864 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700865
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800866 if (isInternal &&
867 (internalDisplayOrientation == ui::ROTATION_90 ||
868 internalDisplayOrientation == ui::ROTATION_270)) {
869 std::swap(width, height);
870 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700871 }
872
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800873 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800874
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800875 if (mEmulatedDisplayDensity) {
876 config.xDpi = mEmulatedDisplayDensity;
877 config.yDpi = mEmulatedDisplayDensity;
878 } else {
879 config.xDpi = xDpi;
880 config.yDpi = yDpi;
881 }
882
883 const nsecs_t period = hwConfig->getVsyncPeriod();
884 config.refreshRate = 1e9f / period;
885
886 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
887 config.appVsyncOffset = offsets.late.app;
888 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800889 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890
Andy McFadden91b2ca82014-06-13 14:04:23 -0700891 // This is how far in advance a buffer must be queued for
892 // presentation at a given time. If you want a buffer to appear
893 // on the screen at time N, you must submit the buffer before
894 // (N - presentationDeadline).
895 //
896 // Normally it's one full refresh period (to give SF a chance to
897 // latch the buffer), but this can be reduced by configuring a
898 // DispSync offset. Any additional delays introduced by the hardware
899 // composer or panel must be accounted for here.
900 //
901 // We add an additional 1ms to allow for processing time and
902 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800903 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700904
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800905 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700906 }
907
Dan Stoza7f7da322014-05-02 15:26:25 -0700908 return NO_ERROR;
909}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700910
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700911status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
912 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700913 return BAD_VALUE;
914 }
915
Ana Krulecc2870422019-01-29 19:00:58 -0800916 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700917 return NO_ERROR;
918}
919
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700920int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700921 int activeConfig;
922 bool isPrimary;
923
924 {
925 Mutex::Autolock lock(mStateLock);
926
927 if (const auto display = getDisplayDeviceLocked(displayToken)) {
928 activeConfig = display->getActiveConfig().value();
929 isPrimary = display->isPrimary();
930 } else {
931 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
932 return NAME_NOT_FOUND;
933 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800934 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700935
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700936 if (isPrimary) {
Steven Thomasc9098452019-09-30 17:15:05 -0700937 std::lock_guard<std::mutex> lock(mActiveConfigLock);
938 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800939 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700940 }
Steven Thomasc9098452019-09-30 17:15:05 -0700941 }
Ady Abraham2139f732019-11-13 18:56:40 -0800942
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700943 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700944}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700945
Ady Abraham03b02dd2019-03-21 15:40:11 -0700946void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800947 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800948 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700949 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800950
Ady Abrahamb838aed2019-02-12 15:30:16 -0800951 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800952 if (mDesiredActiveConfigChanged) {
953 // If a config change is pending, just cache the latest request in
954 // mDesiredActiveConfig
955 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
956 mDesiredActiveConfig = info;
957 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
958 } else {
959 // Check is we are already at the desired config
960 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700961 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800962 return;
963 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800964
Ady Abraham59db0a32020-03-02 18:04:20 -0800965 // Initiate a config change.
966 mDesiredActiveConfigChanged = true;
967 mDesiredActiveConfig = info;
968
Ady Abrahamb838aed2019-02-12 15:30:16 -0800969 // This will trigger HWC refresh without resetting the idle timer.
970 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700971 // Start receiving vsync samples now, so that we can detect a period
972 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700973 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700974 // As we called to set period, we will call to onRefreshRateChangeCompleted once
975 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700976 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800977
Ady Abrahamabc27602020-04-08 17:20:29 -0700978 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800979 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700981
982 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800983 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700984 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985}
986
987status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
988 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800989
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100990 if (!displayToken) {
991 return BAD_VALUE;
992 }
Ady Abraham838de062019-02-04 10:24:03 -0800993
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700994 auto future = schedule([=]() -> status_t {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100995 const auto display = getDisplayDeviceLocked(displayToken);
996 if (!display) {
997 ALOGE("Attempt to set allowed display configs for invalid display token %p",
998 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700999 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001000 } else if (display->isVirtual()) {
1001 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001002 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001003 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001004 const HwcConfigIndexType config(mode);
1005 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
1006 const scheduler::RefreshRateConfigs::Policy policy{config, fps, fps};
1007 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001008
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001009 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1010 }
1011 });
1012
1013 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001014}
1015
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001016void SurfaceFlinger::setActiveConfigInternal() {
1017 ATRACE_CALL();
1018
Dominik Laskowski22488f62019-03-28 09:53:04 -07001019 const auto display = getDefaultDisplayDeviceLocked();
1020 if (!display) {
1021 return;
1022 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001023
Alec Mouri8de697e2020-03-19 10:52:01 -07001024 auto& oldRefreshRate =
1025 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1026
Dominik Laskowski22488f62019-03-28 09:53:04 -07001027 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001028 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001029 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001030 display->setActiveConfig(mUpcomingActiveConfig.configId);
1031
Ady Abraham2e1dd892020-03-05 13:48:36 -08001032 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001033 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001034 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001035 mTimeStats->incrementRefreshRateSwitches();
1036 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001037 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001038 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001039 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001040
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001041 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001042 const nsecs_t vsyncPeriod =
1043 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001044 .getVsyncPeriod();
Ady Abraham447052e2019-02-13 16:07:27 -08001045 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001046 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001047 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001048}
1049
Ady Abraham53852a52019-05-28 18:07:44 -07001050void SurfaceFlinger::desiredActiveConfigChangeDone() {
1051 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1052 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1053 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001054
Ady Abraham2e1dd892020-03-05 13:48:36 -08001055 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001056 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001057 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1058 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001059 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001060}
1061
Ady Abraham27cbed72020-04-10 12:56:59 -07001062void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001063 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001064 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001065 // Store the local variable to release the lock.
Ady Abraham27cbed72020-04-10 12:56:59 -07001066 const auto desiredActiveConfig = [&]() -> std::optional<ActiveConfigInfo> {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001067 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham27cbed72020-04-10 12:56:59 -07001068 if (mDesiredActiveConfigChanged) {
1069 return mDesiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001070 }
Ady Abraham27cbed72020-04-10 12:56:59 -07001071 return std::nullopt;
1072 }();
1073
1074 if (!desiredActiveConfig) {
1075 // No desired active config pending to be applied
1076 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001077 }
1078
Ady Abraham2e1dd892020-03-05 13:48:36 -08001079 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001080 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001081 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1082 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001083 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001084 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001085 // display is not valid or we are already in the requested mode
1086 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001087 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001088 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001089 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001090
Ady Abraham838de062019-02-04 10:24:03 -08001091 // Desired active config was set, it is different than the config currently in use, however
1092 // allowed configs might have change by the time we process the refresh.
1093 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001094 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001095 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001096 return;
Ady Abraham838de062019-02-04 10:24:03 -08001097 }
Alec Mouri7f015182019-07-11 13:56:22 -07001098
Ady Abraham27cbed72020-04-10 12:56:59 -07001099 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001100 const auto displayId = display->getId();
1101 LOG_ALWAYS_FATAL_IF(!displayId);
1102
Ady Abrahamabc27602020-04-08 17:20:29 -07001103 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001104
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001105 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001106 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001107 constraints.desiredTimeNanos = systemTime();
1108 constraints.seamlessRequired = false;
1109
Peiyong Line9d809e2020-04-14 13:10:48 -07001110 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001111 auto status =
1112 getHwComposer().setActiveConfigWithConstraints(*displayId,
1113 mUpcomingActiveConfig.configId.value(),
1114 constraints, &outTimeline);
1115 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001116 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1117 // to be sent. We just log the error in this case.
1118 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001119 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001120 }
1121
1122 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1123 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001124 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001125}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001126
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001127status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1128 Vector<ColorMode>* outColorModes) {
1129 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001130 return BAD_VALUE;
1131 }
1132
Peiyong Lina52f0292018-03-14 17:26:31 -07001133 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001134 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001135 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001136 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1137
1138 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1139 if (!displayId) {
1140 return NAME_NOT_FOUND;
1141 }
1142
Dominik Laskowski075d3172018-05-24 15:50:06 -07001143 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001144 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001145 }
Michael Wright28f24d02016-07-12 13:30:53 -07001146 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001147
1148 // If it's built-in display and the configuration claims it's not wide color capable,
1149 // filter out all wide color modes. The typical reason why this happens is that the
1150 // hardware is not good enough to support GPU composition of wide color, and thus the
1151 // OEMs choose to disable this capability.
1152 if (isInternalDisplay && !hasWideColorDisplay) {
1153 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1154 isWideColorMode);
1155 } else {
1156 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1157 }
Michael Wright28f24d02016-07-12 13:30:53 -07001158
1159 return NO_ERROR;
1160}
1161
Daniel Solomon42d04562019-01-20 21:03:19 -08001162status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1163 ui::DisplayPrimaries &primaries) {
1164 if (!displayToken) {
1165 return BAD_VALUE;
1166 }
1167
1168 // Currently we only support this API for a single internal display.
1169 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001170 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001171 }
1172
1173 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1174 return NO_ERROR;
1175}
1176
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001177ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001178 Mutex::Autolock lock(mStateLock);
1179
1180 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001181 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001182 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001183 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001184}
1185
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001186status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001187 schedule([=] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001188 Vector<ColorMode> modes;
1189 getDisplayColorModes(displayToken, &modes);
1190 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1191 if (mode < ColorMode::NATIVE || !exists) {
1192 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1193 decodeColorMode(mode).c_str(), mode, displayToken.get());
1194 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001195 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001196 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001197 if (!display) {
1198 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1199 decodeColorMode(mode).c_str(), mode, displayToken.get());
1200 } else if (display->isVirtual()) {
1201 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1202 decodeColorMode(mode).c_str(), mode);
1203 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001204 display->getCompositionDisplay()->setColorProfile(
1205 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1206 RenderIntent::COLORIMETRIC,
1207 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001208 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001209 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001210
Michael Wright28f24d02016-07-12 13:30:53 -07001211 return NO_ERROR;
1212}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001213
Galia Peycheva5492cb52019-10-30 14:13:16 +01001214status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1215 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001216 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001217 return BAD_VALUE;
1218 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001219
1220 Mutex::Autolock lock(mStateLock);
1221
Galia Peycheva5492cb52019-10-30 14:13:16 +01001222 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1223 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001224 return NAME_NOT_FOUND;
1225 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001226 *outSupport =
1227 getHwComposer().hasDisplayCapability(*displayId,
1228 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001229 return NO_ERROR;
1230}
1231
1232void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001233 static_cast<void>(schedule([=] {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001234 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1235 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1236 } else {
1237 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1238 }
1239 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001240}
1241
1242status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1243 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001244 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001245 return BAD_VALUE;
1246 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001247
1248 Mutex::Autolock lock(mStateLock);
1249
Galia Peycheva5492cb52019-10-30 14:13:16 +01001250 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1251 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001252 return NAME_NOT_FOUND;
1253 }
1254
Peiyong Line9d809e2020-04-14 13:10:48 -07001255 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001256 getHwComposer().getSupportedContentTypes(*displayId, &types);
1257
1258 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001259 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001260 return NO_ERROR;
1261}
1262
1263void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001264 static_cast<void>(schedule([=] {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001265 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001266 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001267 getHwComposer().setContentType(*displayId, type);
1268 } else {
1269 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1270 }
1271 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001272}
1273
Svetoslavd85084b2014-03-20 10:28:31 -07001274status_t SurfaceFlinger::clearAnimationFrameStats() {
1275 Mutex::Autolock _l(mStateLock);
1276 mAnimFrameTracker.clearStats();
1277 return NO_ERROR;
1278}
1279
1280status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1281 Mutex::Autolock _l(mStateLock);
1282 mAnimFrameTracker.getStats(outStats);
1283 return NO_ERROR;
1284}
1285
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001286status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1287 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001288 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001289
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001290 const auto display = getDisplayDeviceLocked(displayToken);
1291 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001292 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1293 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001294 }
1295
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001296 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001297 // meaning the luminance information is already queried from
1298 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001299 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001300 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1301 capabilities.getDesiredMaxLuminance(),
1302 capabilities.getDesiredMaxAverageLuminance(),
1303 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001304
1305 return NO_ERROR;
1306}
1307
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001308std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1309 const DisplayDevice& display) const {
1310 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1311 // avoid repetitive HAL IPC and EDID parsing.
1312 const auto displayId = display.getId();
1313 LOG_FATAL_IF(!displayId);
1314
1315 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1316 LOG_FATAL_IF(!hwcDisplayId);
1317
1318 uint8_t port;
1319 DisplayIdentificationData data;
1320 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1321 ALOGV("%s: No identification data.", __FUNCTION__);
1322 return {};
1323 }
1324
1325 const auto info = parseDisplayIdentificationData(port, data);
1326 if (!info) {
1327 return {};
1328 }
1329 return info->deviceProductInfo;
1330}
1331
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001332status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1333 ui::PixelFormat* outFormat,
1334 ui::Dataspace* outDataspace,
1335 uint8_t* outComponentMask) const {
1336 if (!outFormat || !outDataspace || !outComponentMask) {
1337 return BAD_VALUE;
1338 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001339
1340 Mutex::Autolock lock(mStateLock);
1341
1342 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1343 if (!displayId) {
1344 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001345 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001346
1347 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001348 outDataspace, outComponentMask);
1349}
1350
Kevin DuBois74e53772018-11-19 10:52:38 -08001351status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1352 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001353 uint64_t maxFrames) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001354 return schedule([=]() -> status_t {
1355 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1356 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1357 componentMask,
1358 maxFrames);
1359 } else {
1360 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1361 return NAME_NOT_FOUND;
1362 }
1363 })
1364 .get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001365}
1366
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001367status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1368 uint64_t maxFrames, uint64_t timestamp,
1369 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001370 Mutex::Autolock lock(mStateLock);
1371
1372 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1373 if (!displayId) {
1374 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001375 }
1376
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001377 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001378}
1379
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001380status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1381 if (!outSupported) {
1382 return BAD_VALUE;
1383 }
1384 *outSupported = getRenderEngine().supportsProtectedContent();
1385 return NO_ERROR;
1386}
1387
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001388status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1389 bool* outIsWideColorDisplay) const {
1390 if (!displayToken || !outIsWideColorDisplay) {
1391 return BAD_VALUE;
1392 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001393
1394 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001395 const auto display = getDisplayDeviceLocked(displayToken);
1396 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001397 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001398 }
Peiyong Linff84a152019-05-17 18:36:19 -07001399
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001400 *outIsWideColorDisplay =
1401 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001402 return NO_ERROR;
1403}
1404
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001405status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001406 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001407 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001408
Dominik Laskowski6505f792019-09-18 11:10:05 -07001409 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1410 mEventQueue->setEventConnection(
1411 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001412 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001413 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001414
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001415 return NO_ERROR;
1416}
1417
1418status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001419 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001420 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001421}
1422
Lloyd Pique755e3192018-01-31 16:46:15 -08001423status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1424 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001425 // Try to acquire a lock for 1s, fail gracefully
1426 const status_t err = mStateLock.timedLock(s2ns(1));
1427 const bool locked = (err == NO_ERROR);
1428 if (!locked) {
1429 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1430 return TIMED_OUT;
1431 }
1432
1433 outLayers->clear();
1434 mCurrentState.traverseInZOrder([&](Layer* layer) {
1435 outLayers->push_back(layer->getLayerDebugInfo());
1436 });
1437
1438 mStateLock.unlock();
1439 return NO_ERROR;
1440}
1441
Peiyong Linc6780972018-10-28 15:24:08 -07001442status_t SurfaceFlinger::getCompositionPreference(
1443 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1444 Dataspace* outWideColorGamutDataspace,
1445 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001446 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001447 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001448 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001449 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001450 return NO_ERROR;
1451}
1452
Dan Stozaec460082018-12-17 15:35:09 -08001453status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1454 const sp<IBinder>& stopLayerHandle,
1455 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001456 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001457 return BAD_VALUE;
1458 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001459
1460 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1461 mRegionSamplingThread->addListener(samplingArea, stopLayer, 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
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001495 return promise::chain(schedule([=] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001496 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1497 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1498 } else {
1499 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001500 return promise::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001501 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001502 }))
1503 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001504 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001505}
1506
Ady Abraham8532d012019-05-08 14:50:56 -07001507status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1508 PowerHint powerHint = static_cast<PowerHint>(hintId);
1509
1510 if (powerHint == PowerHint::INTERACTION) {
1511 mScheduler->notifyTouchEvent();
1512 }
1513
1514 return NO_ERROR;
1515}
1516
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001517// ----------------------------------------------------------------------------
1518
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001519sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001520 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001521 const auto& handle =
1522 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001523
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001524 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001525}
1526
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001527void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001528 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001529 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001530 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001531}
1532
1533void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001534 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001535 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001536 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001537}
1538
1539void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001540 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001541 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001542}
1543
Dominik Laskowski83b88212018-12-11 13:34:06 -08001544nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001545 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001546 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1547 return 0;
1548 }
1549
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001550 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001551}
1552
Peiyong Line9d809e2020-04-14 13:10:48 -07001553void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001554 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001555 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001556 ATRACE_NAME("SF onVsync");
1557
Steven Thomas3cfac282017-02-06 12:29:30 -08001558 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001559 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001560 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001561 return;
1562 }
1563
Dominik Laskowski075d3172018-05-24 15:50:06 -07001564 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001565 return;
1566 }
1567
Dominik Laskowski075d3172018-05-24 15:50:06 -07001568 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001569 // For now, we don't do anything with external display vsyncs.
1570 return;
1571 }
1572
Alec Mourif8e689c2019-05-20 18:32:22 -07001573 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001574 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001575 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001576 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001577 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001578}
1579
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001580void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001581 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1582 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001583}
1584
Ady Abraham2139f732019-11-13 18:56:40 -08001585bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001586 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001587}
1588
Ady Abraham2139f732019-11-13 18:56:40 -08001589void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1590 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001591 const auto display = getDefaultDisplayDeviceLocked();
1592 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001593 return;
1594 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001595 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001596
Ana Krulec7d1d6832018-12-27 11:10:09 -08001597 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001598 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001599 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001600 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001601 return;
1602 }
1603
Ady Abrahamabc27602020-04-08 17:20:29 -07001604 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001605}
1606
Peiyong Line9d809e2020-04-14 13:10:48 -07001607void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
1608 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001609 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001610 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001611
Lloyd Piqueba04e622017-12-14 17:11:26 -08001612 // Ignore events that do not have the right sequenceId.
1613 if (sequenceId != getBE().mComposerSequenceId) {
1614 return;
1615 }
1616
Steven Thomasb02664d2017-07-26 18:48:28 -07001617 // Only lock if we're not on the main thread. This function is normally
1618 // called on a hwbinder thread, but for the primary display it's called on
1619 // the main thread with the state lock already held, so don't attempt to
1620 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001621 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001622
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001623 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001624
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001625 if (std::this_thread::get_id() == mMainThreadId) {
1626 // Process all pending hot plug events immediately if we are on the main thread.
1627 processDisplayHotplugEventsLocked();
1628 }
1629
Lloyd Piqueba04e622017-12-14 17:11:26 -08001630 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001631}
1632
Ady Abraham7159f572019-10-11 11:10:18 -07001633void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001634 int32_t sequenceId, hal::HWDisplayId /*display*/,
1635 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001636 Mutex::Autolock lock(mStateLock);
1637 if (sequenceId != getBE().mComposerSequenceId) {
1638 return;
1639 }
1640 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001641}
1642
Peiyong Line9d809e2020-04-14 13:10:48 -07001643void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001644 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1645 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1646}
1647
Peiyong Line9d809e2020-04-14 13:10:48 -07001648void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001649 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001650 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001651 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001652 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001653 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001654}
1655
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001656void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001657 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001658
1659 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1660 // display power state.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001661 static_cast<void>(
1662 schedule([=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001663}
1664
1665void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1666 ATRACE_CALL();
1667
Peiyong Line9d809e2020-04-14 13:10:48 -07001668 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001669
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001670 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001671 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1672 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001673 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001674 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001675 }
Mathias Agopian86303202012-07-24 22:46:10 -07001676}
1677
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001678// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001679void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001680 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001681 // Clear the drawing state so that the logic inside of
1682 // handleTransactionLocked will fire. It will determine the delta between
1683 // mCurrentState and mDrawingState and re-apply all changes when we make the
1684 // transition.
1685 mDrawingState.displays.clear();
1686 mDisplays.clear();
1687}
1688
Steven Thomas050b2c82017-03-06 11:45:16 -08001689void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001690 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001691 if (!mVrFlinger)
1692 return;
1693 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001694 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001695 return;
1696 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001697
Lloyd Pique441d5042018-10-18 16:49:51 -07001698 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001699 ALOGE("Vr flinger is only supported for remote hardware composer"
1700 " service connections. Ignoring request to transition to vr"
1701 " flinger.");
1702 mVrFlingerRequestsDisplay = false;
1703 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001704 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001705
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001706 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001707
Steven Thomas0123ac62018-07-12 11:32:34 -07001708 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001709 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001710
Peiyong Lin65248e02020-04-18 21:15:07 -07001711 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001712
1713 // Clear out all the output layers from the composition engine for all
1714 // displays before destroying the hardware composer interface. This ensures
1715 // any HWC layers are destroyed through that interface before it becomes
1716 // invalid.
1717 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001718 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001719 }
1720
Steven Thomas0123ac62018-07-12 11:32:34 -07001721 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1722 // called below. Clear the reference now so we don't accidentally use it
1723 // later.
1724 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001725
Steven Thomasb02664d2017-07-26 18:48:28 -07001726 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001727 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001728 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001729
Steven Thomasb02664d2017-07-26 18:48:28 -07001730 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001731 // Delete the current instance before creating the new one
1732 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1733 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1734 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001735 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001736
Lloyd Pique441d5042018-10-18 16:49:51 -07001737 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001738 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001739
1740 if (vrFlingerRequestsDisplay) {
1741 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001742 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001743
1744 mVisibleRegionsDirty = true;
1745 invalidateHwcGeometry();
1746
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001747 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001748 display = getDefaultDisplayDeviceLocked();
1749 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001750 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001751
Steven Thomasb02664d2017-07-26 18:48:28 -07001752 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001753 const nsecs_t vsyncPeriod = getVsyncPeriod();
1754 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001755
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001756 // The present fences returned from vr_hwc are not an accurate
1757 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001758 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001759
Steven Thomasb02664d2017-07-26 18:48:28 -07001760 // Use phase of 0 since phase is not known.
1761 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001762 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001763 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001764
Ana Krulecc2870422019-01-29 19:00:58 -08001765 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001766
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001767 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001768 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001769}
1770
Alec Mouri6d414b52020-03-17 11:18:05 -07001771sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001772 // We are storing the last 2 present fences. If sf's phase offset is to be
1773 // woken up before the actual vsync but targeting the next vsync, we need to check
1774 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001775 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1776 : mPreviousPresentFences[1];
1777}
1778
1779bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1780 ATRACE_CALL();
1781 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001782
Ady Abraham11579302019-09-19 12:35:58 -07001783 if (fence == Fence::NO_FENCE) {
1784 return false;
1785 }
1786
1787 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1788 fence->wait(graceTimeMs);
1789 }
1790
1791 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001792}
1793
Alec Mouri6d414b52020-03-17 11:18:05 -07001794nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1795 const sp<Fence>& fence = previousFrameFence();
1796
1797 if (fence == Fence::NO_FENCE) {
1798 return Fence::SIGNAL_TIME_INVALID;
1799 }
1800
1801 return fence->getSignalTime();
1802}
1803
Ady Abraham5facfb12020-04-22 15:18:31 -07001804nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001805 DisplayStatInfo stats;
1806 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001807 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001808 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001809 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001810}
1811
Ady Abraham5facfb12020-04-22 15:18:31 -07001812void SurfaceFlinger::onMessageReceived(int32_t what,
1813 nsecs_t expectedVSyncTime) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001814 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001815 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001816 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001817 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001818 // calculate the expected present time once and use the cached
1819 // value throughout this frame to make sure all layers are
1820 // seeing this same value.
Alec Mouri6d414b52020-03-17 11:18:05 -07001821 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
Ady Abraham5facfb12020-04-22 15:18:31 -07001822 mExpectedPresentTime = expectedVSyncTime;
Ady Abraham7c03ce62019-07-19 10:59:45 -07001823
Ady Abraham11579302019-09-19 12:35:58 -07001824 // When Backpressure propagation is enabled we want to give a small grace period
1825 // for the present fence to fire instead of just giving up on this frame to handle cases
1826 // where present fence is just about to get signaled.
1827 const int graceTimeForPresentFenceMs =
1828 (mPropagateBackpressure &&
1829 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1830 ? 1
1831 : 0;
Alec Mouri6d414b52020-03-17 11:18:05 -07001832
1833 // Pending frames may trigger backpressure propagation.
1834 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1835 previousFramePending(
1836 graceTimeForPresentFenceMs)};
1837
1838 // Frame missed counts for metrics tracking.
1839 // A frame is missed if the prior frame is still pending. If no longer pending,
1840 // then we still count the frame as missed if the predicted present time
1841 // was further in the past than when the fence actually fired.
1842
1843 // Add some slop to correct for drift. This should generally be
1844 // smaller than a typical frame duration, but should not be so small
1845 // that it reports reasonable drift as a missed frame.
1846 DisplayStatInfo stats;
1847 mScheduler->getDisplayStatInfo(&stats);
1848 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1849 const nsecs_t previousPresentTime = previousFramePresentTime();
1850 const TracedOrdinal<bool> frameMissed =
1851 {"PrevFrameMissed",
1852 framePending ||
1853 (previousPresentTime >= 0 &&
1854 (lastExpectedPresentTime < previousPresentTime - frameMissedSlop))};
1855 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001856 mHadDeviceComposition && frameMissed};
Alec Mouri6d414b52020-03-17 11:18:05 -07001857 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001858 mHadClientComposition && frameMissed};
1859
Alec Mouricc0fc602019-02-26 21:45:19 -08001860 if (frameMissed) {
1861 mFrameMissedCount++;
1862 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001863 if (mMissedFrameJankCount == 0) {
1864 mMissedFrameJankStart = systemTime();
1865 }
1866 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001867 }
1868
Alec Mouri40189b02019-03-05 15:07:54 -08001869 if (hwcFrameMissed) {
1870 mHwcFrameMissedCount++;
1871 }
1872
1873 if (gpuFrameMissed) {
1874 mGpuFrameMissedCount++;
1875 }
1876
Ady Abraham27cbed72020-04-10 12:56:59 -07001877 // If we are in the middle of a config change and the fence hasn't
1878 // fired yet just wait for the next invalidate
1879 if (mSetActiveConfigPending) {
1880 if (framePending) {
1881 mEventQueue->invalidate();
1882 break;
1883 }
1884
1885 // We received the present fence from the HWC, so we assume it successfully updated
1886 // the config, hence we update SF.
1887 mSetActiveConfigPending = false;
1888 setActiveConfigInternal();
1889 }
1890
Alec Mouri6d414b52020-03-17 11:18:05 -07001891 if (framePending && mPropagateBackpressure) {
Ady Abrahamadb9a992019-09-19 21:21:55 +00001892 if ((hwcFrameMissed && !gpuFrameMissed) ||
1893 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001894 signalLayerUpdate();
1895 break;
1896 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001897 }
Dan Stoza50182882016-07-08 12:02:20 -07001898
Alec Mouri989ddbe2020-02-06 09:26:19 -08001899 // Our jank window is always at least 100ms since we missed a
1900 // frame...
1901 static constexpr nsecs_t kMinJankyDuration =
1902 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1903 // ...but if it's larger than 1s then we missed the trace cutoff.
1904 static constexpr nsecs_t kMaxJankyDuration =
1905 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1906 // If we're in a user build then don't push any atoms
1907 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1908 const auto displayDevice = getDefaultDisplayDeviceLocked();
1909 // Only report jank when the display is on, as displays in DOZE
1910 // power mode may operate at a different frame rate than is
1911 // reported in their config, which causes noticeable (but less
1912 // severe) jank.
Peiyong Lin65248e02020-04-18 21:15:07 -07001913 if (displayDevice && displayDevice->getPowerMode() == hal::PowerMode::ON) {
Alec Mouri989ddbe2020-02-06 09:26:19 -08001914 const nsecs_t currentTime = systemTime();
1915 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1916 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1917 ATRACE_NAME("Jank detected");
1918 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1919 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1920 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1921 jankyDurationMillis, mMissedFrameJankCount);
1922 }
1923
1924 // We either reported a jank event or we missed the trace
1925 // window, so clear counters here.
1926 if (jankDuration > kMinJankyDuration) {
1927 mMissedFrameJankCount = 0;
1928 mMissedFrameJankStart = 0;
1929 }
1930 }
1931 }
1932
Steven Thomas050b2c82017-03-06 11:45:16 -08001933 // Now that we're going to make it to the handleMessageTransaction()
1934 // call below it's safe to call updateVrFlinger(), which will
1935 // potentially trigger a display handoff.
1936 updateVrFlinger();
1937
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001938 if (mTracingEnabledChanged) {
1939 mTracingEnabled = mTracing.isEnabled();
1940 mTracingEnabledChanged = false;
1941 }
1942
Vishnu Nair60db8c02020-04-02 11:55:16 -07001943 bool refreshNeeded;
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001944 {
1945 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1946
Vishnu Nair60db8c02020-04-02 11:55:16 -07001947 refreshNeeded = handleMessageTransaction();
1948 refreshNeeded |= handleMessageInvalidate();
1949 if (mTracingEnabled) {
1950 mAddCompositionStateToTrace =
1951 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1952 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1953 mTracing.notifyLocked("visibleRegionsDirty");
1954 }
1955 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001956 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001957
Ana Krulecc84d09b2019-11-02 23:10:29 +01001958 // Layers need to get updated (in the previous line) before we can use them for
1959 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001960 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1961 // and may eventually call to ~Layer() if it holds the last reference
1962 {
1963 Mutex::Autolock _l(mStateLock);
1964 mScheduler->chooseRefreshRateForContent();
1965 }
1966
Ady Abraham27cbed72020-04-10 12:56:59 -07001967 performSetActiveConfig();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001968
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001969 updateCursorAsync();
1970 updateInputFlinger();
1971
Dan Stoza58784442014-12-02 16:58:17 -08001972 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001973 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001974 // Signal a refresh if a transaction modified the window state,
1975 // a new buffer was latched, or if HWC has requested a full
1976 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001977 if (mFrameStartTime <= 0) {
1978 // We should only use the time of the first invalidate
1979 // message that signals a refresh as the beginning of the
1980 // frame. Otherwise the real frame time will be
1981 // underestimated.
1982 mFrameStartTime = frameStart;
1983 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001984 signalRefresh();
1985 }
1986 break;
1987 }
1988 case MessageQueue::REFRESH: {
1989 handleMessageRefresh();
1990 break;
1991 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001992 }
1993}
1994
Dan Stoza6b9454d2014-11-07 16:00:59 -08001995bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001996 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001997 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001998
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001999 bool flushedATransaction = flushTransactionQueues();
2000
2001 bool runHandleTransaction = transactionFlags &&
2002 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
2003
2004 if (runHandleTransaction) {
2005 handleTransaction(eTransactionMask);
2006 } else {
2007 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002008 }
2009
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002010 if (transactionFlushNeeded()) {
2011 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002012 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002013
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002014 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002015}
2016
Mathias Agopian4fec8732012-06-29 14:12:52 -07002017void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002018 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002019
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002020 mRefreshPending = false;
2021
Lloyd Piqueab039b52019-02-13 14:22:42 -08002022 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002023 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002024 for (const auto& [_, display] : mDisplays) {
2025 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2026 }
2027 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002028 if (auto layerFE = layer->getCompositionEngineLayerFE())
2029 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002030 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002031 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2032 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002033 if (auto layerFE = layer->getCompositionEngineLayerFE())
2034 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002035 }
2036
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002037 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002038 refreshArgs.outputColorSetting = useColorManagement
2039 ? mDisplayColorSetting
2040 : compositionengine::OutputColorSetting::kUnmanaged;
2041 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2042 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002043
2044 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2045 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002046 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002047
2048 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2049 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2050 mDrawingState.colorMatrixChanged = false;
2051 }
2052
2053 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2054
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002055 if (mDebugRegion != 0) {
2056 refreshArgs.devOptFlashDirtyRegionsDelay =
2057 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2058 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002059
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002060 mGeometryInvalid = false;
2061
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002062 // Store the present time just before calling to the composition engine so we could notify
2063 // the scheduler.
2064 const auto presentTime = systemTime();
2065
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002066 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002067 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2068 // Reset the frame start time now that we've recorded this frame.
2069 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002070
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002071 mScheduler->onDisplayRefreshed(presentTime);
2072
David Sodmanfa9b2af2017-12-24 13:28:59 -08002073 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002074 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002075
Alec Mouri8f7a0102020-04-15 12:11:10 -07002076 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2077
Lloyd Pique66d68602019-02-13 14:23:31 -08002078 mHadClientComposition =
2079 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2080 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002081 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2082 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002083 });
2084 mHadDeviceComposition =
2085 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2086 auto& displayDevice = tokenDisplayPair.second;
2087 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2088 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002089 mReusedClientComposition =
2090 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2091 auto& displayDevice = tokenDisplayPair.second;
2092 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2093 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002094
Alec Mouri8f7a0102020-04-15 12:11:10 -07002095 // Only report a strategy change if we move in and out of composition with hw overlays
2096 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2097 mTimeStats->incrementCompositionStrategyChanges();
2098 }
2099
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002100 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002101
David Sodman7e4ae112018-02-09 15:02:28 -08002102 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002103 if (mVisibleRegionsDirty) {
2104 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002105 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002106 mTracing.notify("visibleRegionsDirty");
2107 }
2108 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002109
2110 if (mCompositionEngine->needsAnotherUpdate()) {
2111 signalLayerUpdate();
2112 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002113}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002114
David Sodmanfa9b2af2017-12-24 13:28:59 -08002115
2116bool SurfaceFlinger::handleMessageInvalidate() {
2117 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002118 bool refreshNeeded = handlePageFlip();
2119
Vishnu Nair4351ad52019-02-11 14:13:02 -08002120 if (mVisibleRegionsDirty) {
2121 computeLayerBounds();
2122 }
2123
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002124 for (auto& layer : mLayersPendingRefresh) {
2125 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002126 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002127 invalidateLayerStack(layer, visibleReg);
2128 }
2129 mLayersPendingRefresh.clear();
2130 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002131}
2132
Ana Krulece588e312018-09-18 12:32:24 -07002133void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2134 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002135 // Update queue of past composite+present times and determine the
2136 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002137 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002138 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002139 while (!getBE().mCompositePresentTimes.empty()) {
2140 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002141 // Cached values should have been updated before calling this method,
2142 // which helps avoid duplicate syscalls.
2143 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2144 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2145 break;
2146 }
2147 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002148 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002149 }
2150
2151 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002152 while (getBE().mCompositePresentTimes.size() > 16) {
2153 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002154 }
2155
Ana Krulece588e312018-09-18 12:32:24 -07002156 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002157}
2158
Ana Krulece588e312018-09-18 12:32:24 -07002159void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2160 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002161 // Integer division and modulo round toward 0 not -inf, so we need to
2162 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002163 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2164 ? (stats.vsyncPeriod -
2165 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2166 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002167
Ady Abraham9e16a482019-12-03 17:19:41 -08002168 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002169 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002170 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002171 }
2172
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002173 // Snap the latency to a value that removes scheduling jitter from the
2174 // composition and present times, which often have >1ms of jitter.
2175 // Reducing jitter is important if an app attempts to extrapolate
2176 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002177 // Snapping also allows an app to precisely calculate
2178 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002179 nsecs_t bias = stats.vsyncPeriod / 2;
2180 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2181 nsecs_t snappedCompositeToPresentLatency =
2182 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002183
David Sodman99974d22017-11-28 12:04:33 -08002184 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002185 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2186 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002187 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002188}
2189
David Sodman2b406362017-12-15 13:33:47 -08002190void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002191{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002192 ATRACE_CALL();
2193 ALOGV("postComposition");
2194
Brian Andersonf6386862016-10-31 16:34:13 -07002195 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002196 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002197 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002198 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002199 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002200 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002201
David Sodman73beded2017-11-15 11:56:06 -08002202 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002203 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002204 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002205 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002206 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2207 ->getRenderSurface()
2208 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002209 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002210 } else {
2211 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2212 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002213
David Sodman73beded2017-11-15 11:56:06 -08002214 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002215 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2216 mPreviousPresentFences[0] = displayDevice
2217 ? getHwComposer().getPresentFence(*displayDevice->getId())
2218 : Fence::NO_FENCE;
2219 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002220 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002221
Ana Krulece588e312018-09-18 12:32:24 -07002222 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002223 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002224
Lloyd Piqueab039b52019-02-13 14:22:42 -08002225 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2226 // be sampled a little later than when we started doing work for this frame,
2227 // but that should be okay since updateCompositorTiming has snapping logic.
2228 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2229 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002230 CompositorTiming compositorTiming;
2231 {
David Sodman99974d22017-11-28 12:04:33 -08002232 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2233 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002234 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002235
Edgar Arriaga844fa672020-01-16 14:21:42 -08002236 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002237 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2238 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002239 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002240 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002241 }
Robert Carr2047fae2016-11-28 14:09:09 -08002242 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002243
Valerie Hau4b678442020-04-14 10:50:42 -07002244 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2245 mTransactionCompletedThread.sendCallbacks();
2246
Ady Abraham92fa2f42020-02-11 15:33:56 -08002247 if (displayDevice && displayDevice->isPrimary() &&
Peiyong Lin65248e02020-04-18 21:15:07 -07002248 displayDevice->getPowerMode() == hal::PowerMode::ON && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002249 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002250 }
2251
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002252 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002253 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2254 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002255 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002256 }
2257 }
2258
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002259 if (mAnimCompositionPending) {
2260 mAnimCompositionPending = false;
2261
Brian Anderson4e606e32017-03-16 15:34:57 -07002262 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002263 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002264 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002265 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002266 // The HWC doesn't support present fences, so use the refresh
2267 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002268 const nsecs_t presentTime =
2269 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002270 mAnimFrameTracker.setActualPresentTime(presentTime);
2271 }
2272 mAnimFrameTracker.advanceFrame();
2273 }
Dan Stozab90cf072015-03-05 11:05:59 -08002274
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002275 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002276 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002277 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002278 }
2279
Vishnu Nair9b079a22020-01-21 14:36:08 -08002280 if (mReusedClientComposition) {
2281 mTimeStats->incrementClientCompositionReusedFrames();
2282 }
2283
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002284 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002285
Alec Mouri717bcb62020-02-10 17:07:19 -08002286 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2287 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2288 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2289
Lloyd Pique32cbe282018-10-19 13:09:22 -07002290 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2291 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002292 return;
2293 }
2294
2295 nsecs_t currentTime = systemTime();
2296 if (mHasPoweredOff) {
2297 mHasPoweredOff = false;
2298 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002299 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002300 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002301 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2302 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002303 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002304 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002305 }
David Sodman4a36e932017-11-07 14:29:47 -08002306 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002307 }
David Sodman4a36e932017-11-07 14:29:47 -08002308 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002309
Alec Mouri4dde1782019-09-30 17:27:13 -07002310 // Cleanup any outstanding resources due to rendering a prior frame.
2311 getRenderEngine().cleanupPostRender();
2312
Dan Stoza436ccf32018-06-21 12:10:12 -07002313 {
2314 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002315 if (mTexturePool.size() < mTexturePoolSize) {
2316 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002317 const size_t offset = mTexturePool.size();
2318 mTexturePool.resize(mTexturePoolSize);
2319 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2320 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002321 } else if (mTexturePool.size() > mTexturePoolSize) {
2322 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2323 const size_t offset = mTexturePoolSize;
2324 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2325 mTexturePool.resize(mTexturePoolSize);
2326 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002327 }
2328 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002329
Kevin DuBois413287f2019-02-25 08:46:47 -08002330 if (mLumaSampling && mRegionSamplingThread) {
2331 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002332 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002333
2334 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2335 // side-effect of getTotalSize(), so we check that again here
2336 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002337 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002338 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2339 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002340}
2341
Lloyd Pique7eebe692020-04-22 22:40:06 -07002342FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2343 return displayDevice.getViewport().toFloatRect();
2344}
2345
Vishnu Nair4351ad52019-02-11 14:13:02 -08002346void SurfaceFlinger::computeLayerBounds() {
2347 for (const auto& pair : mDisplays) {
2348 const auto& displayDevice = pair.second;
2349 const auto display = displayDevice->getCompositionDisplay();
2350 for (const auto& layer : mDrawingState.layersSortedByZ) {
2351 // only consider the layers on the given layer stack
2352 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002353 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002354 }
2355
Lloyd Pique7eebe692020-04-22 22:40:06 -07002356 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002357 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002358 }
2359 }
2360}
2361
David Sodmanfa9b2af2017-12-24 13:28:59 -08002362void SurfaceFlinger::postFrame()
2363{
2364 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002365 const auto display = getDefaultDisplayDeviceLocked();
2366 if (display && getHwComposer().isConnected(*display->getId())) {
2367 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002368 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2369 logFrameStats();
2370 }
2371 }
2372}
2373
Mathias Agopian87baae12012-07-31 12:38:26 -07002374void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375{
Mathias Agopian841cde52012-03-01 15:44:37 -08002376 ATRACE_CALL();
2377
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002378 // here we keep a copy of the drawing state (that is the state that's
2379 // going to be overwritten by handleTransactionLocked()) outside of
2380 // mStateLock so that the side-effects of the State assignment
2381 // don't happen with mStateLock held (which can cause deadlocks).
2382 State drawingState(mDrawingState);
2383
Mathias Agopianca4d3602011-05-19 15:38:14 -07002384 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002385 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002386
Mathias Agopianca4d3602011-05-19 15:38:14 -07002387 // Here we're guaranteed that some transaction flags are set
2388 // so we can call handleTransactionLocked() unconditionally.
2389 // We call getTransactionFlags(), which will also clear the flags,
2390 // with mStateLock held to guarantee that mCurrentState won't change
2391 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002392
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002393 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002394 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002395 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002396
Mathias Agopianca4d3602011-05-19 15:38:14 -07002397 mDebugInTransaction = 0;
2398 invalidateHwcGeometry();
2399 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002400}
2401
Lloyd Piqueba04e622017-12-14 17:11:26 -08002402void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2403 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002404 const std::optional<DisplayIdentificationInfo> info =
2405 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002406
Dominik Laskowski075d3172018-05-24 15:50:06 -07002407 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002408 continue;
2409 }
2410
Dominik Laskowski55c85402020-01-21 16:25:47 -08002411 const DisplayId displayId = info->id;
2412 const auto it = mPhysicalDisplayTokens.find(displayId);
2413
Peiyong Line9d809e2020-04-14 13:10:48 -07002414 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002415 if (it == mPhysicalDisplayTokens.end()) {
2416 ALOGV("Creating display %s", to_string(displayId).c_str());
2417
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002418 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002419 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002420 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002421
Dominik Laskowski075d3172018-05-24 15:50:06 -07002422 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002423 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2424 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002425 state.isSecure = true; // All physical displays are currently considered secure.
2426 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002427
2428 sp<IBinder> token = new BBinder();
2429 mCurrentState.displays.add(token, state);
2430 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2431
Dominik Laskowski075d3172018-05-24 15:50:06 -07002432 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002433 } else {
2434 ALOGV("Recreating display %s", to_string(displayId).c_str());
2435
2436 const auto token = it->second;
2437 auto& state = mCurrentState.displays.editValueFor(token);
2438 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002439 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002440 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002441 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002442
Dominik Laskowski55c85402020-01-21 16:25:47 -08002443 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002444 if (index >= 0) {
2445 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2446 mInterceptor->saveDisplayDeletion(state.sequenceId);
2447 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002448 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002449 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002450 }
2451
2452 processDisplayChangesLocked();
2453 }
2454
2455 mPendingHotplugEvents.clear();
2456}
2457
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002458void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002459 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2460 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002461}
2462
Lloyd Pique99d3da52018-01-22 17:48:03 -08002463sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002464 const wp<IBinder>& displayToken,
2465 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002466 const DisplayDeviceState& state,
2467 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002468 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002469 auto displayId = compositionDisplay->getDisplayId();
2470 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002471 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002472 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002473 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002474 creationArgs.hasWideColorGamut = false;
2475 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002476
Dominik Laskowski55c85402020-01-21 16:25:47 -08002477 if (const auto& physical = state.physical) {
2478 creationArgs.connectionType = physical->type;
2479 }
2480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002481 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002482 creationArgs.isPrimary = isInternalDisplay;
2483
2484 if (useColorManagement && displayId) {
2485 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002486 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002487 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002488 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002489 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002490
Dominik Laskowski7e045462018-05-30 13:02:02 -07002491 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002492 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002493 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002494 }
tangrobin6753a022018-08-10 10:58:54 +08002495 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002496
Dominik Laskowski075d3172018-05-24 15:50:06 -07002497 if (displayId) {
2498 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002499 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002500 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002501 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502
Lloyd Pique90c115d2018-09-18 21:39:42 -07002503 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002504 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002505 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002506
Lloyd Pique99d3da52018-01-22 17:48:03 -08002507 // Make sure that composition can never be stalled by a virtual display
2508 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002509 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002510 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002511 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2512 }
2513
Dominik Laskowski718f9602019-11-09 20:01:35 -08002514 creationArgs.physicalOrientation =
2515 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002516
Lloyd Pique99d3da52018-01-22 17:48:03 -08002517 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002518 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002519
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002520 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002521
2522 if (maxFrameBufferAcquiredBuffers >= 3) {
2523 nativeWindowSurface->preallocateBuffers();
2524 }
2525
2526 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002527 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002528 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002529 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002530 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002531 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002532 display->getCompositionDisplay()->setColorProfile(
2533 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2534 RenderIntent::COLORIMETRIC,
2535 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002536 if (!state.isVirtual()) {
2537 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002538 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2539 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002540 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002541
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002542 display->setLayerStack(state.layerStack);
2543 display->setProjection(state.orientation, state.viewport, state.frame);
2544 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002545
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002546 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547}
2548
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002549void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2550 const DisplayDeviceState& state) {
2551 int width = 0;
2552 int height = 0;
2553 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2554 if (state.physical) {
2555 const auto& activeConfig =
2556 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2557 width = activeConfig->getWidth();
2558 height = activeConfig->getHeight();
2559 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2560 } else if (state.surface != nullptr) {
2561 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2562 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2563 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2564 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2565 int intPixelFormat;
2566 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2567 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2568 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2569 } else {
2570 // Virtual displays without a surface are dormant:
2571 // they have external state (layer stack, projection,
2572 // etc.) but no internal state (i.e. a DisplayDevice).
2573 return;
2574 }
2575
2576 compositionengine::DisplayCreationArgsBuilder builder;
2577 if (const auto& physical = state.physical) {
2578 builder.setPhysical({physical->id, physical->type});
2579 }
2580 builder.setPixels(ui::Size(width, height));
2581 builder.setPixelFormat(pixelFormat);
2582 builder.setIsSecure(state.isSecure);
2583 builder.setLayerStackId(state.layerStack);
2584 builder.setPowerAdvisor(&mPowerAdvisor);
2585 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2586 builder.setName(state.displayName);
2587 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2588
2589 sp<compositionengine::DisplaySurface> displaySurface;
2590 sp<IGraphicBufferProducer> producer;
2591 sp<IGraphicBufferProducer> bqProducer;
2592 sp<IGraphicBufferConsumer> bqConsumer;
2593 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2594
2595 std::optional<DisplayId> displayId = compositionDisplay->getId();
2596
2597 if (state.isVirtual()) {
2598 sp<VirtualDisplaySurface> vds =
2599 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2600 bqConsumer, state.displayName);
2601
2602 displaySurface = vds;
2603 producer = vds;
2604 } else {
2605 ALOGE_IF(state.surface != nullptr,
2606 "adding a supported display, but rendering "
2607 "surface is provided (%p), ignoring it",
2608 state.surface.get());
2609
2610 LOG_ALWAYS_FATAL_IF(!displayId);
2611 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2612 maxGraphicsWidth, maxGraphicsHeight);
2613 producer = bqProducer;
2614 }
2615
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002616 LOG_FATAL_IF(!displaySurface);
2617 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2618 displaySurface, producer);
2619 mDisplays.emplace(displayToken, display);
2620 if (!state.isVirtual()) {
2621 LOG_FATAL_IF(!displayId);
2622 dispatchDisplayHotplugEvent(displayId->value, true);
2623 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002624
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002625 if (display->isPrimary()) {
2626 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002627 }
2628}
2629
2630void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2631 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2632 // Save display ID before disconnecting.
2633 const auto displayId = display->getId();
2634 display->disconnect();
2635
2636 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002637 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002638 dispatchDisplayHotplugEvent(displayId->value, false);
2639 }
2640 }
2641
2642 mDisplays.erase(displayToken);
2643}
2644
2645void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2646 const DisplayDeviceState& currentState,
2647 const DisplayDeviceState& drawingState) {
2648 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2649 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002650 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002651 // changing the surface is like destroying and recreating the DisplayDevice
2652 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2653 display->disconnect();
2654 }
2655 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002656 if (const auto& physical = currentState.physical) {
2657 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2658 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002659 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002660 if (currentState.physical) {
2661 initializeDisplays();
2662 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002663 return;
2664 }
2665
2666 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2667 if (currentState.layerStack != drawingState.layerStack) {
2668 display->setLayerStack(currentState.layerStack);
2669 }
2670 if ((currentState.orientation != drawingState.orientation) ||
2671 (currentState.viewport != drawingState.viewport) ||
2672 (currentState.frame != drawingState.frame)) {
2673 display->setProjection(currentState.orientation, currentState.viewport,
2674 currentState.frame);
2675 }
2676 if (currentState.width != drawingState.width ||
2677 currentState.height != drawingState.height) {
2678 display->setDisplaySize(currentState.width, currentState.height);
2679 if (display->isPrimary()) {
2680 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2681 }
2682 }
2683 }
2684}
2685
Lloyd Pique347200f2017-12-14 17:00:15 -08002686void SurfaceFlinger::processDisplayChangesLocked() {
2687 // here we take advantage of Vector's copy-on-write semantics to
2688 // improve performance by skipping the transaction entirely when
2689 // know that the lists are identical
2690 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2691 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2692 if (!curr.isIdenticalTo(draw)) {
2693 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002694
2695 // find the displays that were removed
2696 // (ie: in drawing state but not in current state)
2697 // also handle displays that changed
2698 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002699 for (size_t i = 0; i < draw.size(); i++) {
2700 const wp<IBinder>& displayToken = draw.keyAt(i);
2701 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 if (j < 0) {
2703 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002704 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002705 } else {
2706 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002707 const DisplayDeviceState& currentState = curr[j];
2708 const DisplayDeviceState& drawingState = draw[i];
2709 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002710 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 }
2712
2713 // find displays that were added
2714 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002715 for (size_t i = 0; i < curr.size(); i++) {
2716 const wp<IBinder>& displayToken = curr.keyAt(i);
2717 if (draw.indexOfKey(displayToken) < 0) {
2718 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002719 }
2720 }
2721 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002722
2723 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002724}
2725
Mathias Agopian87baae12012-07-31 12:38:26 -07002726void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002727{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002728 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2729
Dan Stoza7dde5992015-05-22 09:51:44 -07002730 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002731 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002732 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002733 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002734
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735 /*
2736 * Traversal of the children
2737 * (perform the transaction for each of them if needed)
2738 */
2739
Marissa Wall06255332019-03-27 13:48:27 -07002740 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002741 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002743 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744
2745 const uint32_t flags = layer->doTransaction(0);
2746 if (flags & Layer::eVisibleRegion)
2747 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002748
2749 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002750 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002751 }
Robert Carr2047fae2016-11-28 14:09:09 -08002752 });
Marissa Wall06255332019-03-27 13:48:27 -07002753 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754 }
2755
2756 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002757 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 */
2759
Mathias Agopiane57f2922012-08-09 16:29:12 -07002760 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002761 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002762 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002763 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002765 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002766 // The transform hint might have changed for some layers
2767 // (either because a display has changed, or because a layer
2768 // as changed).
2769 //
2770 // Walk through all the layers in currentLayers,
2771 // and update their transform hint.
2772 //
2773 // If a layer is visible only on a single display, then that
2774 // display is used to calculate the hint, otherwise we use the
2775 // default display.
2776 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002777 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002778 // the hint is set before we acquire a buffer from the surface texture.
2779 //
2780 // NOTE: layer transactions have taken place already, so we use their
2781 // drawing state. However, SurfaceFlinger's own transaction has not
2782 // happened yet, so we must use the current state layer list
2783 // (soon to become the drawing state list).
2784 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002785 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002786 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002787 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002788 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002789 // NOTE: we rely on the fact that layers are sorted by
2790 // layerStack first (so we don't have to traverse the list
2791 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002792 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002793 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002794 currentlayerStack = layerStack;
2795 // figure out if this layerstack is mirrored
2796 // (more than one display) if so, pick the default display,
2797 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002798 hintDisplay = nullptr;
2799 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002800 if (display->getCompositionDisplay()
2801 ->belongsInOutput(layer->getLayerStack(),
2802 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002803 if (hintDisplay) {
2804 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002805 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002806 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002807 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002808 }
2809 }
2810 }
2811 }
Chet Haase91d25932013-04-11 15:24:55 -07002812
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002813 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002814 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2815 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002816
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002817 // could be null when this layer is using a layerStack
2818 // that is not visible on any display. Also can occur at
2819 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002820 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002821 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002822
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002823 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002824 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002825 if (hintDisplay) {
2826 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002827 }
Robert Carr2047fae2016-11-28 14:09:09 -08002828
2829 first = false;
2830 });
Mathias Agopian84300952012-11-21 16:02:13 -08002831 }
2832
2833
Mathias Agopian3559b072012-08-15 13:46:03 -07002834 /*
2835 * Perform our own transaction if needed
2836 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002837
2838 if (mLayersAdded) {
2839 mLayersAdded = false;
2840 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002841 mVisibleRegionsDirty = true;
2842 }
2843
2844 // some layers might have been removed, so
2845 // we need to update the regions they're exposing.
2846 if (mLayersRemoved) {
2847 mLayersRemoved = false;
2848 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002849 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002850 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002851 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002852 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002853 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002854 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002855 }
Robert Carr2047fae2016-11-28 14:09:09 -08002856 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 }
2858
Vishnu Nairec0ab382019-02-13 15:32:56 -08002859 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002861}
2862
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002863void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002864 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002865 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002866 return;
2867 }
2868
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002869 if (mVisibleRegionsDirty || mInputInfoChanged) {
2870 mInputInfoChanged = false;
2871 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002872 } else if (mInputWindowCommands.syncInputWindows) {
2873 // If the caller requested to sync input windows, but there are no
2874 // changes to input windows, notify immediately.
2875 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002876 }
2877
Arthur Hung6cbb9752019-09-05 16:38:18 +08002878 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002879}
2880
2881void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002882 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002883
2884 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2885 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002886 // When calculating the screen bounds we ignore the transparent region since it may
2887 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002888 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002889 }
2890 });
chaviw291d88a2019-02-14 10:33:58 -08002891
2892 mInputFlinger->setInputWindows(inputHandles,
2893 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2894 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002895}
2896
Vishnu Nairec0ab382019-02-13 15:32:56 -08002897void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002898 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002899 mPendingInputWindowCommands.clear();
2900}
2901
Riley Andrews03414a12014-07-01 14:22:59 -07002902void SurfaceFlinger::updateCursorAsync()
2903{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002904 compositionengine::CompositionRefreshArgs refreshArgs;
2905 for (const auto& [_, display] : mDisplays) {
2906 if (display->getId()) {
2907 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002908 }
2909 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002910
2911 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002912}
2913
Ady Abraham2139f732019-11-13 18:56:40 -08002914void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002915 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2916 // If this is called from the main thread mStateLock must be locked before
2917 // Currently the only way to call this function from the main thread is from
2918 // Sheduler::chooseRefreshRateForContent
2919
2920 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002921 changeRefreshRateLocked(refreshRate, event);
2922}
2923
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002924void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2925 if (mScheduler) {
2926 // In practice it's not allowed to hotplug in/out the primary display once it's been
2927 // connected during startup, but some tests do it, so just warn and return.
2928 ALOGW("Can't re-init scheduler");
2929 return;
2930 }
2931
Ady Abraham2139f732019-11-13 18:56:40 -08002932 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002933 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002934 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002935 primaryDisplayId),
2936 currentConfig);
2937 mRefreshRateStats =
2938 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002939 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002940 mRefreshRateStats->setConfigMode(currentConfig);
2941
Ady Abraham9e16a482019-12-03 17:19:41 -08002942 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2943
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002944 // start the EventThread
2945 mScheduler =
2946 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002947 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002948 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002949 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002950 impl::EventThread::InterceptVSyncsCallback());
2951 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002952 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002953 [this](nsecs_t timestamp) {
2954 mInterceptor->saveVSyncEvent(timestamp);
2955 });
2956
2957 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2958 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002959 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002960
2961 mRegionSamplingThread =
2962 new RegionSamplingThread(*this, *mScheduler,
2963 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002964 // Dispatch a config change request for the primary display on scheduler
2965 // initialization, so that the EventThreads always contain a reference to a
2966 // prior configuration.
2967 //
2968 // This is a bit hacky, but this avoids a back-pointer into the main SF
2969 // classes from EventThread, and there should be no run-time binder cost
2970 // anyway since there are no connected apps at this point.
2971 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002972 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Alec Mouri60aee1c2019-10-28 16:18:59 -07002973 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2974 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002975}
2976
Mathias Agopian4fec8732012-06-29 14:12:52 -07002977void SurfaceFlinger::commitTransaction()
2978{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002979 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002980 mTransactionPending = false;
2981 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002982 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983}
2984
Lloyd Pique58e24a32019-08-01 15:50:14 -07002985void SurfaceFlinger::commitTransactionLocked() {
2986 if (!mLayersPendingRemoval.isEmpty()) {
2987 // Notify removed layers now that they can't be drawn from
2988 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002989 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002990
2991 // Ensure any buffers set to display on any children are released.
2992 if (l->isRemovedFromCurrentState()) {
2993 l->latchAndReleaseBuffer();
2994 }
2995
2996 // If the layer has been removed and has no parent, then it will not be reachable
2997 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2998 // ensure we can copy its current to drawing state.
2999 if (!l->getParent()) {
3000 mOffscreenLayers.emplace(l.get());
3001 }
3002 }
3003 mLayersPendingRemoval.clear();
3004 }
3005
3006 // If this transaction is part of a window animation then the next frame
3007 // we composite should be considered an animation as well.
3008 mAnimCompositionPending = mAnimTransactionPending;
3009
3010 mDrawingState = mCurrentState;
3011 // clear the "changed" flags in current state
3012 mCurrentState.colorMatrixChanged = false;
3013
Edgar Arriaga844fa672020-01-16 14:21:42 -08003014 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003015 layer->commitChildList();
3016
3017 // If the layer can be reached when traversing mDrawingState, then the layer is no
3018 // longer offscreen. Remove the layer from the offscreenLayer set.
3019 if (mOffscreenLayers.count(layer)) {
3020 mOffscreenLayers.erase(layer);
3021 }
3022 });
3023
3024 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003025 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003026}
3027
chaviw74d90ad2019-04-26 14:45:26 -07003028void SurfaceFlinger::commitOffscreenLayers() {
3029 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003030 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003031 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3032 if (!trFlags) return;
3033
3034 layer->doTransaction(0);
3035 layer->commitChildList();
3036 });
3037 }
3038}
3039
Chia-I Wuab0c3192017-08-01 11:29:00 -07003040void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003041 for (const auto& [token, displayDevice] : mDisplays) {
3042 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003043 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003044 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003045 }
3046 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003047}
3048
Dan Stoza6b9454d2014-11-07 16:00:59 -08003049bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050{
Ady Abraham09bd3922019-04-08 10:44:56 -07003051 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003052 ALOGV("handlePageFlip");
3053
Brian Andersond6927fb2016-07-23 23:37:30 -07003054 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055
Mathias Agopian4fec8732012-06-29 14:12:52 -07003056 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003057 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003058 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003059
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003060 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3061
Eric Penner51c59cd2014-07-28 19:51:58 -07003062 // Store the set of layers that need updates. This set must not change as
3063 // buffers are being latched, as this could result in a deadlock.
3064 // Example: Two producers share the same command stream and:
3065 // 1.) Layer 0 is latched
3066 // 2.) Layer 0 gets a new frame
3067 // 2.) Layer 1 gets a new frame
3068 // 3.) Layer 1 is latched.
3069 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3070 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003071 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003072 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003073 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003074 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003075 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003076 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003077 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003078 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003079 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003080 } else {
3081 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003082 }
Robert Carr2047fae2016-11-28 14:09:09 -08003083 });
3084
chaviw49a108c2019-08-12 11:23:06 -07003085 // The client can continue submitting buffers for offscreen layers, but they will not
3086 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3087 // layers to ensure dequeueBuffer doesn't block indefinitely.
3088 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003089 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003090 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3091 }
3092
Lloyd Piquef2c79392018-12-20 16:23:33 -08003093 if (!mLayersWithQueuedFrames.empty()) {
3094 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3095 // writes to Layer current state. See also b/119481871
3096 Mutex::Autolock lock(mStateLock);
3097
3098 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003099 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003100 mLayersPendingRefresh.push_back(layer);
3101 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003102 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003103 if (layer->isBufferLatched()) {
3104 newDataLatched = true;
3105 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003106 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003107 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003108
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003109 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003110
3111 // If we will need to wake up at some time in the future to deal with a
3112 // queued frame that shouldn't be displayed during this vsync period, wake
3113 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003114 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003115 signalLayerUpdate();
3116 }
3117
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003118 // enter boot animation on first buffer latch
3119 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3120 ALOGI("Enter boot animation");
3121 mBootStage = BootStage::BOOTANIMATION;
3122 }
3123
Edgar Arriaga844fa672020-01-16 14:21:42 -08003124 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003125
Dan Stoza6b9454d2014-11-07 16:00:59 -08003126 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003127 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128}
3129
Mathias Agopianad456f92011-01-13 17:53:01 -08003130void SurfaceFlinger::invalidateHwcGeometry()
3131{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003132 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003133}
3134
Robert Carrc0df3122019-04-11 13:18:21 -07003135status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3136 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3137 const sp<IBinder>& parentHandle,
3138 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003139 // add this layer to the current state list
3140 {
3141 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003142 sp<Layer> parent;
3143 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003144 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003145 if (parent == nullptr) {
3146 return NAME_NOT_FOUND;
3147 }
3148 } else {
3149 parent = parentLayer;
3150 }
3151
Ady Abraham0a525092020-03-03 12:51:24 -08003152 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003153 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003154 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003155 return NO_MEMORY;
3156 }
Robert Carrc0df3122019-04-11 13:18:21 -07003157
3158 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3159
Robert Carrb89ea9d2018-12-10 13:01:14 -08003160 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003161 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003162 } else if (parent == nullptr) {
3163 lbc->onRemovedFromCurrentState();
3164 } else if (parent->isRemovedFromCurrentState()) {
3165 parent->addChild(lbc);
3166 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003167 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003168 parent->addChild(lbc);
3169 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003170
Yiwei Zhang243b3782018-05-15 17:40:04 -07003171 if (gbc != nullptr) {
3172 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3173 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3174 mMaxGraphicBufferProducerListSize,
3175 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3176 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003177 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003178 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003179 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003180 }
3181
Mathias Agopian96f08192010-06-02 23:28:45 -07003182 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003183 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003184
Dan Stoza7d89d062015-04-30 13:29:25 -07003185 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003186}
3187
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003188void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3189 static_cast<void>(schedule([=] {
3190 Mutex::Autolock lock(mStateLock);
3191 mGraphicBufferProducerList.erase(binder);
3192 }));
3193}
3194
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003195uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003196 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003197}
3198
Mathias Agopian3f844832013-08-07 21:24:32 -07003199uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003200 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201}
3202
Mathias Agopian3f844832013-08-07 21:24:32 -07003203uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003204 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003205}
3206
3207uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003208 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003209 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003210 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003212 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213 }
3214 return old;
3215}
3216
Marissa Wall713b63f2018-10-17 15:42:43 -07003217bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003218 // to prevent onHandleDestroyed from being called while the lock is held,
3219 // we must keep a copy of the transactions (specifically the composer
3220 // states) around outside the scope of the lock
3221 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003222 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003223 {
3224 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003225
Valerie Haufce31b82019-04-30 16:41:14 -07003226 auto it = mTransactionQueues.begin();
3227 while (it != mTransactionQueues.end()) {
3228 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003229
Valerie Haufce31b82019-04-30 16:41:14 -07003230 while (!transactionQueue.empty()) {
3231 const auto& transaction = transactionQueue.front();
3232 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3233 transaction.states)) {
3234 setTransactionFlags(eTransactionFlushNeeded);
3235 break;
3236 }
3237 transactions.push_back(transaction);
3238 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3239 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003240 transaction.buffer, transaction.postTime,
3241 transaction.privileged, transaction.hasListenerCallbacks,
3242 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003243 transactionQueue.pop();
3244 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003245 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003246
Valerie Haufce31b82019-04-30 16:41:14 -07003247 if (transactionQueue.empty()) {
3248 it = mTransactionQueues.erase(it);
3249 mTransactionCV.broadcast();
3250 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003251 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003252 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003253 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003254 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003255 return flushedATransaction;
3256}
3257
3258bool SurfaceFlinger::transactionFlushNeeded() {
3259 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003260}
3261
chaviwca27f252018-02-06 16:46:39 -08003262
Marissa Wall17b4e452018-12-26 16:32:34 -08003263bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3264 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003265
3266 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003267 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3268 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3269 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3270 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3271 return false;
3272 }
3273
Marissa Wall713b63f2018-10-17 15:42:43 -07003274 for (const ComposerState& state : states) {
3275 const layer_state_t& s = state.state;
3276 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3277 continue;
3278 }
3279 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003280 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003281 }
3282 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003283 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003284}
3285
Valerie Hau9dab9732019-08-20 09:29:25 -07003286void SurfaceFlinger::setTransactionState(
3287 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3288 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3289 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3290 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003291 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003292
Valerie Haubc6ddb12019-03-08 11:10:15 -08003293 const int64_t postTime = systemTime();
3294
Robert Carr14167e02019-02-13 13:50:55 -08003295 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3296
Mathias Agopian698c0872011-06-28 19:09:31 -07003297 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003298
Marissa Wall713b63f2018-10-17 15:42:43 -07003299 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003300 auto itr = mTransactionQueues.find(applyToken);
3301 // if this is an animation frame, wait until prior animation frame has
3302 // been applied by SF
3303 if (flags & eAnimation) {
3304 while (itr != mTransactionQueues.end()) {
3305 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3306 if (CC_UNLIKELY(err != NO_ERROR)) {
3307 ALOGW_IF(err == TIMED_OUT,
3308 "setTransactionState timed out "
3309 "waiting for animation frame to apply");
3310 break;
3311 }
3312 itr = mTransactionQueues.find(applyToken);
3313 }
3314 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003315
Ady Abraham5facfb12020-04-22 15:18:31 -07003316 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003317 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003318 if (!pendingTransactions) {
3319 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3320 }
3321
3322 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003323 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003324 uncacheBuffer, postTime, privileged,
3325 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003326 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003327 return;
3328 }
3329
Valerie Haubc6ddb12019-03-08 11:10:15 -08003330 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003331 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3332 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003333}
3334
Valerie Hau9dab9732019-08-20 09:29:25 -07003335void SurfaceFlinger::applyTransactionState(
3336 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3337 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3338 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3339 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3340 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003341 uint32_t transactionFlags = 0;
3342
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003343 if (flags & eAnimation) {
3344 // For window updates that are part of an animation we must wait for
3345 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003346 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003347 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003348 if (CC_UNLIKELY(err != NO_ERROR)) {
3349 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003350 // caller after a few seconds.
3351 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3352 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003353 mAnimTransactionPending = false;
3354 break;
3355 }
3356 }
3357 }
3358
chaviwca27f252018-02-06 16:46:39 -08003359 for (const DisplayState& display : displays) {
3360 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003361 }
3362
Valerie Hau9dab9732019-08-20 09:29:25 -07003363 // start and end registration for listeners w/ no surface so they can get their callback. Note
3364 // that listeners with SurfaceControls will start registration during setClientStateLocked
3365 // below.
3366 for (const auto& listener : listenerCallbacks) {
3367 mTransactionCompletedThread.startRegistration(listener);
3368 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003369 }
3370
Valerie Hau9dab9732019-08-20 09:29:25 -07003371 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003372 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003373 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003374 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3375 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003376 }
3377
Valerie Hau9dab9732019-08-20 09:29:25 -07003378 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003379 mTransactionCompletedThread.endRegistration(listenerCallback);
3380 }
3381
Marissa Walle2ffb422018-10-12 11:33:52 -07003382 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003383 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003384 mTransactionCompletedThread.sendCallbacks();
3385 }
3386 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003387
chaviw273171b2018-12-26 11:46:30 -08003388 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3389
Marissa Wall947d34e2019-03-29 14:03:53 -07003390 if (uncacheBuffer.isValid()) {
3391 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003392 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003393 }
3394
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003395 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3396 // anyway. This can be used as a flush mechanism for previous async transactions.
3397 // Empty animation transaction can be used to simulate back-pressure, so also force a
3398 // transaction for empty animation transactions.
3399 if (transactionFlags == 0 &&
3400 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003401 transactionFlags = eTransactionNeeded;
3402 }
3403
Marissa Wall06255332019-03-27 13:48:27 -07003404 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3405 // so we don't have to wake up again next frame to preform an uneeded traversal.
3406 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3407 transactionFlags = transactionFlags & (~eTraversalNeeded);
3408 mTraversalNeededMainThread = true;
3409 }
3410
Mathias Agopian386aa982011-11-07 21:58:03 -08003411 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003412 if (mInterceptor->isEnabled()) {
3413 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003414 }
Irvel468051e2016-06-13 16:44:44 -07003415
Mathias Agopian386aa982011-11-07 21:58:03 -08003416 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003417 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3418 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003419 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003420
3421 // if this is a synchronous transaction, wait for it to take effect
3422 // before returning.
3423 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003424 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003425 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003426 if (flags & eAnimation) {
3427 mAnimTransactionPending = true;
3428 }
chaviw4fe36852019-04-15 16:25:49 -07003429 if (mPendingInputWindowCommands.syncInputWindows) {
3430 mPendingSyncInputWindows = true;
3431 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003432
3433 // applyTransactionState can be called by either the main SF thread or by
3434 // another process through setTransactionState. While a given process may wish
3435 // to wait on synchronous transactions, the main SF thread should never
3436 // be blocked. Therefore, we only wait if isMainThread is false.
3437 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003438 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3439 if (CC_UNLIKELY(err != NO_ERROR)) {
3440 // just in case something goes wrong in SF, return to the
3441 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003442 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3443 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003444 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003445 break;
3446 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003447 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003448 }
3449}
3450
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003451uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3452 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3453 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003454
Mathias Agopiane57f2922012-08-09 16:29:12 -07003455 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003456 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3457
3458 const uint32_t what = s.what;
3459 if (what & DisplayState::eSurfaceChanged) {
3460 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3461 state.surface = s.surface;
3462 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003463 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003464 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003465 if (what & DisplayState::eLayerStackChanged) {
3466 if (state.layerStack != s.layerStack) {
3467 state.layerStack = s.layerStack;
3468 flags |= eDisplayTransactionNeeded;
3469 }
3470 }
3471 if (what & DisplayState::eDisplayProjectionChanged) {
3472 if (state.orientation != s.orientation) {
3473 state.orientation = s.orientation;
3474 flags |= eDisplayTransactionNeeded;
3475 }
3476 if (state.frame != s.frame) {
3477 state.frame = s.frame;
3478 flags |= eDisplayTransactionNeeded;
3479 }
3480 if (state.viewport != s.viewport) {
3481 state.viewport = s.viewport;
3482 flags |= eDisplayTransactionNeeded;
3483 }
3484 }
3485 if (what & DisplayState::eDisplaySizeChanged) {
3486 if (state.width != s.width) {
3487 state.width = s.width;
3488 flags |= eDisplayTransactionNeeded;
3489 }
3490 if (state.height != s.height) {
3491 state.height = s.height;
3492 flags |= eDisplayTransactionNeeded;
3493 }
3494 }
3495
Mathias Agopiane57f2922012-08-09 16:29:12 -07003496 return flags;
3497}
3498
Steven Thomasd4071902020-03-24 16:02:53 -07003499bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003500 IPCThreadState* ipc = IPCThreadState::self();
3501 const int pid = ipc->getCallingPid();
3502 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003503 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003504 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3505 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003506 return false;
3507 }
3508 return true;
3509}
3510
Marissa Wall3dad52d2019-03-22 14:03:19 -07003511uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003512 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3513 bool privileged,
3514 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003515 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003516
Valerie Hau9dab9732019-08-20 09:29:25 -07003517 for (auto& listener : s.listeners) {
3518 // note that startRegistration will not re-register if the listener has
3519 // already be registered for a prior surface control
3520 mTransactionCompletedThread.startRegistration(listener);
3521 listenerCallbacks.insert(listener);
3522 }
3523
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003524 sp<Layer> layer = nullptr;
3525 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003526 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003527 } else {
3528 // The client may provide us a null handle. Treat it as if the layer was removed.
3529 ALOGW("Attempt to set client state with a null layer handle");
3530 }
chaviw8b3871a2017-11-01 17:41:01 -07003531 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003532 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003533 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003534 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003535 }
chaviw8b3871a2017-11-01 17:41:01 -07003536 return 0;
3537 }
3538
chaviw8b3871a2017-11-01 17:41:01 -07003539 uint32_t flags = 0;
3540
Garfield Tan8a3083e2018-12-03 13:21:07 -08003541 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003542
3543 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3544 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003545 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003546 layer->pushPendingState();
3547 }
3548
Valerie Hau871d6352020-01-29 08:44:02 -08003549 // Only set by BLAST adapter layers
3550 if (what & layer_state_t::eProducerDisconnect) {
3551 layer->onDisconnect();
3552 }
3553
chaviw8b3871a2017-11-01 17:41:01 -07003554 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003555 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003556 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003557 }
chaviw8b3871a2017-11-01 17:41:01 -07003558 }
3559 if (what & layer_state_t::eLayerChanged) {
3560 // NOTE: index needs to be calculated before we update the state
3561 const auto& p = layer->getParent();
3562 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003563 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003564 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003565 mCurrentState.layersSortedByZ.removeAt(idx);
3566 mCurrentState.layersSortedByZ.add(layer);
3567 // we need traversal (state changed)
3568 // AND transaction (list changed)
3569 flags |= eTransactionNeeded|eTraversalNeeded;
3570 }
chaviw8b3871a2017-11-01 17:41:01 -07003571 } else {
3572 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003573 flags |= eTransactionNeeded|eTraversalNeeded;
3574 }
3575 }
chaviw8b3871a2017-11-01 17:41:01 -07003576 }
3577 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003578 // NOTE: index needs to be calculated before we update the state
3579 const auto& p = layer->getParent();
3580 if (p == nullptr) {
3581 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3582 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3583 mCurrentState.layersSortedByZ.removeAt(idx);
3584 mCurrentState.layersSortedByZ.add(layer);
3585 // we need traversal (state changed)
3586 // AND transaction (list changed)
3587 flags |= eTransactionNeeded|eTraversalNeeded;
3588 }
3589 } else {
3590 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3591 flags |= eTransactionNeeded|eTraversalNeeded;
3592 }
chaviw8b3871a2017-11-01 17:41:01 -07003593 }
3594 }
3595 if (what & layer_state_t::eSizeChanged) {
3596 if (layer->setSize(s.w, s.h)) {
3597 flags |= eTraversalNeeded;
3598 }
3599 }
3600 if (what & layer_state_t::eAlphaChanged) {
3601 if (layer->setAlpha(s.alpha))
3602 flags |= eTraversalNeeded;
3603 }
3604 if (what & layer_state_t::eColorChanged) {
3605 if (layer->setColor(s.color))
3606 flags |= eTraversalNeeded;
3607 }
Peiyong Lind3788632018-09-18 16:01:31 -07003608 if (what & layer_state_t::eColorTransformChanged) {
3609 if (layer->setColorTransform(s.colorTransform)) {
3610 flags |= eTraversalNeeded;
3611 }
3612 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003613 if (what & layer_state_t::eBackgroundColorChanged) {
3614 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3615 flags |= eTraversalNeeded;
3616 }
3617 }
chaviw8b3871a2017-11-01 17:41:01 -07003618 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003619 // TODO: b/109894387
3620 //
3621 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3622 // rotation. To see the problem observe that if we have a square parent, and a child
3623 // of the same size, then we rotate the child 45 degrees around it's center, the child
3624 // must now be cropped to a non rectangular 8 sided region.
3625 //
3626 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3627 // private API, and the WindowManager only uses rotation in one case, which is on a top
3628 // level layer in which cropping is not an issue.
3629 //
3630 // However given that abuse of rotation matrices could lead to surfaces extending outside
3631 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3632 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3633 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003634 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003635 flags |= eTraversalNeeded;
3636 }
3637 if (what & layer_state_t::eTransparentRegionChanged) {
3638 if (layer->setTransparentRegionHint(s.transparentRegion))
3639 flags |= eTraversalNeeded;
3640 }
3641 if (what & layer_state_t::eFlagsChanged) {
3642 if (layer->setFlags(s.flags, s.mask))
3643 flags |= eTraversalNeeded;
3644 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003645 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003646 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003647 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003648 if (what & layer_state_t::eCornerRadiusChanged) {
3649 if (layer->setCornerRadius(s.cornerRadius))
3650 flags |= eTraversalNeeded;
3651 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003652 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003653 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3654 }
chaviw8b3871a2017-11-01 17:41:01 -07003655 if (what & layer_state_t::eLayerStackChanged) {
3656 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3657 // We only allow setting layer stacks for top level layers,
3658 // everything else inherits layer stack from its parent.
3659 if (layer->hasParent()) {
3660 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003661 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003662 } else if (idx < 0) {
3663 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003664 "that also does not appear in the top level layer list. Something"
3665 " has gone wrong.",
3666 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003667 } else if (layer->setLayerStack(s.layerStack)) {
3668 mCurrentState.layersSortedByZ.removeAt(idx);
3669 mCurrentState.layersSortedByZ.add(layer);
3670 // we need traversal (state changed)
3671 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003672 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003673 }
3674 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003675 if (what & layer_state_t::eDeferTransaction_legacy) {
3676 if (s.barrierHandle_legacy != nullptr) {
3677 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3678 } else if (s.barrierGbp_legacy != nullptr) {
3679 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003680 if (authenticateSurfaceTextureLocked(gbp)) {
3681 const auto& otherLayer =
3682 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003683 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003684 } else {
3685 ALOGE("Attempt to defer transaction to to an"
3686 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003687 }
3688 }
chaviw8b3871a2017-11-01 17:41:01 -07003689 // We don't trigger a traversal here because if no other state is
3690 // changed, we don't want this to cause any more work
3691 }
chaviw8b3871a2017-11-01 17:41:01 -07003692 if (what & layer_state_t::eReparentChildren) {
3693 if (layer->reparentChildren(s.reparentHandle)) {
3694 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003695 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003696 }
chaviw8b3871a2017-11-01 17:41:01 -07003697 if (what & layer_state_t::eDetachChildren) {
3698 layer->detachChildren();
3699 }
3700 if (what & layer_state_t::eOverrideScalingModeChanged) {
3701 layer->setOverrideScalingMode(s.overrideScalingMode);
3702 // We don't trigger a traversal here because if no other state is
3703 // changed, we don't want this to cause any more work
3704 }
Marissa Wall61c58622018-07-18 10:12:20 -07003705 if (what & layer_state_t::eTransformChanged) {
3706 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3707 }
3708 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3709 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3710 flags |= eTraversalNeeded;
3711 }
3712 if (what & layer_state_t::eCropChanged) {
3713 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3714 }
Marissa Wall861616d2018-10-22 12:52:23 -07003715 if (what & layer_state_t::eFrameChanged) {
3716 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3717 }
Marissa Wall61c58622018-07-18 10:12:20 -07003718 if (what & layer_state_t::eAcquireFenceChanged) {
3719 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3720 }
3721 if (what & layer_state_t::eDataspaceChanged) {
3722 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3723 }
3724 if (what & layer_state_t::eHdrMetadataChanged) {
3725 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3726 }
3727 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3728 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3729 }
3730 if (what & layer_state_t::eApiChanged) {
3731 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3732 }
3733 if (what & layer_state_t::eSidebandStreamChanged) {
3734 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3735 }
Robert Carr720e5062018-07-30 17:45:14 -07003736 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003737 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003738 layer->setInputInfo(s.inputInfo);
3739 flags |= eTraversalNeeded;
3740 } else {
3741 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3742 }
Robert Carr720e5062018-07-30 17:45:14 -07003743 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003744 if (what & layer_state_t::eMetadataChanged) {
3745 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3746 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003747 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3748 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3749 flags |= eTraversalNeeded;
3750 }
3751 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003752 if (what & layer_state_t::eShadowRadiusChanged) {
3753 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3754 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003755 if (what & layer_state_t::eFrameRateSelectionPriority) {
3756 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3757 flags |= eTraversalNeeded;
3758 }
3759 }
Steven Thomas3172e202020-01-06 19:25:30 -08003760 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003761 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3762 "SurfaceFlinger::setClientStateLocked") &&
3763 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3764 Layer::FrameRate::convertCompatibility(
3765 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003766 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003767 }
Steven Thomas3172e202020-01-06 19:25:30 -08003768 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003769 // This has to happen after we reparent children because when we reparent to null we remove
3770 // child layers from current state and remove its relative z. If the children are reparented in
3771 // the same transaction, then we have to make sure we reparent the children first so we do not
3772 // lose its relative z order.
3773 if (what & layer_state_t::eReparent) {
3774 bool hadParent = layer->hasParent();
3775 if (layer->reparent(s.parentHandleForChild)) {
3776 if (!hadParent) {
3777 mCurrentState.layersSortedByZ.remove(layer);
3778 }
3779 flags |= eTransactionNeeded | eTraversalNeeded;
3780 }
3781 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003782 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003783 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3784 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003785 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3786 }
3787 }
Marissa Wall78b72202019-03-15 14:58:34 -07003788 bool bufferChanged = what & layer_state_t::eBufferChanged;
3789 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3790 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003791 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003792 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003793 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3794 if (success) {
3795 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3796 success = ClientCache::getInstance()
3797 .registerErasedRecipient(s.cachedBuffer,
3798 wp<ClientCache::ErasedRecipient>(this));
3799 if (!success) {
3800 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3801 }
3802 }
Marissa Wall78b72202019-03-15 14:58:34 -07003803 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003804 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003805 } else if (bufferChanged) {
3806 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003807 }
Marissa Wall78b72202019-03-15 14:58:34 -07003808 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003809 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3810 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003811 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003812 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003813 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003814 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3815 // Do not put anything that updates layer state or modifies flags after
3816 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003817 return flags;
3818}
3819
chaviw273171b2018-12-26 11:46:30 -08003820uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3821 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003822 if (inputWindowCommands.syncInputWindows) {
3823 flags |= eTraversalNeeded;
3824 }
3825
Vishnu Nairec0ab382019-02-13 15:32:56 -08003826 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003827 return flags;
3828}
3829
chaviwfe94a222019-08-21 13:52:59 -07003830status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3831 sp<IBinder>* outHandle) {
3832 if (!mirrorFromHandle) {
3833 return NAME_NOT_FOUND;
3834 }
3835
3836 sp<Layer> mirrorLayer;
3837 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003838 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003839
3840 {
3841 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003842 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003843 if (!mirrorFrom) {
3844 return NAME_NOT_FOUND;
3845 }
3846
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003847 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3848 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003849 if (result != NO_ERROR) {
3850 return result;
3851 }
3852
3853 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3854 }
3855
3856 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3857}
3858
Marissa Wall2d814fb2019-04-09 18:52:57 +00003859status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3860 uint32_t h, PixelFormat format, uint32_t flags,
3861 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003862 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003863 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3864 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003865 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003866 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003867 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003868 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003869 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003870
Robert Carrc0df3122019-04-11 13:18:21 -07003871 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3872 "Expected only one of parentLayer or parentHandle to be non-null. "
3873 "Programmer error?");
3874
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003875 status_t result = NO_ERROR;
3876
3877 sp<Layer> layer;
3878
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003879 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003880
Evan Roskya1f1e152019-01-24 16:17:46 -08003881 bool primaryDisplayOnly = false;
3882
3883 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3884 // TODO b/64227542
3885 if (metadata.has(METADATA_WINDOW_TYPE)) {
3886 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3887 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003888 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003889 primaryDisplayOnly = true;
3890 }
3891 }
3892
Mathias Agopian3165cc22012-08-08 19:42:09 -07003893 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003894 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003895 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3896 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003897
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003898 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003899 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003900 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003901 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003902 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003903 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003904 // check if buffer size is set for color layer.
3905 if (w > 0 || h > 0) {
3906 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3907 int(w), int(h));
3908 return BAD_VALUE;
3909 }
3910
Vishnu Nairfa247b12020-02-11 08:58:26 -08003911 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3912 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003913 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003914 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003915 // check if buffer size is set for container layer.
3916 if (w > 0 || h > 0) {
3917 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3918 int(w), int(h));
3919 return BAD_VALUE;
3920 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003921 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3922 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003923 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003924 default:
3925 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003926 break;
3927 }
3928
Dan Stoza7d89d062015-04-30 13:29:25 -07003929 if (result != NO_ERROR) {
3930 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003931 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003932
Evan Roskya1f1e152019-01-24 16:17:46 -08003933 if (primaryDisplayOnly) {
3934 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003935 }
3936
Robert Carrb89ea9d2018-12-10 13:01:14 -08003937 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003938 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3939 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003940 if (result != NO_ERROR) {
3941 return result;
3942 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003943 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003944
3945 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003946 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003947}
3948
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003949std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3950 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003951
3952 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003953 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003954
Dan Stoza436ccf32018-06-21 12:10:12 -07003955 // Grab the state lock since we're accessing mCurrentState
3956 Mutex::Autolock lock(mStateLock);
3957
Cody Northropbc755282017-03-31 12:00:08 -06003958 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003959 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003960 while (matchFound) {
3961 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003962 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003963 if (layer->getName() == uniqueName) {
3964 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003965 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003966 }
3967 });
3968 }
3969
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003970 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003971 return uniqueName;
3972}
3973
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003974status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003975 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003976 LayerMetadata metadata, PixelFormat& format,
3977 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003978 sp<IGraphicBufferProducer>* gbp,
3979 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003980 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003981 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003982 case PIXEL_FORMAT_TRANSPARENT:
3983 case PIXEL_FORMAT_TRANSLUCENT:
3984 format = PIXEL_FORMAT_RGBA_8888;
3985 break;
3986 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003987 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003988 break;
3989 }
3990
chaviwb4c6e582019-08-16 14:35:07 -07003991 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003992 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003993 args.textureName = getNewTexture();
3994 {
3995 // Grab the SF state lock during this since it's the only safe way to access
3996 // RenderEngine when creating a BufferLayerConsumer
3997 // TODO: Check if this lock is still needed here
3998 Mutex::Autolock lock(mStateLock);
3999 layer = getFactory().createBufferQueueLayer(args);
4000 }
4001
Marissa Wallfd668622018-05-10 10:21:13 -07004002 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004003 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004004 *handle = layer->getHandle();
4005 *gbp = layer->getProducer();
4006 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004007 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004008
Marissa Wallfd668622018-05-10 10:21:13 -07004009 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004010 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004011}
4012
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004013status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004014 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004015 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004016 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004017 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004018 args.displayDevice = getDefaultDisplayDevice();
4019 args.textureName = getNewTexture();
4020 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004021 if (outTransformHint) {
4022 *outTransformHint = layer->getTransformHint();
4023 }
Marissa Wall61c58622018-07-18 10:12:20 -07004024 *handle = layer->getHandle();
4025 *outLayer = layer;
4026
4027 return NO_ERROR;
4028}
4029
Vishnu Nairfa247b12020-02-11 08:58:26 -08004030status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4031 uint32_t h, uint32_t flags, LayerMetadata metadata,
4032 sp<IBinder>* handle, sp<Layer>* outLayer) {
4033 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004034 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004035 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004036 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004037}
4038
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004039status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004040 uint32_t w, uint32_t h, uint32_t flags,
4041 LayerMetadata metadata, sp<IBinder>* handle,
4042 sp<Layer>* outLayer) {
4043 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004044 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004045 *handle = (*outLayer)->getHandle();
4046 return NO_ERROR;
4047}
4048
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004049void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004050 mLayersPendingRemoval.add(layer);
4051 mLayersRemoved = true;
4052 setTransactionFlags(eTransactionNeeded);
4053}
4054
Robert Carr695d5282018-12-18 15:27:58 -08004055void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004056{
Robert Carr2e102c92018-10-23 12:11:15 -07004057 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004058 // If a layer has a parent, we allow it to out-live it's handle
4059 // with the idea that the parent holds a reference and will eventually
4060 // be cleaned up. However no one cleans up the top-level so we do so
4061 // here.
4062 if (layer->getParent() == nullptr) {
4063 mCurrentState.layersSortedByZ.remove(layer);
4064 }
4065 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004066
4067 auto it = mLayersByLocalBinderToken.begin();
4068 while (it != mLayersByLocalBinderToken.end()) {
4069 if (it->second == layer) {
4070 it = mLayersByLocalBinderToken.erase(it);
4071 } else {
4072 it++;
4073 }
4074 }
4075
Robert Carr695d5282018-12-18 15:27:58 -08004076 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004077}
4078
Mathias Agopianb60314a2012-04-10 22:09:54 -07004079// ---------------------------------------------------------------------------
4080
Andy McFadden13a082e2012-08-24 10:16:42 -07004081void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004082 const auto display = getDefaultDisplayDeviceLocked();
4083 if (!display) return;
4084
4085 const sp<IBinder> token = display->getDisplayToken().promote();
4086 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004087
Jesse Hall01e29052013-02-19 16:13:35 -08004088 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004089 Vector<ComposerState> state;
4090 Vector<DisplayState> displays;
4091 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004092 d.what = DisplayState::eDisplayProjectionChanged |
4093 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004094 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004095 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004096 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004097 d.frame.makeInvalid();
4098 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004099 d.width = 0;
4100 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004101 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004102 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4103 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004104
Peiyong Lin65248e02020-04-18 21:15:07 -07004105 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004106
Dominik Laskowski83b88212018-12-11 13:34:06 -08004107 const nsecs_t vsyncPeriod = getVsyncPeriod();
4108 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004109
Brian Andersond0010582017-03-07 13:20:31 -08004110 // Use phase of 0 since phase is not known.
4111 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004112 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004113 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004114}
4115
4116void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004117 // Async since we may be called from the main thread.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004118 static_cast<void>(schedule([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004119}
4120
Peiyong Line9d809e2020-04-14 13:10:48 -07004121void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, hal::Vsync enabled) {
Ady Abraham27c70212019-06-11 10:52:26 -07004122 if (mHWCVsyncState != enabled) {
4123 getHwComposer().setVsyncEnabled(displayId, enabled);
4124 mHWCVsyncState = enabled;
4125 }
4126}
4127
Peiyong Lin65248e02020-04-18 21:15:07 -07004128void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004129 if (display->isVirtual()) {
4130 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004131 return;
4132 }
4133
Dominik Laskowski075d3172018-05-24 15:50:06 -07004134 const auto displayId = display->getId();
4135 LOG_ALWAYS_FATAL_IF(!displayId);
4136
Dominik Laskowski34157762018-10-31 13:07:19 -07004137 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004138
Peiyong Lin65248e02020-04-18 21:15:07 -07004139 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004140 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004141 return;
4142 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004143
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004144 display->setPowerMode(mode);
4145
Lloyd Pique4dccc412018-01-22 17:21:36 -08004146 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004147 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004148 }
4149
Peiyong Lin65248e02020-04-18 21:15:07 -07004150 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004151 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4152 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4153 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004154 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004155 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004156 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004157 mScheduler->onScreenAcquired(mAppConnectionHandle);
4158 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004159 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004160
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004161 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004162 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004163 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004164 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004165 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004166 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4167 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004168 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004169 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004170 mScheduler->disableHardwareVsync(true);
4171 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004172 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004173
Ady Abraham27c70212019-06-11 10:52:26 -07004174 // Make sure HWVsync is disabled before turning off the display
Peiyong Line9d809e2020-04-14 13:10:48 -07004175 setVsyncEnabledInHWC(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004176
Dominik Laskowski075d3172018-05-24 15:50:06 -07004177 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004178 mVisibleRegionsDirty = true;
4179 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004180 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004181 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004182 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004183 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004184 mScheduler->onScreenAcquired(mAppConnectionHandle);
4185 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004186 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004187 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004188 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004189 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004190 mScheduler->disableHardwareVsync(true);
4191 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004192 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004193 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004194 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004195 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004196 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004197 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004198
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004199 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004200 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004201 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004202 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004203 }
4204
Dominik Laskowski34157762018-10-31 13:07:19 -07004205 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004206}
4207
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004208void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004209 schedule([=]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004210 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004211 if (!display) {
4212 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4213 displayToken.get());
4214 } else if (display->isVirtual()) {
4215 ALOGW("Attempt to set power mode %d for virtual display", mode);
4216 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004217 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004218 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004219 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004220}
4221
Dominik Laskowskic2867142019-01-21 11:33:38 -08004222status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4223 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004224 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004225
Mathias Agopianbd115332013-04-18 16:41:04 -07004226 IPCThreadState* ipc = IPCThreadState::self();
4227 const int pid = ipc->getCallingPid();
4228 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004229
Mathias Agopianbd115332013-04-18 16:41:04 -07004230 if ((uid != AID_SHELL) &&
4231 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004232 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4233 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004234 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004235 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004236 // (this would indicate SF is stuck, but we want to be able to
4237 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004238 status_t err = mStateLock.timedLock(s2ns(1));
4239 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004240 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004241 StringAppendF(&result,
4242 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4243 "(no locks held)\n",
4244 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004245 }
4246
Dominik Laskowskic2867142019-01-21 11:33:38 -08004247 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004248 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004249 {"--dispsync"s,
4250 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004251 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004252 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4253 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4254 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4255 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4256 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4257 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004258 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004259 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4260 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004261
Dominik Laskowskic2867142019-01-21 11:33:38 -08004262 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004263
Dominik Laskowski46470112019-08-02 13:13:11 -07004264 const auto it = dumpers.find(flag);
4265 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004266 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004267 } else if (!asProto) {
4268 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004269 }
4270
Mathias Agopian9795c422009-08-26 16:36:26 -07004271 if (locked) {
4272 mStateLock.unlock();
4273 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004274
Dominik Laskowski46470112019-08-02 13:13:11 -07004275 if (it == dumpers.end()) {
4276 const LayersProto layersProto = dumpProtoFromMainThread();
4277 if (asProto) {
4278 result.append(layersProto.SerializeAsString());
4279 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004280 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004281 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4282 result.append(LayerProtoParser::layerTreeToString(layerTree));
4283 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004284 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004285 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004286 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004287 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004288 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004289 return NO_ERROR;
4290}
4291
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004292status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4293 if (asProto && mTracing.isEnabled()) {
4294 mTracing.writeToFileAsync();
4295 }
4296
4297 return doDump(fd, DumpArgs(), asProto);
4298}
4299
Dominik Laskowskic2867142019-01-21 11:33:38 -08004300void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004301 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004302 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004303}
4304
Dominik Laskowskic2867142019-01-21 11:33:38 -08004305void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004306 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004307
Dominik Laskowskic2867142019-01-21 11:33:38 -08004308 if (args.size() > 1) {
4309 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004310 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004311 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004312 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004313 }
Robert Carr2047fae2016-11-28 14:09:09 -08004314 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004315 } else {
4316 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004317 }
4318}
4319
Dominik Laskowskic2867142019-01-21 11:33:38 -08004320void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004321 const bool clearAll = args.size() < 2;
4322 const auto name = clearAll ? String8() : String8(args[1]);
4323
Edgar Arriaga844fa672020-01-16 14:21:42 -08004324 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004325 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004326 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004327 }
Robert Carr2047fae2016-11-28 14:09:09 -08004328 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004329
Svetoslavd85084b2014-03-20 10:28:31 -07004330 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004331}
4332
Dominik Laskowskic2867142019-01-21 11:33:38 -08004333void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4334 mTimeStats->parseArgs(asProto, args, result);
4335}
4336
Jamie Gennis6547ff42013-07-16 20:12:42 -07004337// This should only be called from the main thread. Otherwise it would need
4338// the lock and should use mCurrentState rather than mDrawingState.
4339void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004340 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004341 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004342 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004343
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004344 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004345}
4346
Yiwei Zhang5434a782018-12-05 18:06:32 -08004347void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004348 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004349
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004350 if (isLayerTripleBufferingDisabled())
4351 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004352
Yiwei Zhang5434a782018-12-05 18:06:32 -08004353 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4354 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4355 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4356 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4357 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4358 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004359 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004360}
4361
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004362void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004363 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004364
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004365 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004366 result.append("\n");
4367
Ady Abraham9e16a482019-12-03 17:19:41 -08004368 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004369 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004370 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004371 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004372
Steven Thomasd4071902020-03-24 16:02:53 -07004373 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004374 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004375 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004376 ", min: %.2f Hz, max: %.2f Hz",
Steven Thomasd4071902020-03-24 16:02:53 -07004377 policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004378 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4379 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004380 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4381 if (currentPolicy != policy) {
4382 StringAppendF(&result,
4383 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
4384 ", min: %.2f Hz, max: %.2f Hz\n\n",
4385 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
4386 currentPolicy.maxRefreshRate);
4387 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004388
Ana Krulecc2870422019-01-29 19:00:58 -08004389 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004390 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004391}
4392
Yiwei Zhang5434a782018-12-05 18:06:32 -08004393void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4394 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004395 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4396 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004397 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004398 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004399 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004400 }
David Sodman4a36e932017-11-07 14:29:47 -08004401 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004402 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004403 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004404 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4405 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004406}
4407
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004408void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4409 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004410 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4411 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004412 for (const auto& segment : history) {
4413 if (!segment.usedThirdBuffer) {
4414 stats.twoBufferTime += segment.totalTime;
4415 }
4416 if (segment.occupancyAverage < 1.0f) {
4417 stats.doubleBufferedTime += segment.totalTime;
4418 } else if (segment.occupancyAverage < 2.0f) {
4419 stats.tripleBufferedTime += segment.totalTime;
4420 }
4421 ++stats.numSegments;
4422 stats.totalTime += segment.totalTime;
4423 }
4424}
4425
Yiwei Zhang5434a782018-12-05 18:06:32 -08004426void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4427 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004428
4429 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4430 const size_t count = currentLayers.size();
4431 for (size_t i=0 ; i<count ; i++) {
4432 currentLayers[i]->dumpFrameEvents(result);
4433 }
4434}
4435
Yiwei Zhang5434a782018-12-05 18:06:32 -08004436void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004437 result.append("Buffering stats:\n");
4438 result.append(" [Layer name] <Active time> <Two buffer> "
4439 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004440 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004441 typedef std::tuple<std::string, float, float, float> BufferTuple;
4442 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004443 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004444 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004445 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004446 if (stats.numSegments == 0) {
4447 continue;
4448 }
4449 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4450 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4451 stats.totalTime;
4452 float doubleBufferRatio = static_cast<float>(
4453 stats.doubleBufferedTime) / stats.totalTime;
4454 float tripleBufferRatio = static_cast<float>(
4455 stats.tripleBufferedTime) / stats.totalTime;
4456 sorted.insert({activeTime, {name, twoBufferRatio,
4457 doubleBufferRatio, tripleBufferRatio}});
4458 }
4459 for (const auto& sortedPair : sorted) {
4460 float activeTime = sortedPair.first;
4461 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004462 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4463 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004464 }
4465 result.append("\n");
4466}
4467
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004469 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004470 const auto displayId = display->getId();
4471 if (!displayId) {
4472 continue;
4473 }
4474 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004475 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004476 continue;
4477 }
4478
Yiwei Zhang5434a782018-12-05 18:06:32 -08004479 StringAppendF(&result,
4480 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4481 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004482 uint8_t port;
4483 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004484 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004485 result.append("no identification data\n");
4486 continue;
4487 }
4488
4489 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004490 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004491 continue;
4492 }
4493
4494 const auto edid = parseEdid(data);
4495 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004496 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004497 continue;
4498 }
4499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004501 result.append(edid->displayName.data(), edid->displayName.length());
4502 result.append("\"\n");
4503 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004504}
4505
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004506void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4507 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004508 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004509 uint8_t port;
4510 DisplayIdentificationData data;
4511
4512 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4513 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4514 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4515 }
4516}
4517
Yiwei Zhang5434a782018-12-05 18:06:32 -08004518void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004519 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004520 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4521 StringAppendF(&result, "DisplayColorSetting: %s\n",
4522 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004523
4524 // TODO: print out if wide-color mode is active or not
4525
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004526 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004527 const auto displayId = display->getId();
4528 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004529 continue;
4530 }
4531
Yiwei Zhang5434a782018-12-05 18:06:32 -08004532 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004533 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004534 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004535 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004536 }
4537
Lloyd Pique32cbe282018-10-19 13:09:22 -07004538 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004539 StringAppendF(&result, " Current color mode: %s (%d)\n",
4540 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004541 }
4542 result.append("\n");
4543}
4544
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004545LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4546 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
4547 const auto display = getDefaultDisplayDeviceLocked();
4548
chaviw1d044282017-09-27 12:19:28 -07004549 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004550 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004551 layer->writeToProto(layersProto, traceFlags, display);
chaviw08f3cb22020-01-13 13:17:21 -08004552 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004553
chaviw1d044282017-09-27 12:19:28 -07004554 return layersProto;
4555}
4556
Alec Mouri6b9e9912020-01-21 10:50:24 -08004557void SurfaceFlinger::dumpHwc(std::string& result) const {
4558 getHwComposer().dump(result);
4559}
4560
Vishnu Nair0f085c62019-08-30 08:49:12 -07004561void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4562 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4563 // it.
4564 LayerProto* rootProto = layersProto.add_layers();
4565 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4566 rootProto->set_id(offscreenRootLayerId);
4567 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004568 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004569
4570 for (Layer* offscreenLayer : mOffscreenLayers) {
4571 // Add layer as child of the fake root
4572 rootProto->add_children(offscreenLayer->sequence);
4573
4574 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004575 LayerProto* layerProto =
4576 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004577 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004578 }
4579}
4580
Vishnu Nair8406fd72019-07-30 11:29:31 -07004581LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004582 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004583}
4584
Vishnu Nair0f085c62019-08-30 08:49:12 -07004585void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4586 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004587 result.append(schedule([this] {
4588 std::string result;
4589 for (Layer* offscreenLayer : mOffscreenLayers) {
4590 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4591 [&](Layer* layer) {
4592 layer->dumpCallingUidPid(result);
4593 });
4594 }
4595 return result;
4596 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004597}
4598
Dominik Laskowskic2867142019-01-21 11:33:38 -08004599void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4600 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004601 Colorizer colorizer(colorize);
4602
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004603 // figure out if we're stuck somewhere
4604 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004605 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004606 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4607
4608 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004609 * Dump library configuration.
4610 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004611
4612 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004613 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004614 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004615 appendSfConfigString(result);
4616 appendUiConfigString(result);
4617 appendGuiConfigString(result);
4618 result.append("\n");
4619
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004620 result.append("\nDisplay identification data:\n");
4621 dumpDisplayIdentificationData(result);
4622
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004623 result.append("\nWide-Color information:\n");
4624 dumpWideColorInfo(result);
4625
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004626 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004627 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004628 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004629 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004630 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004631
Andy McFadden41d67d72014-04-25 16:58:34 -07004632 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004633 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004634 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004635 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004636 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004637
Dan Stozab90cf072015-03-05 11:05:59 -08004638 dumpStaticScreenStats(result);
4639 result.append("\n");
4640
Alec Mouri40189b02019-03-05 15:07:54 -08004641 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4642 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4643 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004644
Dan Stozae77c7662016-05-13 11:37:28 -07004645 dumpBufferingStats(result);
4646
Andy McFadden4803b742012-09-24 19:07:20 -07004647 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004648 * Dump the visible layer list
4649 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004650 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004651 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4653 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004654 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004655
Chia-I Wu2f884132018-09-13 15:17:58 -07004656 {
Lloyd Pique207def92019-02-28 16:09:52 -08004657 StringAppendF(&result, "Composition layers\n");
4658 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004659 auto* compositionState = layer->getCompositionState();
4660 if (!compositionState) return;
4661
4662 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4663 layer->getDebugName() ? layer->getDebugName()
4664 : "<unknown>");
4665 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004666 });
4667 }
4668
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004669 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004670 * Dump Display state
4671 */
4672
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004673 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004674 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004675 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004676 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004677 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004678 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004679 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004680
4681 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004682 * Dump CompositionEngine state
4683 */
4684
4685 mCompositionEngine->dump(result);
4686
4687 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004688 * Dump SurfaceFlinger global state
4689 */
4690
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004691 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004692 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004693 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004694
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004695 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004696
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004697 DebugEGLImageTracker::getInstance()->dump(result);
4698
Dominik Laskowski075d3172018-05-24 15:50:06 -07004699 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004700 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4701 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004702 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4703 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004704 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004705 StringAppendF(&result,
4706 " transaction-flags : %08x\n"
4707 " gpu_to_cpu_unsupported : %d\n",
4708 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004709
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004710 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004711 displayId && getHwComposer().isConnected(*displayId)) {
4712 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004713 StringAppendF(&result,
4714 " refresh-rate : %f fps\n"
4715 " x-dpi : %f\n"
4716 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004717 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4718 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004719 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004720
Yiwei Zhang5434a782018-12-05 18:06:32 -08004721 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004722
Dan Stozae22aec72016-08-01 13:20:59 -07004723 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004724 * Tracing state
4725 */
4726 mTracing.dump(result);
4727 result.append("\n");
4728
4729 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004730 * HWC layer minidump
4731 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004732 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004733 const auto displayId = display->getId();
4734 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004735 continue;
4736 }
4737
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004739 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004740 const sp<DisplayDevice> displayDevice = display;
4741 mCurrentState.traverseInZOrder(
4742 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004743 result.append("\n");
4744 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004745
4746 /*
4747 * Dump HWComposer state
4748 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004749 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004750 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004751 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004752 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004753 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004754 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004755
4756 /*
4757 * Dump gralloc state
4758 */
4759 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4760 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004761
4762 /*
4763 * Dump VrFlinger state if in use.
4764 */
4765 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4766 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004767 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004768 result.append("\n");
4769 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004770
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004771 result.append(mTimeStats->miniDump());
4772 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004773}
4774
Chia-I Wu28f320b2018-05-03 11:02:56 -07004775void SurfaceFlinger::updateColorMatrixLocked() {
4776 mat4 colorMatrix;
4777 if (mGlobalSaturationFactor != 1.0f) {
4778 // Rec.709 luma coefficients
4779 float3 luminance{0.213f, 0.715f, 0.072f};
4780 luminance *= 1.0f - mGlobalSaturationFactor;
4781 mat4 saturationMatrix = mat4(
4782 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4783 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4784 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4785 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4786 );
4787 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4788 } else {
4789 colorMatrix = mClientColorMatrix * mDaltonizer();
4790 }
4791
4792 if (mCurrentState.colorMatrix != colorMatrix) {
4793 mCurrentState.colorMatrix = colorMatrix;
4794 mCurrentState.colorMatrixChanged = true;
4795 setTransactionFlags(eTransactionNeeded);
4796 }
4797}
4798
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004799status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004800#pragma clang diagnostic push
4801#pragma clang diagnostic error "-Wswitch-enum"
4802 switch (static_cast<ISurfaceComposerTag>(code)) {
4803 // These methods should at minimum make sure that the client requested
4804 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004805 case BOOT_FINISHED:
4806 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004807 case CREATE_DISPLAY:
4808 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004809 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004810 case GET_ANIMATION_FRAME_STATS:
4811 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004812 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004813 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004814 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004815 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4816 case SET_AUTO_LOW_LATENCY_MODE:
4817 case GET_GAME_CONTENT_TYPE_SUPPORT:
4818 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004819 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004820 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004821 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004822 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004823 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004824 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004825 case SET_GLOBAL_SHADOW_SETTINGS:
4826 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4827 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4828 // necessary permission dynamically. Don't use the permission cache for this check.
4829 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4830 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004831 IPCThreadState* ipc = IPCThreadState::self();
4832 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4833 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004834 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004835 }
Robert Carr1db73f62016-12-21 12:58:51 -08004836 return OK;
4837 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004838 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004839 IPCThreadState* ipc = IPCThreadState::self();
4840 const int pid = ipc->getCallingPid();
4841 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004842 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4843 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004844 return PERMISSION_DENIED;
4845 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004846 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004847 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004848 // Used by apps to hook Choreographer to SurfaceFlinger.
4849 case CREATE_DISPLAY_EVENT_CONNECTION:
4850 // The following calls are currently used by clients that do not
4851 // request necessary permissions. However, they do not expose any secret
4852 // information, so it is OK to pass them.
4853 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004854 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004855 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004856 case GET_PHYSICAL_DISPLAY_IDS:
4857 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004858 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004859 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004860 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004861 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004862 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004863 case GET_DISPLAY_STATS:
4864 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4865 // Calling setTransactionState is safe, because you need to have been
4866 // granted a reference to Client* and Handle* to do anything with it.
4867 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004868 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004869 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004870 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004871 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004872 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004873 // setFrameRate() is deliberately available for apps to call without any
4874 // special permissions.
4875 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004876 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4877 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004878 return OK;
4879 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004880 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004881 case CAPTURE_SCREEN:
4882 case ADD_REGION_SAMPLING_LISTENER:
4883 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004884 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004885 IPCThreadState* ipc = IPCThreadState::self();
4886 const int pid = ipc->getCallingPid();
4887 const int uid = ipc->getCallingUid();
4888 if ((uid != AID_GRAPHICS) &&
4889 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4890 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4891 return PERMISSION_DENIED;
4892 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004893 return OK;
4894 }
chaviw93df2ea2019-04-30 16:45:12 -07004895 case CAPTURE_SCREEN_BY_ID: {
4896 IPCThreadState* ipc = IPCThreadState::self();
4897 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004898 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004899 return OK;
4900 }
4901 return PERMISSION_DENIED;
4902 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004903 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004904
4905 // These codes are used for the IBinder protocol to either interrogate the recipient
4906 // side of the transaction for its canonical interface descriptor or to dump its state.
4907 // We let them pass by default.
4908 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4909 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4910 code == IBinder::SYSPROPS_TRANSACTION) {
4911 return OK;
4912 }
Ady Abraham07e54702020-04-16 15:05:37 -07004913 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004914 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004915 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004916 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4917 return OK;
4918 }
4919 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4920 return PERMISSION_DENIED;
4921#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004922}
4923
Ana Krulec13be8ad2018-08-21 02:43:56 +00004924status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4925 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004926 status_t credentialCheck = CheckTransactCodeCredentials(code);
4927 if (credentialCheck != OK) {
4928 return credentialCheck;
4929 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004930
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004931 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4932 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004933 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004934 IPCThreadState* ipc = IPCThreadState::self();
4935 const int uid = ipc->getCallingUid();
4936 if (CC_UNLIKELY(uid != AID_SYSTEM
4937 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004938 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004939 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004940 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004941 return PERMISSION_DENIED;
4942 }
4943 int n;
4944 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004945 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004946 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004947 return NO_ERROR;
4948 case 1002: // SHOW_UPDATES
4949 n = data.readInt32();
4950 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004951 invalidateHwcGeometry();
4952 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004953 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004954 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004955 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004956 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004957 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004958 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004959 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004960 setTransactionFlags(
4961 eTransactionNeeded|
4962 eDisplayTransactionNeeded|
4963 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004964 return NO_ERROR;
4965 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004966 case 1006:{ // send empty update
4967 signalRefresh();
4968 return NO_ERROR;
4969 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004970 case 1008: // toggle use of hw composer
4971 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004972 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004973 invalidateHwcGeometry();
4974 repaintEverything();
4975 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004976 case 1009: // toggle use of transform hint
4977 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004978 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004979 invalidateHwcGeometry();
4980 repaintEverything();
4981 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004982 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004983 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004984 reply->writeInt32(0);
4985 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004986 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004987 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004988 return NO_ERROR;
4989 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004990 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004991 if (!display) {
4992 return NAME_NOT_FOUND;
4993 }
4994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004995 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004996 return NO_ERROR;
4997 }
4998 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004999 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005000 // daltonize
5001 n = data.readInt32();
5002 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005003 case 1:
5004 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5005 break;
5006 case 2:
5007 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5008 break;
5009 case 3:
5010 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5011 break;
5012 default:
5013 mDaltonizer.setType(ColorBlindnessType::None);
5014 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005015 }
5016 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005017 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005018 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005019 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005020 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005021
5022 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005023 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005024 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005025 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005026 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005027 // apply a color matrix
5028 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005029 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005030 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005031 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005032 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005033 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005034 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005035 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005036 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005037 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005038 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005039
5040 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5041 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005042 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005043 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5044 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5045 }
5046
Chia-I Wu28f320b2018-05-03 11:02:56 -07005047 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005048 return NO_ERROR;
5049 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005050 case 1016: { // Unused.
5051 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005052 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005053 case 1017: {
5054 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005055 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005056 return NO_ERROR;
5057 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005058 case 1018: { // Modify Choreographer's phase offset
5059 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005060 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005061 return NO_ERROR;
5062 }
5063 case 1019: { // Modify SurfaceFlinger's phase offset
5064 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005065 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005066 return NO_ERROR;
5067 }
Irvel468051e2016-06-13 16:44:44 -07005068 case 1020: { // Layer updates interceptor
5069 n = data.readInt32();
5070 if (n) {
5071 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005072 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005073 }
5074 else{
5075 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005076 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005077 }
5078 return NO_ERROR;
5079 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005080 case 1021: { // Disable HWC virtual displays
5081 n = data.readInt32();
5082 mUseHwcVirtualDisplays = !n;
5083 return NO_ERROR;
5084 }
Romain Guy0147a172017-06-01 13:53:56 -07005085 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005086 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005087 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005088
Chia-I Wu28f320b2018-05-03 11:02:56 -07005089 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005090 return NO_ERROR;
5091 }
Romain Guy54f154a2017-10-24 21:40:32 +01005092 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005093 int32_t colorMode;
5094
Chia-I Wu0d711262018-05-21 15:19:35 -07005095 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005096 if (data.readInt32(&colorMode) == NO_ERROR) {
5097 mForceColorMode = static_cast<ColorMode>(colorMode);
5098 }
Romain Guy54f154a2017-10-24 21:40:32 +01005099 invalidateHwcGeometry();
5100 repaintEverything();
5101 return NO_ERROR;
5102 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005103 // Deprecate, use 1030 to check whether the device is color managed.
5104 case 1024: {
5105 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005106 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005107 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005108 n = data.readInt32();
5109 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005110 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005111 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005112 reply->writeInt32(NO_ERROR);
5113 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005114 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005115 mTracingEnabledChanged = mTracing.disable();
5116 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005117 reply->writeInt32(mTracing.writeToFile());
5118 } else {
5119 reply->writeInt32(NO_ERROR);
5120 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005121 }
5122 return NO_ERROR;
5123 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005124 case 1026: { // Get layer tracing status
5125 reply->writeBool(mTracing.isEnabled());
5126 return NO_ERROR;
5127 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005128 // Is a DisplayColorSetting supported?
5129 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005130 const auto display = getDefaultDisplayDevice();
5131 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005132 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005133 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005134
5135 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5136 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005137 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005138 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005139 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005140 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005141 reply->writeBool(true);
5142 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005143 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005144 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005145 break;
5146 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005147 reply->writeBool(
5148 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005149 break;
5150 }
5151 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005152 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005153 // Is VrFlinger active?
5154 case 1028: {
5155 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005156 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005157 return NO_ERROR;
5158 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005159 // Set buffer size for SF tracing (value in KB)
5160 case 1029: {
5161 n = data.readInt32();
5162 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5163 ALOGW("Invalid buffer size: %d KB", n);
5164 reply->writeInt32(BAD_VALUE);
5165 return BAD_VALUE;
5166 }
5167
5168 ALOGD("Updating trace buffer to %d KB", n);
5169 mTracing.setBufferSize(n * 1024);
5170 reply->writeInt32(NO_ERROR);
5171 return NO_ERROR;
5172 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005173 // Is device color managed?
5174 case 1030: {
5175 reply->writeBool(useColorManagement);
5176 return NO_ERROR;
5177 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005178 // Override default composition data space
5179 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5180 // && adb shell stop zygote && adb shell start zygote
5181 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5182 // adb shell stop zygote && adb shell start zygote
5183 case 1031: {
5184 Mutex::Autolock _l(mStateLock);
5185 n = data.readInt32();
5186 if (n) {
5187 n = data.readInt32();
5188 if (n) {
5189 Dataspace dataspace = static_cast<Dataspace>(n);
5190 if (!validateCompositionDataspace(dataspace)) {
5191 return BAD_VALUE;
5192 }
5193 mDefaultCompositionDataspace = dataspace;
5194 }
5195 n = data.readInt32();
5196 if (n) {
5197 Dataspace dataspace = static_cast<Dataspace>(n);
5198 if (!validateCompositionDataspace(dataspace)) {
5199 return BAD_VALUE;
5200 }
5201 mWideColorGamutCompositionDataspace = dataspace;
5202 }
5203 } else {
5204 // restore composition data space.
5205 mDefaultCompositionDataspace = defaultCompositionDataspace;
5206 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5207 }
5208 return NO_ERROR;
5209 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005210 // Set trace flags
5211 case 1033: {
5212 n = data.readUint32();
5213 ALOGD("Updating trace flags to 0x%x", n);
5214 mTracing.setTraceFlags(n);
5215 reply->writeInt32(NO_ERROR);
5216 return NO_ERROR;
5217 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005218 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005219 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005220 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005221 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005222 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005223 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005224 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005225 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005226 } else {
5227 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005228 }
5229 return NO_ERROR;
5230 }
Ady Abraham34392f72019-04-10 11:29:27 -07005231 case 1035: {
5232 n = data.readInt32();
5233 mDebugDisplayConfigSetByBackdoor = false;
5234 if (n >= 0) {
5235 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005236 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005237 if (result != NO_ERROR) {
5238 return result;
5239 }
5240 mDebugDisplayConfigSetByBackdoor = true;
5241 }
5242 return NO_ERROR;
5243 }
Ady Abraham07e54702020-04-16 15:05:37 -07005244 case 1036: {
5245 if (data.readInt32() > 0) {
5246 status_t result =
5247 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5248 if (result != NO_ERROR) {
5249 return result;
5250 }
5251 } else {
5252 mDebugFrameRateFlexibilityToken = nullptr;
5253 }
5254 return NO_ERROR;
5255 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005256 }
5257 }
5258 return err;
5259}
5260
Steven Thomas6d8110b2017-08-31 18:24:21 -07005261void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005262 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005263 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005264}
5265
Ana Krulec7d1d6832018-12-27 11:10:09 -08005266void SurfaceFlinger::repaintEverythingForHWC() {
5267 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005268 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005269 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005270}
5271
Ady Abrahama09852a2020-02-20 14:23:42 -08005272void SurfaceFlinger::kernelTimerChanged(bool expired) {
5273 static bool updateOverlay =
5274 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5275 if (!updateOverlay || !mRefreshRateOverlay) return;
5276
5277 // Update the overlay on the main thread to avoid race conditions with
5278 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005279 static_cast<void>(schedule([=]() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahama09852a2020-02-20 14:23:42 -08005280 if (mRefreshRateOverlay) {
5281 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5282 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005283 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005284 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5285 if (mDesiredActiveConfigChanged) {
5286 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5287 mDesiredActiveConfig.configId);
5288 }
5289
5290 return mRefreshRateConfigs->getCurrentRefreshRate();
5291 }();
5292 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5293
5294 if (current != min) {
5295 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5296 mEventQueue->invalidate();
5297 }
5298 }
5299 }));
5300}
5301
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005302// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5303class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005304public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005305 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5306 ~WindowDisconnector() {
5307 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005308 }
5309
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005310private:
5311 ANativeWindow* mWindow;
5312 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005313};
5314
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005315status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005316 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005317 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5318 const Rect& sourceCrop, uint32_t reqWidth,
5319 uint32_t reqHeight, bool useIdentityTransform,
5320 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005321 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005322
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005323 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005324
Dominik Laskowski718f9602019-11-09 20:01:35 -08005325 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5326 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5327 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5328 renderAreaRotation = ui::Transform::ROT_0;
5329 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005330
Chia-I Wu20261cb2018-08-23 12:55:44 -07005331 sp<DisplayDevice> display;
5332 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005333 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005334
Chia-I Wu20261cb2018-08-23 12:55:44 -07005335 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005336 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005337
Chia-I Wucb023152018-08-28 12:57:23 -07005338 // set the requested width/height to the logical display viewport size
5339 // by default
5340 if (reqWidth == 0 || reqHeight == 0) {
5341 reqWidth = uint32_t(display->getViewport().width());
5342 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005343 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005344 }
5345
Peiyong Lin0e003c92018-09-17 11:09:51 -07005346 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005347 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005348 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5349 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005350 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005351 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005352}
5353
chaviw93df2ea2019-04-30 16:45:12 -07005354static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5355 switch (colorMode) {
5356 case ColorMode::DISPLAY_P3:
5357 case ColorMode::BT2100_PQ:
5358 case ColorMode::BT2100_HLG:
5359 case ColorMode::DISPLAY_BT2020:
5360 return Dataspace::DISPLAY_P3;
5361 default:
5362 return Dataspace::V0_SRGB;
5363 }
5364}
5365
Martin Liu4a322352020-03-24 21:30:38 +08005366status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5367 static constexpr int kFifoPriority = 2;
5368 static constexpr int kOtherPriority = 0;
5369
5370 struct sched_param param = {0};
5371 int sched_policy;
5372 if (enabled) {
5373 sched_policy = SCHED_FIFO;
5374 param.sched_priority = kFifoPriority;
5375 } else {
5376 sched_policy = SCHED_OTHER;
5377 param.sched_priority = kOtherPriority;
5378 }
5379
5380 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5381 return -errno;
5382 }
5383 return NO_ERROR;
5384}
5385
chaviw93df2ea2019-04-30 16:45:12 -07005386const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5387 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5388 if (displayToken) {
5389 return getDisplayDeviceLocked(displayToken);
5390 }
5391 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5392 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005393 return getDisplayByLayerStack(displayOrLayerStack);
5394}
5395
5396const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005397 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005398 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005399 return display;
5400 }
5401 }
5402 return nullptr;
5403}
5404
5405status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5406 sp<GraphicBuffer>* outBuffer) {
5407 sp<DisplayDevice> display;
5408 uint32_t width;
5409 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005410 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005411 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005412 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005413 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5414 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005415 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005416 }
5417
5418 width = uint32_t(display->getViewport().width());
5419 height = uint32_t(display->getViewport().height());
5420
Dominik Laskowski718f9602019-11-09 20:01:35 -08005421 const auto orientation = display->getOrientation();
5422 captureOrientation = ui::Transform::toRotationFlags(orientation);
5423
5424 switch (captureOrientation) {
5425 case ui::Transform::ROT_90:
5426 captureOrientation = ui::Transform::ROT_270;
5427 break;
5428
5429 case ui::Transform::ROT_270:
5430 captureOrientation = ui::Transform::ROT_90;
5431 break;
5432
5433 case ui::Transform::ROT_INVALID:
5434 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5435 captureOrientation = ui::Transform::ROT_0;
5436 break;
5437
5438 default:
5439 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005440 }
chaviw93df2ea2019-04-30 16:45:12 -07005441 *outDataspace =
5442 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5443 }
5444
5445 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5446 false /* captureSecureLayers */);
5447
5448 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5449 std::placeholders::_1);
5450 bool ignored = false;
5451 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5452 false /* useIdentityTransform */,
5453 ignored /* outCapturedSecureLayers */);
5454}
5455
Robert Carr866455f2019-04-02 16:28:26 -07005456status_t SurfaceFlinger::captureLayers(
5457 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5458 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5459 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5460 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005461 ATRACE_CALL();
5462
5463 class LayerRenderArea : public RenderArea {
5464 public:
Robert Carr578038f2018-03-09 12:25:24 -08005465 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005466 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005467 bool childrenOnly, const Rect& displayViewport)
5468 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005469 mLayer(layer),
5470 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005471 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005472 mFlinger(flinger),
5473 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005474 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005475 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005476 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005477 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005478 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005479 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005480 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005481 }
chaviwa76b2712017-09-20 12:02:26 -07005482 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005483 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005484 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005485 Rect getSourceCrop() const override {
5486 if (mCrop.isEmpty()) {
5487 return getBounds();
5488 } else {
5489 return mCrop;
5490 }
5491 }
Robert Carr578038f2018-03-09 12:25:24 -08005492 class ReparentForDrawing {
5493 public:
5494 const sp<Layer>& oldParent;
5495 const sp<Layer>& newParent;
5496
Vishnu Nair4351ad52019-02-11 14:13:02 -08005497 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5498 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005499 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005500 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005501 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5502 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005503 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005504 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005505 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005506 };
5507
5508 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005509 const Rect sourceCrop = getSourceCrop();
5510 // no need to check rotation because there is none
5511 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5512 sourceCrop.height() != getReqHeight();
5513
Robert Carr578038f2018-03-09 12:25:24 -08005514 if (!mChildrenOnly) {
5515 mTransform = mLayer->getTransform().inverse();
5516 drawLayers();
5517 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005518 uint32_t w = static_cast<uint32_t>(getWidth());
5519 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005520 // In the "childrenOnly" case we reparent the children to a screenshot
5521 // layer which has no properties set and which does not draw.
5522 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005523 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5524 "Screenshot Parent"s, w, h, 0,
5525 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005526
Vishnu Nair4351ad52019-02-11 14:13:02 -08005527 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005528 drawLayers();
5529 }
5530 }
chaviwa76b2712017-09-20 12:02:26 -07005531
chaviwa76b2712017-09-20 12:02:26 -07005532 private:
chaviw7206d492017-11-10 16:16:12 -08005533 const sp<Layer> mLayer;
5534 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005535
Peiyong Linefefaac2018-08-17 12:27:51 -07005536 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005537 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005538
5539 SurfaceFlinger* mFlinger;
5540 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005541 };
5542
Robert Carrc0df3122019-04-11 13:18:21 -07005543 int reqWidth = 0;
5544 int reqHeight = 0;
5545 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005546 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005547 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005548 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005549 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005550 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005551
Alec Mouri9a02eda2020-04-21 17:39:34 -07005552 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005553 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5554 ALOGE("captureLayers called with an invalid or removed parent");
5555 return NAME_NOT_FOUND;
5556 }
5557
5558 const int uid = IPCThreadState::self()->getCallingUid();
5559 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5560 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5561 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5562 return PERMISSION_DENIED;
5563 }
5564
Vishnu Nairefc42e22019-12-03 17:36:12 -08005565 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005566 if (sourceCrop.width() <= 0) {
5567 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005568 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005569 }
5570
5571 if (sourceCrop.height() <= 0) {
5572 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005573 crop.bottom = parentSourceBounds.getHeight();
5574 }
5575
5576 if (crop.isEmpty() || frameScale <= 0.0f) {
5577 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5578 // crop was not specified, or an invalid frame scale was provided.
5579 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005580 }
5581 reqWidth = crop.width() * frameScale;
5582 reqHeight = crop.height() * frameScale;
5583
5584 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005585 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005586 if (excludeLayer != nullptr) {
5587 excludeLayers.emplace(excludeLayer);
5588 } else {
5589 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5590 return NAME_NOT_FOUND;
5591 }
5592 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005593
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005594 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005595 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005596 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005597 }
5598
5599 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005600 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005601
Chia-I Wu20261cb2018-08-23 12:55:44 -07005602 // really small crop or frameScale
5603 if (reqWidth <= 0) {
5604 reqWidth = 1;
5605 }
5606 if (reqHeight <= 0) {
5607 reqHeight = 1;
5608 }
5609
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005610 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5611 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005612 auto traverseLayers = [parent, childrenOnly,
5613 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005614 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5615 if (!layer->isVisible()) {
5616 return;
Robert Carr578038f2018-03-09 12:25:24 -08005617 } else if (childrenOnly && layer == parent.get()) {
5618 return;
chaviwa76b2712017-09-20 12:02:26 -07005619 }
Robert Carr866455f2019-04-02 16:28:26 -07005620
5621 sp<Layer> p = layer;
5622 while (p != nullptr) {
5623 if (excludeLayers.count(p) != 0) {
5624 return;
5625 }
5626 p = p->getParent();
5627 }
5628
chaviwa76b2712017-09-20 12:02:26 -07005629 visitor(layer);
5630 });
5631 };
Robert Carr108b2c72019-04-02 16:32:58 -07005632
5633 bool outCapturedSecureLayers = false;
5634 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5635 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005636}
5637
5638status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5639 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005640 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005641 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005642 bool useIdentityTransform,
5643 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005644 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005645
Peiyong Lin0e003c92018-09-17 11:09:51 -07005646 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005647 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5648 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005649 *outBuffer =
5650 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5651 static_cast<android_pixel_format>(reqPixelFormat), 1,
5652 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005653
Robert Carr108b2c72019-04-02 16:32:58 -07005654 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005655 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005656}
5657
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005658status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5659 TraverseLayersFunction traverseLayers,
5660 const sp<GraphicBuffer>& buffer,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005661 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005662 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005663 const int uid = IPCThreadState::self()->getCallingUid();
5664 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5665
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005666 status_t result;
5667 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005668
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005669 do {
5670 std::tie(result, syncFd) =
5671 schedule([&] {
5672 if (mRefreshPending) {
5673 ATRACE_NAME("Skipping screenshot for now");
5674 return std::make_pair(EAGAIN, -1);
5675 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005676
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005677 status_t result = NO_ERROR;
5678 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005679
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005680 Mutex::Autolock lock(mStateLock);
5681 renderArea.render([&] {
5682 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5683 useIdentityTransform, forSystem, &fd,
5684 regionSampling, outCapturedSecureLayers);
5685 });
5686
5687 return std::make_pair(result, fd);
5688 }).get();
5689 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005690
5691 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005692 sync_wait(syncFd, -1);
5693 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005694 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005695
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005696 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005697}
5698
chaviwa76b2712017-09-20 12:02:26 -07005699void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005700 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005701 ANativeWindowBuffer* buffer, bool useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005702 bool regionSampling, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005703 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005704
chaviwa76b2712017-09-20 12:02:26 -07005705 const auto reqWidth = renderArea.getReqWidth();
5706 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005707 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005708 const auto transform = renderArea.getTransform();
5709 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005710 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005711
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005712 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005713 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005714
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005715 // assume that bounds are never offset, and that they are the same as the
5716 // buffer bounds.
5717 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005718 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005719 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005720
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005721 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5722 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005723
chaviw50da5042018-04-09 13:49:37 -07005724 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005725
Vishnu Nair9b079a22020-01-21 14:36:08 -08005726 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005727 fillLayer.source.buffer.buffer = nullptr;
5728 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005729 fillLayer.geometry.boundaries =
5730 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005731 fillLayer.alpha = half(alpha);
5732 clientCompositionLayers.push_back(fillLayer);
5733
Yichi Chen40773d92020-04-01 10:10:18 +08005734 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005735 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005736 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005737 const bool supportProtectedContent = false;
5738 Region clip(renderArea.getBounds());
5739 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5740 clip,
5741 useIdentityTransform,
Alec Mouri5a6d8572020-03-23 23:56:15 -07005742 layer->needsFilteringForScreenshots(renderArea.getDisplayDevice(), transform) ||
5743 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005744 renderArea.isSecure(),
5745 supportProtectedContent,
5746 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005747 displayViewport,
5748 clientCompositionDisplay.outputDataspace,
5749 true, /* realContentIsVisible */
5750 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005751 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005752 std::vector<compositionengine::LayerFE::LayerSettings> results =
5753 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005754 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005755 for (auto& settings : results) {
5756 settings.geometry.positionTransform =
5757 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupinf11eba52020-04-20 18:42:31 -07005758 // There's no need to process blurs when we're executing region sampling,
5759 // we're just trying to understand what we're drawing, and doing so without
5760 // blurs is already a pretty good approximation.
5761 if (regionSampling) {
5762 settings.backgroundBlurRadius = 0;
5763 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005764 }
Yichi Chen40773d92020-04-01 10:10:18 +08005765 clientCompositionLayers.insert(clientCompositionLayers.end(),
5766 std::make_move_iterator(results.begin()),
5767 std::make_move_iterator(results.end()));
5768 renderedLayers.push_back(layer);
5769 }
chaviwa76b2712017-09-20 12:02:26 -07005770 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005771
Yichi Chen40773d92020-04-01 10:10:18 +08005772 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5773 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005774 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005775 clientCompositionLayerPointers.begin(),
5776 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005777
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005778 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005779 // Use an empty fence for the buffer fence, since we just created the buffer so
5780 // there is no need for synchronization with the GPU.
5781 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005782 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005783 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005784 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005785 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005786
5787 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005788
5789 if (*outSyncFd >= 0) {
5790 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5791 for (auto* layer : renderedLayers) {
5792 layer->onLayerDisplayed(releaseFence);
5793 }
5794 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005795}
5796
chaviwa76b2712017-09-20 12:02:26 -07005797status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5798 TraverseLayersFunction traverseLayers,
5799 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005800 bool useIdentityTransform, bool forSystem,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005801 int* outSyncFd, bool regionSampling,
5802 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005803 ATRACE_CALL();
5804
chaviwa76b2712017-09-20 12:02:26 -07005805 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005806 outCapturedSecureLayers =
5807 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005808 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005809
Robert Carr03480e22018-01-04 16:02:06 -08005810 // We allow the system server to take screenshots of secure layers for
5811 // use in situations like the Screen-rotation animation and place
5812 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005813 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005814 ALOGW("FB is protected: PERMISSION_DENIED");
5815 return PERMISSION_DENIED;
5816 }
Lucas Dupinf11eba52020-04-20 18:42:31 -07005817 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5818 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005819 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005820}
5821
chaviw95ef3c42019-02-14 10:55:09 -08005822void SurfaceFlinger::setInputWindowsFinished() {
5823 Mutex::Autolock _l(mStateLock);
5824
5825 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005826
chaviw95ef3c42019-02-14 10:55:09 -08005827 mTransactionCV.broadcast();
5828}
chaviw5f21a5e2019-02-14 10:00:34 -08005829
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005830// ---------------------------------------------------------------------------
5831
Edgar Arriaga844fa672020-01-16 14:21:42 -08005832void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5833 layersSortedByZ.traverse(visitor);
5834}
5835
Dan Stoza412903f2017-04-27 13:42:17 -07005836void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5837 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005838}
5839
Dan Stoza412903f2017-04-27 13:42:17 -07005840void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5841 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005842}
5843
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005844void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005845 const LayerVector::Visitor& visitor) {
5846 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005847 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005848 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005849 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005850 continue;
5851 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005852 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005853 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005854 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005855 return;
5856 }
chaviwa76b2712017-09-20 12:02:26 -07005857 if (!layer->isVisible()) {
5858 return;
5859 }
5860 visitor(layer);
5861 });
5862 }
5863}
5864
Steven Thomasd4071902020-03-24 16:02:53 -07005865status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5866 const sp<DisplayDevice>& display,
5867 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005868 Mutex::Autolock lock(mStateLock);
5869
Steven Thomasd4071902020-03-24 16:02:53 -07005870 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5871 "Can only set override policy on the primary display");
5872 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5873
Dominik Laskowski22488f62019-03-28 09:53:04 -07005874 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005875 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5876 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5877 // it should go thru setDesiredActiveConfig, similar to primary display.
5878 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5879 const auto displayId = display->getId();
5880 LOG_ALWAYS_FATAL_IF(!displayId);
5881
Peiyong Line9d809e2020-04-14 13:10:48 -07005882 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005883 constraints.desiredTimeNanos = systemTime();
5884 constraints.seamlessRequired = false;
5885
Peiyong Line9d809e2020-04-14 13:10:48 -07005886 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005887 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5888 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005889 constraints, &timeline) < 0) {
5890 return BAD_VALUE;
5891 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005892 if (timeline.refreshRequired) {
5893 repaintEverythingForHWC();
5894 }
5895
Steven Thomasd4071902020-03-24 16:02:53 -07005896 display->setActiveConfig(policy->defaultConfig);
5897 const nsecs_t vsyncPeriod = getHwComposer()
5898 .getConfigs(*displayId)[policy->defaultConfig.value()]
5899 ->getVsyncPeriod();
5900 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5901 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005902 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005903 }
5904
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005905 if (mDebugDisplayConfigSetByBackdoor) {
5906 // ignore this request as config is overridden by backdoor
5907 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005908 }
5909
Steven Thomasd4071902020-03-24 16:02:53 -07005910 status_t setPolicyResult = overridePolicy
5911 ? mRefreshRateConfigs->setOverridePolicy(policy)
5912 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5913 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005914 return BAD_VALUE;
5915 }
Steven Thomasd4071902020-03-24 16:02:53 -07005916 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005917 return NO_ERROR;
5918 }
Steven Thomasd4071902020-03-24 16:02:53 -07005919 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005920
5921 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
Steven Thomasd4071902020-03-24 16:02:53 -07005922 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
5923 currentPolicy.maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005924
5925 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5926 // that listeners that care about a change in allowed configs can get the notification.
5927 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005928 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005929 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5930 .getVsyncPeriod();
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005931 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005932 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005933
Ana Krulec3f6a2062020-01-23 15:48:01 -08005934 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005935 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005936 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5937 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005938 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005939 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005940 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005941
Ady Abrahamabc27602020-04-08 17:20:29 -07005942 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5943 ALOGV("switching to Scheduler preferred config %d",
5944 preferredRefreshRate.getConfigId().value());
5945 setDesiredActiveConfig(
5946 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005947 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005948 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5949 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005950 }
5951
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005952 return NO_ERROR;
5953}
5954
Ana Krulec0782b882019-10-15 17:34:54 -07005955status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005956 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005957 float maxRefreshRate) {
5958 ATRACE_CALL();
5959
5960 if (!displayToken) {
5961 return BAD_VALUE;
5962 }
5963
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005964 auto future = schedule([=]() -> status_t {
Ana Krulec234bb162019-11-10 22:55:55 +01005965 const auto display = getDisplayDeviceLocked(displayToken);
5966 if (!display) {
5967 ALOGE("Attempt to set desired display configs for invalid display token %p",
5968 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005969 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01005970 } else if (display->isVirtual()) {
5971 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005972 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01005973 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005974 using Policy = scheduler::RefreshRateConfigs::Policy;
5975 const Policy policy{HwcConfigIndexType(defaultConfig), minRefreshRate, maxRefreshRate};
5976 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005977
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005978 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
5979 }
5980 });
5981
5982 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01005983}
5984
5985status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005986 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005987 float* outMinRefreshRate,
5988 float* outMaxRefreshRate) {
5989 ATRACE_CALL();
5990
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005991 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005992 return BAD_VALUE;
5993 }
5994
5995 Mutex::Autolock lock(mStateLock);
5996 const auto display = getDisplayDeviceLocked(displayToken);
5997 if (!display) {
5998 return NAME_NOT_FOUND;
5999 }
6000
6001 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006002 scheduler::RefreshRateConfigs::Policy policy =
6003 mRefreshRateConfigs->getDisplayManagerPolicy();
6004 *outDefaultConfig = policy.defaultConfig.value();
6005 *outMinRefreshRate = policy.minRefreshRate;
6006 *outMaxRefreshRate = policy.maxRefreshRate;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006007 return NO_ERROR;
6008 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006009 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006010 } else {
6011 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006012 LOG_FATAL_IF(!displayId);
6013
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006014 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6015 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6016 *outMinRefreshRate = 1e9f / vsyncPeriod;
6017 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6018 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006019 }
Ana Krulec0782b882019-10-15 17:34:54 -07006020}
6021
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006022void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006023 mFlinger->setInputWindowsFinished();
6024}
6025
Alec Mouri9a02eda2020-04-21 17:39:34 -07006026wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6027 Mutex::Autolock _l(mStateLock);
6028 return fromHandleLocked(handle);
6029}
6030
6031wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006032 BBinder* b = nullptr;
6033 if (handle) {
6034 b = handle->localBinder();
6035 }
Robert Carrc0df3122019-04-11 13:18:21 -07006036 if (b == nullptr) {
6037 return nullptr;
6038 }
6039 auto it = mLayersByLocalBinderToken.find(b);
6040 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006041 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006042 }
6043 return nullptr;
6044}
6045
Dominik Laskowski75848362019-11-11 17:57:20 -08006046void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006047 mNumLayers++;
6048 mScheduler->registerLayer(layer);
6049}
6050
6051void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6052 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006053 removeFromOffscreenLayers(layer);
6054}
6055
6056// WARNING: ONLY CALL THIS FROM LAYER DTOR
6057// Here we add children in the current state to offscreen layers and remove the
6058// layer itself from the offscreen layer list. Since
6059// this is the dtor, it is safe to access the current state. This keeps us
6060// from dangling children layers such that they are not reachable from the
6061// Drawing state nor the offscreen layer list
6062// See b/141111965
6063void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6064 for (auto& child : layer->getCurrentChildren()) {
6065 mOffscreenLayers.emplace(child.get());
6066 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006067 mOffscreenLayers.erase(layer);
6068}
6069
Alec Mouri4545a8a2019-08-08 20:05:32 -07006070void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6071 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6072}
6073
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006074status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6075 float lightPosY, float lightPosZ,
6076 float lightRadius) {
6077 Mutex::Autolock _l(mStateLock);
6078 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6079 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6080 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6081 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6082 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6083
6084 // these values are overridden when calculating the shadow settings for a layer.
6085 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6086 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006087 return NO_ERROR;
6088}
6089
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006090const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6091 const {
6092 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6093 // on the work to remove the table in that bug rather than adding more to
6094 // it.
6095 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6096 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6097 // supported, and exposed via the
6098 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6099 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6100 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6101 };
6102 return genericLayerMetadataKeyMap;
6103}
6104
Steven Thomas62a4cf82020-01-31 12:04:03 -08006105status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6106 int8_t compatibility) {
6107 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6108 return BAD_VALUE;
6109 }
6110
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006111 static_cast<void>(schedule([=]() NO_THREAD_SAFETY_ANALYSIS {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006112 Mutex::Autolock lock(mStateLock);
6113 if (authenticateSurfaceTextureLocked(surface)) {
6114 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6115 if (layer->setFrameRate(
6116 Layer::FrameRate(frameRate,
6117 Layer::FrameRate::convertCompatibility(compatibility)))) {
6118 setTransactionFlags(eTraversalNeeded);
6119 }
6120 } else {
6121 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6122 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006123 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006124 return NO_ERROR;
6125 }));
6126
Steven Thomas62a4cf82020-01-31 12:04:03 -08006127 return NO_ERROR;
6128}
6129
Steven Thomasd4071902020-03-24 16:02:53 -07006130status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6131 if (!outToken) {
6132 return BAD_VALUE;
6133 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006134
6135 auto future = schedule([this] {
6136 status_t result = NO_ERROR;
6137 sp<IBinder> token;
6138
Steven Thomasd4071902020-03-24 16:02:53 -07006139 if (mFrameRateFlexibilityTokenCount == 0) {
6140 // |mStateLock| not needed as we are on the main thread
6141 const auto display = getDefaultDisplayDeviceLocked();
6142
6143 // This is a little racy, but not in a way that hurts anything. As we grab the
6144 // defaultConfig from the display manager policy, we could be setting a new display
6145 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6146 // matter for the override policy though, since we set allowGroupSwitching to true, so
6147 // it's not a problem.
6148 scheduler::RefreshRateConfigs::Policy overridePolicy;
6149 overridePolicy.defaultConfig =
6150 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6151 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006152 constexpr bool kOverridePolicy = true;
6153 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006154 }
6155
6156 if (result == NO_ERROR) {
6157 mFrameRateFlexibilityTokenCount++;
6158 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6159 // below, is something to consider carefully. The lifetime of the
6160 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6161 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6162 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6163 // in this case, for two reasons:
6164 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6165 // the program exits is via a crash. So we won't have a situation where the
6166 // SurfaceFlinger object is dead but the process is still up.
6167 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6168 // if condition 1 were changed, the problem would only show up when running CTS tests,
6169 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006170 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006171 [this]() { onFrameRateFlexibilityTokenReleased(); });
6172 ALOGD("Frame rate flexibility token acquired. count=%d",
6173 mFrameRateFlexibilityTokenCount);
6174 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006175
6176 return std::make_pair(result, token);
6177 });
6178
6179 status_t result;
6180 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006181 return result;
6182}
6183
6184void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006185 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006186 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6187 "Failed tracking frame rate flexibility tokens");
6188 mFrameRateFlexibilityTokenCount--;
6189 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6190 if (mFrameRateFlexibilityTokenCount == 0) {
6191 // |mStateLock| not needed as we are on the main thread
6192 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006193 constexpr bool kOverridePolicy = true;
6194 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006195 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6196 }
6197 }));
6198}
6199
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006200} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006201
Mathias Agopian3f844832013-08-07 21:24:32 -07006202#if defined(__gl_h_)
6203#error "don't include gl/gl.h in this file"
6204#endif
6205
6206#if defined(__gl2_h_)
6207#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006208#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006209
6210// TODO(b/129481165): remove the #pragma below and fix conversion issues
6211#pragma clang diagnostic pop // ignored "-Wconversion"