blob: 9c151c0aed50ea2a4c70ce0deb70f6e5d7e29914 [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"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Peiyong Line9d809e2020-04-14 13:10:48 -0700143namespace hal = android::hardware::graphics::composer::hal;
144
Steven Thomasb02664d2017-07-26 18:48:28 -0700145namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700146
147#pragma clang diagnostic push
148#pragma clang diagnostic error "-Wswitch-enum"
149
150bool isWideColorMode(const ColorMode colorMode) {
151 switch (colorMode) {
152 case ColorMode::DISPLAY_P3:
153 case ColorMode::ADOBE_RGB:
154 case ColorMode::DCI_P3:
155 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700156 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700157 case ColorMode::BT2100_PQ:
158 case ColorMode::BT2100_HLG:
159 return true;
160 case ColorMode::NATIVE:
161 case ColorMode::STANDARD_BT601_625:
162 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
163 case ColorMode::STANDARD_BT601_525:
164 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
165 case ColorMode::STANDARD_BT709:
166 case ColorMode::SRGB:
167 return false;
168 }
169 return false;
170}
171
172#pragma clang diagnostic pop
173
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700174template <typename Mutex>
175struct ConditionalLockGuard {
176 ConditionalLockGuard(Mutex& mutex, bool lock) : mutex(mutex), lock(lock) {
177 if (lock) mutex.lock();
Steven Thomasb02664d2017-07-26 18:48:28 -0700178 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700179
180 ~ConditionalLockGuard() {
181 if (lock) mutex.unlock();
182 }
183
184 Mutex& mutex;
185 const bool lock;
Steven Thomasb02664d2017-07-26 18:48:28 -0700186};
Peiyong Linfca547f2018-07-09 13:03:33 -0700187
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700188using ConditionalLock = ConditionalLockGuard<Mutex>;
189
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800190// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
191constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
192
193float getDensityFromProperty(const char* property, bool required) {
194 char value[PROPERTY_VALUE_MAX];
195 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
196 if (!density && required) {
197 ALOGE("%s must be defined as a build property", property);
198 return FALLBACK_DENSITY;
199 }
200 return density / 160.f;
201}
202
Peiyong Lin9d846a52018-11-05 13:18:20 -0800203// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
204bool validateCompositionDataspace(Dataspace dataspace) {
205 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
206}
207
Steven Thomasd4071902020-03-24 16:02:53 -0700208class FrameRateFlexibilityToken : public BBinder {
209public:
210 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
211 virtual ~FrameRateFlexibilityToken() { mCallback(); }
212
213private:
214 std::function<void()> mCallback;
215};
216
Steven Thomasb02664d2017-07-26 18:48:28 -0700217} // namespace anonymous
218
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219// ---------------------------------------------------------------------------
220
Mathias Agopian99b49842011-06-27 16:05:52 -0700221const String16 sHardwareTest("android.permission.HARDWARE_TEST");
222const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
223const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
224const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800225const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700226
227// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700228int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700229bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800230uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800231bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800232bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800233int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100234uint32_t SurfaceFlinger::maxGraphicsWidth;
235uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600236bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800237ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700238bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700239bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700240Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
241ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
242Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
243ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800244bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700245
Kalle Raitaa099a242017-01-11 11:17:29 -0800246std::string getHwcServiceName() {
247 char value[PROPERTY_VALUE_MAX] = {};
248 property_get("debug.sf.hwc_service_name", value, "default");
249 ALOGI("Using HWComposer service: '%s'", value);
250 return std::string(value);
251}
252
253bool useTrebleTestingOverride() {
254 char value[PROPERTY_VALUE_MAX] = {};
255 property_get("debug.sf.treble_testing_override", value, "false");
256 ALOGI("Treble testing override: '%s'", value);
257 return std::string(value) == "true";
258}
259
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800260std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
261 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800262 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700263 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800264 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700265 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800266 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700267 return std::string("Enhanced");
268 default:
269 return std::string("Unknown ") +
270 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800271 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800272}
273
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700274SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800275
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700276SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
277 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700278 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700279 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700280 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700281 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700282 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800283 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
284 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800285
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700286SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800287 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800288
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800296
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800301
Brian Lindahla13f2d52020-03-05 11:54:17 +0100302 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
303 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
304
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700306
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 mDefaultCompositionDataspace =
310 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700311 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
312 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900313 defaultCompositionDataspace = mDefaultCompositionDataspace;
314 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
315 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
316 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
317 wideColorGamutCompositionPixelFormat =
318 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700319
Yichi Chenda901bf2019-06-28 14:58:27 +0800320 mColorSpaceAgnosticDataspace =
321 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800324
Dominik Laskowski718f9602019-11-09 20:01:35 -0800325 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
326 switch (primary_display_orientation(Values::ORIENTATION_0)) {
327 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800329 case Values::ORIENTATION_90:
330 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800332 case Values::ORIENTATION_180:
333 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800335 case Values::ORIENTATION_270:
336 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800339 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800340
Sundong Ahn85131bd2019-02-18 15:51:53 +0900341 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800342
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343 // debugging stuff...
344 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700345
Mathias Agopianb4b17302013-03-20 18:36:41 -0700346 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700347 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700348
Alec Mouri989ddbe2020-02-06 09:26:19 -0800349 property_get("ro.build.type", value, "user");
350 mIsUserBuild = strcmp(value, "user") == 0;
351
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352 property_get("debug.sf.showupdates", value, "0");
353 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700355 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000356
357 // DDMS debugging deprecated (b/120782499)
358 property_get("debug.sf.ddms", value, "0");
359 int debugDdms = atoi(value);
360 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700361
362 property_get("debug.sf.disable_backpressure", value, "0");
363 mPropagateBackpressure = !atoi(value);
364 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700365
Ady Abrahamadb9a992019-09-19 21:21:55 +0000366 property_get("debug.sf.enable_gl_backpressure", value, "0");
367 mPropagateBackpressureClientComposition = atoi(value);
368 ALOGI_IF(mPropagateBackpressureClientComposition,
369 "Enabling backpressure propagation for Client Composition");
370
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800371 property_get("debug.sf.enable_hwc_vds", value, "0");
372 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800373 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800374
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800375 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800376 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800377 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700378
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800379 property_get("ro.surface_flinger.supports_background_blur", value, "0");
380 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700381 mSupportsBlur = supportsBlurs;
382 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800383 property_get("ro.sf.blurs_are_expensive", value, "0");
384 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800385
Ady Abraham0a525092020-03-03 12:51:24 -0800386 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700387 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
388 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
389
Dan Stozaec460082018-12-17 15:35:09 -0800390 property_get("debug.sf.luma_sampling", value, "1");
391 mLumaSampling = atoi(value);
392
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800393 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800394 mDisableClientCompositionCache = atoi(value);
395
Romain Guy11d63f42017-07-20 12:47:14 -0700396 // We should be reading 'persist.sys.sf.color_saturation' here
397 // but since /data may be encrypted, we need to wait until after vold
398 // comes online to attempt to read the property. The property is
399 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800400
401 if (useTrebleTestingOverride()) {
402 // Without the override SurfaceFlinger cannot connect to HIDL
403 // services that are not listed in the manifests. Considered
404 // deriving the setting from the set service name, but it
405 // would be brittle if the name that's not 'default' is used
406 // for production purposes later on.
407 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
408 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800409
410 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411}
412
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700413SurfaceFlinger::~SurfaceFlinger() = default;
414
415void SurfaceFlinger::onFirstRef() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800416 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417}
418
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700419void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700421 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422
Andy McFadden13a082e2012-08-24 10:16:42 -0700423 // restore initial conditions (default device unblank, etc)
424 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425
426 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700427 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428}
429
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700430void SurfaceFlinger::run() {
431 while (true) {
432 mEventQueue->waitMessage();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700434}
435
436template <typename F, typename T>
437inline std::future<T> SurfaceFlinger::schedule(F&& f) {
438 auto [task, future] = makeTask(std::move(f));
439 mEventQueue->postMessage(std::move(task));
440 return std::move(future);
Robert Carr1db73f62016-12-21 12:58:51 -0800441}
442
443sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700444 const sp<Client> client = new Client(this);
445 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800446}
447
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700448sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700449 class DisplayToken : public BBinder {
450 sp<SurfaceFlinger> flinger;
451 virtual ~DisplayToken() {
452 // no more references, this display must be terminated
453 Mutex::Autolock _l(flinger->mStateLock);
454 flinger->mCurrentState.displays.removeItem(this);
455 flinger->setTransactionFlags(eDisplayTransactionNeeded);
456 }
457 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700458 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459 : flinger(flinger) {
460 }
461 };
462
463 sp<BBinder> token = new DisplayToken(this);
464
465 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700466 // Display ID is assigned when virtual display is allocated by HWC.
467 DisplayDeviceState state;
468 state.isSecure = secure;
469 state.displayName = displayName;
470 mCurrentState.displays.add(token, state);
471 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700472 return token;
473}
474
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700475void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700476 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700477
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700478 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700480 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700481 return;
482 }
483
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700485 if (state.physical) {
486 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 return;
488 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 mInterceptor->saveDisplayDeletion(state.sequenceId);
490 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 setTransactionFlags(eDisplayTransactionNeeded);
492}
493
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800494std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
495 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800497 const auto internalDisplayId = getInternalDisplayIdLocked();
498 if (!internalDisplayId) {
499 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 }
501
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800502 std::vector<PhysicalDisplayId> displayIds;
503 displayIds.reserve(mPhysicalDisplayTokens.size());
504 displayIds.push_back(internalDisplayId->value);
505
506 for (const auto& [id, token] : mPhysicalDisplayTokens) {
507 if (id != *internalDisplayId) {
508 displayIds.push_back(id.value);
509 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800512 return displayIds;
513}
514
515sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
516 Mutex::Autolock lock(mStateLock);
517 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700518}
519
Ady Abraham37965d42018-11-01 13:43:32 -0700520status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
521 if (!outGetColorManagement) {
522 return BAD_VALUE;
523 }
524 *outGetColorManagement = useColorManagement;
525 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700526}
527
Lloyd Pique441d5042018-10-18 16:49:51 -0700528HWComposer& SurfaceFlinger::getHwComposer() const {
529 return mCompositionEngine->getHwComposer();
530}
531
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700532renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
533 return mCompositionEngine->getRenderEngine();
534}
535
Lloyd Pique70d91362018-10-18 16:02:55 -0700536compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
537 return *mCompositionEngine.get();
538}
539
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540void SurfaceFlinger::bootFinished()
541{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700542 if (mBootFinished == true) {
543 ALOGE("Extra call to bootFinished");
544 return;
545 }
546 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700547 if (mStartPropertySetThread->join() != NO_ERROR) {
548 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800549 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800550 const nsecs_t now = systemTime();
551 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000552 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700553
Mikael Pessa90092f42019-08-26 17:22:04 -0700554 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000555 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700556
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557 // wait patiently for the window manager death
558 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700559 mWindowManager = defaultServiceManager()->getService(name);
560 if (mWindowManager != 0) {
561 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 }
Robert Carr720e5062018-07-30 17:45:14 -0700563 sp<IBinder> input(defaultServiceManager()->getService(
564 String16("inputflinger")));
565 if (input == nullptr) {
566 ALOGE("Failed to link to input service");
567 } else {
568 mInputFlinger = interface_cast<IInputFlinger>(input);
569 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700570
Steven Thomas050b2c82017-03-06 11:45:16 -0800571 if (mVrFlinger) {
572 mVrFlinger->OnBootFinished();
573 }
574
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700575 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700576 // formerly we would just kill the process, but we now ask it to exit so it
577 // can choose where to stop the animation.
578 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700579
580 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
581 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
582 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700583
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700584 static_cast<void>(schedule([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800585 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700586 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800587 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800588
Ady Abraham8a82ba62020-01-17 12:43:17 -0800589 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
590 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
591 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
592 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800593 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800594}
595
Dan Stoza436ccf32018-06-21 12:10:12 -0700596uint32_t SurfaceFlinger::getNewTexture() {
597 {
598 std::lock_guard lock(mTexturePoolMutex);
599 if (!mTexturePool.empty()) {
600 uint32_t name = mTexturePool.back();
601 mTexturePool.pop_back();
602 ATRACE_INT("TexturePoolSize", mTexturePool.size());
603 return name;
604 }
605
606 // The pool was too small, so increase it for the future
607 ++mTexturePoolSize;
608 }
609
610 // The pool was empty, so we need to get a new texture name directly using a
611 // blocking call to the main thread
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700612 return schedule([this] {
613 uint32_t name = 0;
614 getRenderEngine().genTextures(1, &name);
615 return name;
616 })
617 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700618}
619
Mathias Agopian3f844832013-08-07 21:24:32 -0700620void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700621 std::lock_guard lock(mTexturePoolMutex);
622 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
623 // to actually delete this or not based on mTexturePoolSize
624 mTexturePool.push_back(texture);
625 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700626}
627
Wei Wangf9b05ee2017-07-19 20:59:39 -0700628// Do not call property_set on main thread which will be blocked by init
629// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700630void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700631 ALOGI( "SurfaceFlinger's main thread ready to run. "
632 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700633 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800634
Steven Thomasb02664d2017-07-26 18:48:28 -0700635 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700636 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800637 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700638 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
639 renderengine::RenderEngineCreationArgs::Builder()
640 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
641 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
642 .setUseColorManagerment(useColorManagement)
643 .setEnableProtectedContext(enable_protected_contents(false))
644 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700645 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700646 .setContextPriority(useContextPriority
647 ? renderengine::RenderEngine::ContextPriority::HIGH
648 : renderengine::RenderEngine::ContextPriority::MEDIUM)
649 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800650 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700651
652 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
653 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700654 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800655 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800656 // Process any initial hotplug and resulting display changes.
657 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700658 const auto display = getDefaultDisplayDeviceLocked();
659 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700660 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700661 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800662
Steven Thomas050b2c82017-03-06 11:45:16 -0800663 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700664 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700665 // This callback is called from the vr flinger dispatch thread. We
666 // need to call signalTransaction(), which requires holding
667 // mStateLock when we're not on the main thread. Acquiring
668 // mStateLock from the vr flinger dispatch thread might trigger a
669 // deadlock in surface flinger (see b/66916578), so post a message
670 // to be handled on the main thread instead.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700671 static_cast<void>(schedule([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700672 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
673 mVrFlingerRequestsDisplay = requestDisplay;
674 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700675 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
678 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700679 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700680 .value_or(0),
681 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800682 if (!mVrFlinger) {
683 ALOGE("Failed to start vrflinger");
684 }
685 }
686
Mathias Agopian92a979a2012-08-02 18:32:23 -0700687 // initialize our drawing state
688 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700689
Andy McFadden13a082e2012-08-24 10:16:42 -0700690 // set initial conditions (e.g. unblank default device)
691 initializeDisplays();
692
Steven Thomas137d4bc2019-07-25 16:55:14 -0700693 char primeShaderCache[PROPERTY_VALUE_MAX];
694 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
695 if (atoi(primeShaderCache)) {
696 getRenderEngine().primeCache();
697 }
Dan Stoza4e637772016-07-28 13:31:51 -0700698
Wei Wangf9b05ee2017-07-19 20:59:39 -0700699 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700700
701 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700702 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700703 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704
705 if (mStartPropertySetThread->Start() != NO_ERROR) {
706 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800707 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800708
Dan Stoza9e56aa02015-11-02 13:00:03 -0800709 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700710}
711
Romain Guy11d63f42017-07-20 12:47:14 -0700712void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700713 Mutex::Autolock _l(mStateLock);
714
Romain Guy11d63f42017-07-20 12:47:14 -0700715 char value[PROPERTY_VALUE_MAX];
716
717 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800718 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700719 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800720 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100721
722 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700723 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800724
725 property_get("persist.sys.sf.color_mode", value, "0");
726 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700727
728 property_get("persist.sys.sf.disable_blurs", value, "0");
729 bool disableBlurs = atoi(value);
730 mDisableBlurs = disableBlurs;
731 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700732}
733
Mathias Agopiana67e4182012-06-19 17:26:12 -0700734void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800735 // Start boot animation service by setting a property mailbox
736 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700737 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800738 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700739 if (mStartPropertySetThread->join() != NO_ERROR) {
740 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800741 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700742}
743
Mathias Agopian875d8e12013-06-07 15:35:48 -0700744size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700745 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700746}
747
Mathias Agopian875d8e12013-06-07 15:35:48 -0700748size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700749 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700750}
751
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800752// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800753
Jamie Gennis582270d2011-08-17 18:19:00 -0700754bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800755 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800756 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800757 return authenticateSurfaceTextureLocked(bufferProducer);
758}
759
760bool SurfaceFlinger::authenticateSurfaceTextureLocked(
761 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800762 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800763 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800764}
765
Brian Anderson6b376712017-04-04 10:51:39 -0700766status_t SurfaceFlinger::getSupportedFrameTimestamps(
767 std::vector<FrameEvent>* outSupported) const {
768 *outSupported = {
769 FrameEvent::REQUESTED_PRESENT,
770 FrameEvent::ACQUIRE,
771 FrameEvent::LATCH,
772 FrameEvent::FIRST_REFRESH_START,
773 FrameEvent::LAST_REFRESH_START,
774 FrameEvent::GPU_COMPOSITION_DONE,
775 FrameEvent::DEQUEUE_READY,
776 FrameEvent::RELEASE,
777 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700778 ConditionalLock _l(mStateLock,
779 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700780 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700781 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
782 }
783 return NO_ERROR;
784}
785
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800786status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
787 if (!displayToken || !state) {
788 return BAD_VALUE;
789 }
790
791 Mutex::Autolock lock(mStateLock);
792
793 const auto display = getDisplayDeviceLocked(displayToken);
794 if (!display) {
795 return NAME_NOT_FOUND;
796 }
797
798 state->layerStack = display->getLayerStack();
799 state->orientation = display->getOrientation();
800
801 const Rect viewport = display->getViewport();
802 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
803
804 return NO_ERROR;
805}
806
807status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
808 if (!displayToken || !info) {
809 return BAD_VALUE;
810 }
811
812 Mutex::Autolock lock(mStateLock);
813
814 const auto display = getDisplayDeviceLocked(displayToken);
815 if (!display) {
816 return NAME_NOT_FOUND;
817 }
818
Dominik Laskowski55c85402020-01-21 16:25:47 -0800819 if (const auto connectionType = display->getConnectionType())
820 info->connectionType = *connectionType;
821 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800822 return INVALID_OPERATION;
823 }
824
825 if (mEmulatedDisplayDensity) {
826 info->density = mEmulatedDisplayDensity;
827 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800828 info->density = info->connectionType == DisplayConnectionType::Internal
829 ? mInternalDisplayDensity
830 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800831 }
832
833 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200834 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800835
836 return NO_ERROR;
837}
838
Dominik Laskowski22488f62019-03-28 09:53:04 -0700839status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800840 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700841 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 return BAD_VALUE;
843 }
844
Dominik Laskowski22488f62019-03-28 09:53:04 -0700845 Mutex::Autolock lock(mStateLock);
846
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800847 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700848 if (!displayId) {
849 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700850 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700851
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800852 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700853
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700855
Dominik Laskowski075d3172018-05-24 15:50:06 -0700856 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800857 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700858
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800859 auto width = hwConfig->getWidth();
860 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700861
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800862 auto xDpi = hwConfig->getDpiX();
863 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700864
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800865 if (isInternal &&
866 (internalDisplayOrientation == ui::ROTATION_90 ||
867 internalDisplayOrientation == ui::ROTATION_270)) {
868 std::swap(width, height);
869 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700870 }
871
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800872 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800873
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800874 if (mEmulatedDisplayDensity) {
875 config.xDpi = mEmulatedDisplayDensity;
876 config.yDpi = mEmulatedDisplayDensity;
877 } else {
878 config.xDpi = xDpi;
879 config.yDpi = yDpi;
880 }
881
882 const nsecs_t period = hwConfig->getVsyncPeriod();
883 config.refreshRate = 1e9f / period;
884
885 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
886 config.appVsyncOffset = offsets.late.app;
887 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800888 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889
Andy McFadden91b2ca82014-06-13 14:04:23 -0700890 // This is how far in advance a buffer must be queued for
891 // presentation at a given time. If you want a buffer to appear
892 // on the screen at time N, you must submit the buffer before
893 // (N - presentationDeadline).
894 //
895 // Normally it's one full refresh period (to give SF a chance to
896 // latch the buffer), but this can be reduced by configuring a
897 // DispSync offset. Any additional delays introduced by the hardware
898 // composer or panel must be accounted for here.
899 //
900 // We add an additional 1ms to allow for processing time and
901 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800902 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800904 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700905 }
906
Dan Stoza7f7da322014-05-02 15:26:25 -0700907 return NO_ERROR;
908}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700909
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700910status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
911 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700912 return BAD_VALUE;
913 }
914
Ana Krulecc2870422019-01-29 19:00:58 -0800915 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700916 return NO_ERROR;
917}
918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700920 int activeConfig;
921 bool isPrimary;
922
923 {
924 Mutex::Autolock lock(mStateLock);
925
926 if (const auto display = getDisplayDeviceLocked(displayToken)) {
927 activeConfig = display->getActiveConfig().value();
928 isPrimary = display->isPrimary();
929 } else {
930 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
931 return NAME_NOT_FOUND;
932 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800933 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700934
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700935 if (isPrimary) {
Steven Thomasc9098452019-09-30 17:15:05 -0700936 std::lock_guard<std::mutex> lock(mActiveConfigLock);
937 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800938 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700939 }
Steven Thomasc9098452019-09-30 17:15:05 -0700940 }
Ady Abraham2139f732019-11-13 18:56:40 -0800941
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700942 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700943}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700944
Ady Abraham03b02dd2019-03-21 15:40:11 -0700945void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800947 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700948 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800949
Ady Abrahamb838aed2019-02-12 15:30:16 -0800950 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800951 if (mDesiredActiveConfigChanged) {
952 // If a config change is pending, just cache the latest request in
953 // mDesiredActiveConfig
954 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
955 mDesiredActiveConfig = info;
956 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
957 } else {
958 // Check is we are already at the desired config
959 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700960 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800961 return;
962 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800963
Ady Abraham59db0a32020-03-02 18:04:20 -0800964 // Initiate a config change.
965 mDesiredActiveConfigChanged = true;
966 mDesiredActiveConfig = info;
967
Ady Abrahamb838aed2019-02-12 15:30:16 -0800968 // This will trigger HWC refresh without resetting the idle timer.
969 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700970 // Start receiving vsync samples now, so that we can detect a period
971 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700972 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700973 // As we called to set period, we will call to onRefreshRateChangeCompleted once
974 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700975 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800976
Ady Abrahamabc27602020-04-08 17:20:29 -0700977 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800978 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700980
981 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800982 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700983 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800984}
985
986status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
987 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800988
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100989 if (!displayToken) {
990 return BAD_VALUE;
991 }
Ady Abraham838de062019-02-04 10:24:03 -0800992
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700993 auto future = schedule([=]() -> status_t {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100994 const auto display = getDisplayDeviceLocked(displayToken);
995 if (!display) {
996 ALOGE("Attempt to set allowed display configs for invalid display token %p",
997 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700998 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100999 } else if (display->isVirtual()) {
1000 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001001 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001002 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001003 const HwcConfigIndexType config(mode);
1004 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
1005 const scheduler::RefreshRateConfigs::Policy policy{config, fps, fps};
1006 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001007
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001008 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1009 }
1010 });
1011
1012 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001013}
1014
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001015void SurfaceFlinger::setActiveConfigInternal() {
1016 ATRACE_CALL();
1017
Dominik Laskowski22488f62019-03-28 09:53:04 -07001018 const auto display = getDefaultDisplayDeviceLocked();
1019 if (!display) {
1020 return;
1021 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001022
Alec Mouri8de697e2020-03-19 10:52:01 -07001023 auto& oldRefreshRate =
1024 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1025
Dominik Laskowski22488f62019-03-28 09:53:04 -07001026 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001027 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001028 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001029 display->setActiveConfig(mUpcomingActiveConfig.configId);
1030
Ady Abraham2e1dd892020-03-05 13:48:36 -08001031 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001032 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001033 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001034 mTimeStats->incrementRefreshRateSwitches();
1035 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001036 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001037 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001038 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001039
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001040 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001041 const nsecs_t vsyncPeriod =
1042 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001043 .getVsyncPeriod();
Ady Abraham447052e2019-02-13 16:07:27 -08001044 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001045 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001046 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001047}
1048
Ady Abraham53852a52019-05-28 18:07:44 -07001049void SurfaceFlinger::desiredActiveConfigChangeDone() {
1050 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1051 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1052 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001053
Ady Abraham2e1dd892020-03-05 13:48:36 -08001054 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001055 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001056 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1057 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001058 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001059}
1060
Ady Abraham27cbed72020-04-10 12:56:59 -07001061void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001062 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001063 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001064 // Store the local variable to release the lock.
Ady Abraham27cbed72020-04-10 12:56:59 -07001065 const auto desiredActiveConfig = [&]() -> std::optional<ActiveConfigInfo> {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001066 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham27cbed72020-04-10 12:56:59 -07001067 if (mDesiredActiveConfigChanged) {
1068 return mDesiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001069 }
Ady Abraham27cbed72020-04-10 12:56:59 -07001070 return std::nullopt;
1071 }();
1072
1073 if (!desiredActiveConfig) {
1074 // No desired active config pending to be applied
1075 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001076 }
1077
Ady Abraham2e1dd892020-03-05 13:48:36 -08001078 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001079 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001080 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1081 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001082 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001083 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001084 // display is not valid or we are already in the requested mode
1085 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001086 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001087 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001088 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001089
Ady Abraham838de062019-02-04 10:24:03 -08001090 // Desired active config was set, it is different than the config currently in use, however
1091 // allowed configs might have change by the time we process the refresh.
1092 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001093 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001094 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001095 return;
Ady Abraham838de062019-02-04 10:24:03 -08001096 }
Alec Mouri7f015182019-07-11 13:56:22 -07001097
Ady Abraham27cbed72020-04-10 12:56:59 -07001098 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001099 const auto displayId = display->getId();
1100 LOG_ALWAYS_FATAL_IF(!displayId);
1101
Ady Abrahamabc27602020-04-08 17:20:29 -07001102 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001103
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001104 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001105 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001106 constraints.desiredTimeNanos = systemTime();
1107 constraints.seamlessRequired = false;
1108
Peiyong Line9d809e2020-04-14 13:10:48 -07001109 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001110 auto status =
1111 getHwComposer().setActiveConfigWithConstraints(*displayId,
1112 mUpcomingActiveConfig.configId.value(),
1113 constraints, &outTimeline);
1114 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001115 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1116 // to be sent. We just log the error in this case.
1117 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001118 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001119 }
1120
1121 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1122 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001123 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001124}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1127 Vector<ColorMode>* outColorModes) {
1128 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001129 return BAD_VALUE;
1130 }
1131
Peiyong Lina52f0292018-03-14 17:26:31 -07001132 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001133 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001134 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001135 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1136
1137 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1138 if (!displayId) {
1139 return NAME_NOT_FOUND;
1140 }
1141
Dominik Laskowski075d3172018-05-24 15:50:06 -07001142 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001143 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001144 }
Michael Wright28f24d02016-07-12 13:30:53 -07001145 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001146
1147 // If it's built-in display and the configuration claims it's not wide color capable,
1148 // filter out all wide color modes. The typical reason why this happens is that the
1149 // hardware is not good enough to support GPU composition of wide color, and thus the
1150 // OEMs choose to disable this capability.
1151 if (isInternalDisplay && !hasWideColorDisplay) {
1152 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1153 isWideColorMode);
1154 } else {
1155 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1156 }
Michael Wright28f24d02016-07-12 13:30:53 -07001157
1158 return NO_ERROR;
1159}
1160
Daniel Solomon42d04562019-01-20 21:03:19 -08001161status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1162 ui::DisplayPrimaries &primaries) {
1163 if (!displayToken) {
1164 return BAD_VALUE;
1165 }
1166
1167 // Currently we only support this API for a single internal display.
1168 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001169 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001170 }
1171
1172 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1173 return NO_ERROR;
1174}
1175
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001176ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001177 Mutex::Autolock lock(mStateLock);
1178
1179 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001180 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001181 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001182 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001183}
1184
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001185status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001186 schedule([=] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001187 Vector<ColorMode> modes;
1188 getDisplayColorModes(displayToken, &modes);
1189 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1190 if (mode < ColorMode::NATIVE || !exists) {
1191 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1192 decodeColorMode(mode).c_str(), mode, displayToken.get());
1193 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001194 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001195 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001196 if (!display) {
1197 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1198 decodeColorMode(mode).c_str(), mode, displayToken.get());
1199 } else if (display->isVirtual()) {
1200 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1201 decodeColorMode(mode).c_str(), mode);
1202 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001203 display->getCompositionDisplay()->setColorProfile(
1204 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1205 RenderIntent::COLORIMETRIC,
1206 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001207 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001208 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001209
Michael Wright28f24d02016-07-12 13:30:53 -07001210 return NO_ERROR;
1211}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001212
Galia Peycheva5492cb52019-10-30 14:13:16 +01001213status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1214 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001215 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001216 return BAD_VALUE;
1217 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001218
1219 Mutex::Autolock lock(mStateLock);
1220
Galia Peycheva5492cb52019-10-30 14:13:16 +01001221 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1222 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001223 return NAME_NOT_FOUND;
1224 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001225 *outSupport =
1226 getHwComposer().hasDisplayCapability(*displayId,
1227 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001228 return NO_ERROR;
1229}
1230
1231void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001232 static_cast<void>(schedule([=] {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001233 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1234 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1235 } else {
1236 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1237 }
1238 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001239}
1240
1241status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1242 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001243 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001244 return BAD_VALUE;
1245 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001246
1247 Mutex::Autolock lock(mStateLock);
1248
Galia Peycheva5492cb52019-10-30 14:13:16 +01001249 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1250 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001251 return NAME_NOT_FOUND;
1252 }
1253
Peiyong Line9d809e2020-04-14 13:10:48 -07001254 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001255 getHwComposer().getSupportedContentTypes(*displayId, &types);
1256
1257 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001258 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001259 return NO_ERROR;
1260}
1261
1262void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001263 static_cast<void>(schedule([=] {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001264 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001265 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001266 getHwComposer().setContentType(*displayId, type);
1267 } else {
1268 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1269 }
1270 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001271}
1272
Svetoslavd85084b2014-03-20 10:28:31 -07001273status_t SurfaceFlinger::clearAnimationFrameStats() {
1274 Mutex::Autolock _l(mStateLock);
1275 mAnimFrameTracker.clearStats();
1276 return NO_ERROR;
1277}
1278
1279status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1280 Mutex::Autolock _l(mStateLock);
1281 mAnimFrameTracker.getStats(outStats);
1282 return NO_ERROR;
1283}
1284
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001285status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1286 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001287 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001288
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001289 const auto display = getDisplayDeviceLocked(displayToken);
1290 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001291 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1292 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001293 }
1294
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001295 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001296 // meaning the luminance information is already queried from
1297 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001298 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001299 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1300 capabilities.getDesiredMaxLuminance(),
1301 capabilities.getDesiredMaxAverageLuminance(),
1302 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001303
1304 return NO_ERROR;
1305}
1306
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001307std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1308 const DisplayDevice& display) const {
1309 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1310 // avoid repetitive HAL IPC and EDID parsing.
1311 const auto displayId = display.getId();
1312 LOG_FATAL_IF(!displayId);
1313
1314 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1315 LOG_FATAL_IF(!hwcDisplayId);
1316
1317 uint8_t port;
1318 DisplayIdentificationData data;
1319 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1320 ALOGV("%s: No identification data.", __FUNCTION__);
1321 return {};
1322 }
1323
1324 const auto info = parseDisplayIdentificationData(port, data);
1325 if (!info) {
1326 return {};
1327 }
1328 return info->deviceProductInfo;
1329}
1330
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001331status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1332 ui::PixelFormat* outFormat,
1333 ui::Dataspace* outDataspace,
1334 uint8_t* outComponentMask) const {
1335 if (!outFormat || !outDataspace || !outComponentMask) {
1336 return BAD_VALUE;
1337 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001338
1339 Mutex::Autolock lock(mStateLock);
1340
1341 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1342 if (!displayId) {
1343 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001344 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001345
1346 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001347 outDataspace, outComponentMask);
1348}
1349
Kevin DuBois74e53772018-11-19 10:52:38 -08001350status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1351 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001352 uint64_t maxFrames) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001353 return schedule([=]() -> status_t {
1354 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1355 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1356 componentMask,
1357 maxFrames);
1358 } else {
1359 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1360 return NAME_NOT_FOUND;
1361 }
1362 })
1363 .get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001364}
1365
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001366status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1367 uint64_t maxFrames, uint64_t timestamp,
1368 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001369 Mutex::Autolock lock(mStateLock);
1370
1371 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1372 if (!displayId) {
1373 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001374 }
1375
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001376 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001377}
1378
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001379status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1380 if (!outSupported) {
1381 return BAD_VALUE;
1382 }
1383 *outSupported = getRenderEngine().supportsProtectedContent();
1384 return NO_ERROR;
1385}
1386
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001387status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1388 bool* outIsWideColorDisplay) const {
1389 if (!displayToken || !outIsWideColorDisplay) {
1390 return BAD_VALUE;
1391 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001392
1393 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001394 const auto display = getDisplayDeviceLocked(displayToken);
1395 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001396 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001397 }
Peiyong Linff84a152019-05-17 18:36:19 -07001398
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001399 *outIsWideColorDisplay =
1400 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001401 return NO_ERROR;
1402}
1403
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001404status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001405 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001406 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001407
Dominik Laskowski6505f792019-09-18 11:10:05 -07001408 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1409 mEventQueue->setEventConnection(
1410 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001411 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001412 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001413
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001414 return NO_ERROR;
1415}
1416
1417status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001418 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001419 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001420}
1421
Lloyd Pique755e3192018-01-31 16:46:15 -08001422status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1423 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001424 // Try to acquire a lock for 1s, fail gracefully
1425 const status_t err = mStateLock.timedLock(s2ns(1));
1426 const bool locked = (err == NO_ERROR);
1427 if (!locked) {
1428 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1429 return TIMED_OUT;
1430 }
1431
1432 outLayers->clear();
1433 mCurrentState.traverseInZOrder([&](Layer* layer) {
1434 outLayers->push_back(layer->getLayerDebugInfo());
1435 });
1436
1437 mStateLock.unlock();
1438 return NO_ERROR;
1439}
1440
Peiyong Linc6780972018-10-28 15:24:08 -07001441status_t SurfaceFlinger::getCompositionPreference(
1442 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1443 Dataspace* outWideColorGamutDataspace,
1444 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001445 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001446 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001447 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001448 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001449 return NO_ERROR;
1450}
1451
Dan Stozaec460082018-12-17 15:35:09 -08001452status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1453 const sp<IBinder>& stopLayerHandle,
1454 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001455 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001456 return BAD_VALUE;
1457 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001458
1459 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1460 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001461 return NO_ERROR;
1462}
1463
Dan Stozaec460082018-12-17 15:35:09 -08001464status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001465 if (!listener) {
1466 return BAD_VALUE;
1467 }
Dan Stozaec460082018-12-17 15:35:09 -08001468 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001469 return NO_ERROR;
1470}
Dan Gittik57e63c52019-01-18 16:37:54 +00001471
1472status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1473 bool* outSupport) const {
1474 if (!displayToken || !outSupport) {
1475 return BAD_VALUE;
1476 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001477
1478 Mutex::Autolock lock(mStateLock);
1479
Dan Gittik57e63c52019-01-18 16:37:54 +00001480 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1481 if (!displayId) {
1482 return NAME_NOT_FOUND;
1483 }
1484 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001485 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001486 return NO_ERROR;
1487}
1488
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001489status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001490 if (!displayToken) {
1491 return BAD_VALUE;
1492 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001493
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001494 return schedule([=]() -> status_t {
1495 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1496 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1497 } else {
1498 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1499 return NAME_NOT_FOUND;
1500 }
1501 })
1502 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001503}
1504
Ady Abraham8532d012019-05-08 14:50:56 -07001505status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1506 PowerHint powerHint = static_cast<PowerHint>(hintId);
1507
1508 if (powerHint == PowerHint::INTERACTION) {
1509 mScheduler->notifyTouchEvent();
1510 }
1511
1512 return NO_ERROR;
1513}
1514
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001515// ----------------------------------------------------------------------------
1516
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001517sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001518 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001519 const auto& handle =
1520 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001521
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001522 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001523}
1524
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001525void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001526 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001527 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001528 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001529}
1530
1531void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001532 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001533 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001534 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001535}
1536
1537void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001538 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001539 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001540}
1541
Dominik Laskowski83b88212018-12-11 13:34:06 -08001542nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001543 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001544 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1545 return 0;
1546 }
1547
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001548 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001549}
1550
Peiyong Line9d809e2020-04-14 13:10:48 -07001551void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001552 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001553 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001554 ATRACE_NAME("SF onVsync");
1555
Steven Thomas3cfac282017-02-06 12:29:30 -08001556 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001557 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001558 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001559 return;
1560 }
1561
Dominik Laskowski075d3172018-05-24 15:50:06 -07001562 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001563 return;
1564 }
1565
Dominik Laskowski075d3172018-05-24 15:50:06 -07001566 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001567 // For now, we don't do anything with external display vsyncs.
1568 return;
1569 }
1570
Alec Mourif8e689c2019-05-20 18:32:22 -07001571 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001572 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001573 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001574 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001575 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001576}
1577
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001578void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001579 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1580 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001581}
1582
Ady Abraham2139f732019-11-13 18:56:40 -08001583bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001584 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001585}
1586
Ady Abraham2139f732019-11-13 18:56:40 -08001587void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1588 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001589 const auto display = getDefaultDisplayDeviceLocked();
1590 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001591 return;
1592 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001593 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001594
Ana Krulec7d1d6832018-12-27 11:10:09 -08001595 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001596 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001597 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001598 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001599 return;
1600 }
1601
Ady Abrahamabc27602020-04-08 17:20:29 -07001602 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001603}
1604
Peiyong Line9d809e2020-04-14 13:10:48 -07001605void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
1606 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001607 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001608 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001609
Lloyd Piqueba04e622017-12-14 17:11:26 -08001610 // Ignore events that do not have the right sequenceId.
1611 if (sequenceId != getBE().mComposerSequenceId) {
1612 return;
1613 }
1614
Steven Thomasb02664d2017-07-26 18:48:28 -07001615 // Only lock if we're not on the main thread. This function is normally
1616 // called on a hwbinder thread, but for the primary display it's called on
1617 // the main thread with the state lock already held, so don't attempt to
1618 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001619 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001620
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001621 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001622
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001623 if (std::this_thread::get_id() == mMainThreadId) {
1624 // Process all pending hot plug events immediately if we are on the main thread.
1625 processDisplayHotplugEventsLocked();
1626 }
1627
Lloyd Piqueba04e622017-12-14 17:11:26 -08001628 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001629}
1630
Ady Abraham7159f572019-10-11 11:10:18 -07001631void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001632 int32_t sequenceId, hal::HWDisplayId /*display*/,
1633 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001634 Mutex::Autolock lock(mStateLock);
1635 if (sequenceId != getBE().mComposerSequenceId) {
1636 return;
1637 }
1638 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001639}
1640
Peiyong Line9d809e2020-04-14 13:10:48 -07001641void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001642 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1643 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1644}
1645
Peiyong Line9d809e2020-04-14 13:10:48 -07001646void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001647 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001648 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001649 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001650 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001651 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001652}
1653
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001654void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001655 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001656
1657 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1658 // display power state.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001659 static_cast<void>(
1660 schedule([=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001661}
1662
1663void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1664 ATRACE_CALL();
1665
Peiyong Line9d809e2020-04-14 13:10:48 -07001666 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001667
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001668 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001669 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1670 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001671 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001672 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001673 }
Mathias Agopian86303202012-07-24 22:46:10 -07001674}
1675
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001676// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001677void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001678 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001679 // Clear the drawing state so that the logic inside of
1680 // handleTransactionLocked will fire. It will determine the delta between
1681 // mCurrentState and mDrawingState and re-apply all changes when we make the
1682 // transition.
1683 mDrawingState.displays.clear();
1684 mDisplays.clear();
1685}
1686
Steven Thomas050b2c82017-03-06 11:45:16 -08001687void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001688 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001689 if (!mVrFlinger)
1690 return;
1691 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001692 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001693 return;
1694 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001695
Lloyd Pique441d5042018-10-18 16:49:51 -07001696 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001697 ALOGE("Vr flinger is only supported for remote hardware composer"
1698 " service connections. Ignoring request to transition to vr"
1699 " flinger.");
1700 mVrFlingerRequestsDisplay = false;
1701 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001702 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001703
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001704 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001705
Steven Thomas0123ac62018-07-12 11:32:34 -07001706 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001707 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001708
Peiyong Lin65248e02020-04-18 21:15:07 -07001709 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001710
1711 // Clear out all the output layers from the composition engine for all
1712 // displays before destroying the hardware composer interface. This ensures
1713 // any HWC layers are destroyed through that interface before it becomes
1714 // invalid.
1715 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001716 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001717 }
1718
Steven Thomas0123ac62018-07-12 11:32:34 -07001719 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1720 // called below. Clear the reference now so we don't accidentally use it
1721 // later.
1722 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001723
Steven Thomasb02664d2017-07-26 18:48:28 -07001724 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001725 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001726 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001727
Steven Thomasb02664d2017-07-26 18:48:28 -07001728 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001729 // Delete the current instance before creating the new one
1730 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1731 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1732 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001733 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001734
Lloyd Pique441d5042018-10-18 16:49:51 -07001735 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001736 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001737
1738 if (vrFlingerRequestsDisplay) {
1739 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001740 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001741
1742 mVisibleRegionsDirty = true;
1743 invalidateHwcGeometry();
1744
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001745 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001746 display = getDefaultDisplayDeviceLocked();
1747 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001748 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001749
Steven Thomasb02664d2017-07-26 18:48:28 -07001750 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001751 const nsecs_t vsyncPeriod = getVsyncPeriod();
1752 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001753
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001754 // The present fences returned from vr_hwc are not an accurate
1755 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001756 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001757
Steven Thomasb02664d2017-07-26 18:48:28 -07001758 // Use phase of 0 since phase is not known.
1759 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001760 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001761 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001762
Ana Krulecc2870422019-01-29 19:00:58 -08001763 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001764
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001765 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001766 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001767}
1768
Alec Mouri6d414b52020-03-17 11:18:05 -07001769sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001770 // We are storing the last 2 present fences. If sf's phase offset is to be
1771 // woken up before the actual vsync but targeting the next vsync, we need to check
1772 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001773 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1774 : mPreviousPresentFences[1];
1775}
1776
1777bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1778 ATRACE_CALL();
1779 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001780
Ady Abraham11579302019-09-19 12:35:58 -07001781 if (fence == Fence::NO_FENCE) {
1782 return false;
1783 }
1784
1785 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1786 fence->wait(graceTimeMs);
1787 }
1788
1789 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001790}
1791
Alec Mouri6d414b52020-03-17 11:18:05 -07001792nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1793 const sp<Fence>& fence = previousFrameFence();
1794
1795 if (fence == Fence::NO_FENCE) {
1796 return Fence::SIGNAL_TIME_INVALID;
1797 }
1798
1799 return fence->getSignalTime();
1800}
1801
Ady Abraham5facfb12020-04-22 15:18:31 -07001802nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001803 DisplayStatInfo stats;
1804 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001805 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001806 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001807 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001808}
1809
Ady Abraham5facfb12020-04-22 15:18:31 -07001810void SurfaceFlinger::onMessageReceived(int32_t what,
1811 nsecs_t expectedVSyncTime) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001812 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001813 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001814 case MessageQueue::INVALIDATE: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001815 onMessageInvalidate(expectedVSyncTime);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001816 break;
1817 }
1818 case MessageQueue::REFRESH: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001819 onMessageRefresh();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001820 break;
1821 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001822 }
1823}
1824
Dan Stoza28d46a52020-04-28 09:54:54 -07001825void SurfaceFlinger::onMessageInvalidate(nsecs_t expectedVSyncTime) NO_THREAD_SAFETY_ANALYSIS {
1826 ATRACE_CALL();
1827
1828 const nsecs_t frameStart = systemTime();
1829 // calculate the expected present time once and use the cached
1830 // value throughout this frame to make sure all layers are
1831 // seeing this same value.
1832 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
1833 mExpectedPresentTime = expectedVSyncTime;
1834
1835 // When Backpressure propagation is enabled we want to give a small grace period
1836 // for the present fence to fire instead of just giving up on this frame to handle cases
1837 // where present fence is just about to get signaled.
1838 const int graceTimeForPresentFenceMs =
1839 (mPropagateBackpressure &&
1840 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1841 ? 1
1842 : 0;
1843
1844 // Pending frames may trigger backpressure propagation.
1845 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1846 previousFramePending(graceTimeForPresentFenceMs)};
1847
1848 // Frame missed counts for metrics tracking.
1849 // A frame is missed if the prior frame is still pending. If no longer pending,
1850 // then we still count the frame as missed if the predicted present time
1851 // was further in the past than when the fence actually fired.
1852
1853 // Add some slop to correct for drift. This should generally be
1854 // smaller than a typical frame duration, but should not be so small
1855 // that it reports reasonable drift as a missed frame.
1856 DisplayStatInfo stats;
1857 mScheduler->getDisplayStatInfo(&stats);
1858 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1859 const nsecs_t previousPresentTime = previousFramePresentTime();
1860 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
1861 framePending ||
1862 (previousPresentTime >= 0 &&
1863 (lastExpectedPresentTime <
1864 previousPresentTime - frameMissedSlop))};
1865 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
1866 mHadDeviceComposition && frameMissed};
1867 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
1868 mHadClientComposition && frameMissed};
1869
1870 if (frameMissed) {
1871 mFrameMissedCount++;
1872 mTimeStats->incrementMissedFrames();
1873 if (mMissedFrameJankCount == 0) {
1874 mMissedFrameJankStart = systemTime();
1875 }
1876 mMissedFrameJankCount++;
1877 }
1878
1879 if (hwcFrameMissed) {
1880 mHwcFrameMissedCount++;
1881 }
1882
1883 if (gpuFrameMissed) {
1884 mGpuFrameMissedCount++;
1885 }
1886
1887 // If we are in the middle of a config change and the fence hasn't
1888 // fired yet just wait for the next invalidate
1889 if (mSetActiveConfigPending) {
1890 if (framePending) {
1891 mEventQueue->invalidate();
1892 return;
1893 }
1894
1895 // We received the present fence from the HWC, so we assume it successfully updated
1896 // the config, hence we update SF.
1897 mSetActiveConfigPending = false;
1898 setActiveConfigInternal();
1899 }
1900
1901 if (framePending && mPropagateBackpressure) {
1902 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
1903 signalLayerUpdate();
1904 return;
1905 }
1906 }
1907
1908 // Our jank window is always at least 100ms since we missed a
1909 // frame...
1910 static constexpr nsecs_t kMinJankyDuration =
1911 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1912 // ...but if it's larger than 1s then we missed the trace cutoff.
1913 static constexpr nsecs_t kMaxJankyDuration =
1914 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1915 // If we're in a user build then don't push any atoms
1916 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1917 const auto displayDevice = getDefaultDisplayDeviceLocked();
1918 // Only report jank when the display is on, as displays in DOZE
1919 // power mode may operate at a different frame rate than is
1920 // reported in their config, which causes noticeable (but less
1921 // severe) jank.
1922 if (displayDevice && displayDevice->getPowerMode() == hal::PowerMode::ON) {
1923 const nsecs_t currentTime = systemTime();
1924 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1925 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1926 ATRACE_NAME("Jank detected");
1927 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1928 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1929 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1930 jankyDurationMillis, mMissedFrameJankCount);
1931 }
1932
1933 // We either reported a jank event or we missed the trace
1934 // window, so clear counters here.
1935 if (jankDuration > kMinJankyDuration) {
1936 mMissedFrameJankCount = 0;
1937 mMissedFrameJankStart = 0;
1938 }
1939 }
1940 }
1941
1942 // Now that we're going to make it to the handleMessageTransaction()
1943 // call below it's safe to call updateVrFlinger(), which will
1944 // potentially trigger a display handoff.
1945 updateVrFlinger();
1946
1947 if (mTracingEnabledChanged) {
1948 mTracingEnabled = mTracing.isEnabled();
1949 mTracingEnabledChanged = false;
1950 }
1951
1952 bool refreshNeeded;
1953 {
1954 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1955
1956 refreshNeeded = handleMessageTransaction();
1957 refreshNeeded |= handleMessageInvalidate();
1958 if (mTracingEnabled) {
1959 mAddCompositionStateToTrace =
1960 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1961 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1962 mTracing.notifyLocked("visibleRegionsDirty");
1963 }
1964 }
1965 }
1966
1967 // Layers need to get updated (in the previous line) before we can use them for
1968 // choosing the refresh rate.
1969 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1970 // and may eventually call to ~Layer() if it holds the last reference
1971 {
1972 Mutex::Autolock _l(mStateLock);
1973 mScheduler->chooseRefreshRateForContent();
1974 }
1975
1976 performSetActiveConfig();
1977
1978 updateCursorAsync();
1979 updateInputFlinger();
1980
1981 refreshNeeded |= mRepaintEverything;
1982 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
1983 // Signal a refresh if a transaction modified the window state,
1984 // a new buffer was latched, or if HWC has requested a full
1985 // repaint
1986 if (mFrameStartTime <= 0) {
1987 // We should only use the time of the first invalidate
1988 // message that signals a refresh as the beginning of the
1989 // frame. Otherwise the real frame time will be
1990 // underestimated.
1991 mFrameStartTime = frameStart;
1992 }
1993 signalRefresh();
1994 }
1995}
1996
Dan Stoza6b9454d2014-11-07 16:00:59 -08001997bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001998 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001999 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002000
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002001 bool flushedATransaction = flushTransactionQueues();
2002
2003 bool runHandleTransaction = transactionFlags &&
2004 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
2005
2006 if (runHandleTransaction) {
2007 handleTransaction(eTransactionMask);
2008 } else {
2009 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002010 }
2011
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002012 if (transactionFlushNeeded()) {
2013 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002014 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002015
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002016 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002017}
2018
Dan Stoza28d46a52020-04-28 09:54:54 -07002019void SurfaceFlinger::onMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002020 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002021
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002022 mRefreshPending = false;
2023
Lloyd Piqueab039b52019-02-13 14:22:42 -08002024 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002025 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002026 for (const auto& [_, display] : mDisplays) {
2027 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2028 }
2029 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002030 if (auto layerFE = layer->getCompositionEngineLayerFE())
2031 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002032 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002033 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2034 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002035 if (auto layerFE = layer->getCompositionEngineLayerFE())
2036 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002037 }
2038
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002039 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002040 refreshArgs.outputColorSetting = useColorManagement
2041 ? mDisplayColorSetting
2042 : compositionengine::OutputColorSetting::kUnmanaged;
2043 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2044 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002045
2046 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2047 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002048 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002049
2050 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2051 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2052 mDrawingState.colorMatrixChanged = false;
2053 }
2054
2055 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2056
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002057 if (mDebugRegion != 0) {
2058 refreshArgs.devOptFlashDirtyRegionsDelay =
2059 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2060 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002061
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002062 mGeometryInvalid = false;
2063
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002064 // Store the present time just before calling to the composition engine so we could notify
2065 // the scheduler.
2066 const auto presentTime = systemTime();
2067
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002068 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002069 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2070 // Reset the frame start time now that we've recorded this frame.
2071 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002072
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002073 mScheduler->onDisplayRefreshed(presentTime);
2074
David Sodmanfa9b2af2017-12-24 13:28:59 -08002075 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002076 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002077
Alec Mouri8f7a0102020-04-15 12:11:10 -07002078 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2079
Lloyd Pique66d68602019-02-13 14:23:31 -08002080 mHadClientComposition =
2081 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2082 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002083 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2084 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002085 });
2086 mHadDeviceComposition =
2087 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2088 auto& displayDevice = tokenDisplayPair.second;
2089 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2090 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002091 mReusedClientComposition =
2092 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2093 auto& displayDevice = tokenDisplayPair.second;
2094 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2095 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002096
Alec Mouri8f7a0102020-04-15 12:11:10 -07002097 // Only report a strategy change if we move in and out of composition with hw overlays
2098 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2099 mTimeStats->incrementCompositionStrategyChanges();
2100 }
2101
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002102 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002103
David Sodman7e4ae112018-02-09 15:02:28 -08002104 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002105 if (mVisibleRegionsDirty) {
2106 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002107 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002108 mTracing.notify("visibleRegionsDirty");
2109 }
2110 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002111
2112 if (mCompositionEngine->needsAnotherUpdate()) {
2113 signalLayerUpdate();
2114 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002115}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002116
David Sodmanfa9b2af2017-12-24 13:28:59 -08002117bool SurfaceFlinger::handleMessageInvalidate() {
2118 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002119 bool refreshNeeded = handlePageFlip();
2120
Vishnu Nair4351ad52019-02-11 14:13:02 -08002121 if (mVisibleRegionsDirty) {
2122 computeLayerBounds();
2123 }
2124
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002125 for (auto& layer : mLayersPendingRefresh) {
2126 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002127 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002128 invalidateLayerStack(layer, visibleReg);
2129 }
2130 mLayersPendingRefresh.clear();
2131 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002132}
2133
Ana Krulece588e312018-09-18 12:32:24 -07002134void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2135 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002136 // Update queue of past composite+present times and determine the
2137 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002138 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002139 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002140 while (!getBE().mCompositePresentTimes.empty()) {
2141 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002142 // Cached values should have been updated before calling this method,
2143 // which helps avoid duplicate syscalls.
2144 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2145 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2146 break;
2147 }
2148 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002149 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002150 }
2151
2152 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002153 while (getBE().mCompositePresentTimes.size() > 16) {
2154 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002155 }
2156
Ana Krulece588e312018-09-18 12:32:24 -07002157 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002158}
2159
Ana Krulece588e312018-09-18 12:32:24 -07002160void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2161 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002162 // Integer division and modulo round toward 0 not -inf, so we need to
2163 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002164 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2165 ? (stats.vsyncPeriod -
2166 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2167 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002168
Ady Abraham9e16a482019-12-03 17:19:41 -08002169 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002170 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002171 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002172 }
2173
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002174 // Snap the latency to a value that removes scheduling jitter from the
2175 // composition and present times, which often have >1ms of jitter.
2176 // Reducing jitter is important if an app attempts to extrapolate
2177 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002178 // Snapping also allows an app to precisely calculate
2179 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002180 nsecs_t bias = stats.vsyncPeriod / 2;
2181 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2182 nsecs_t snappedCompositeToPresentLatency =
2183 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002184
David Sodman99974d22017-11-28 12:04:33 -08002185 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002186 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2187 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002188 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002189}
2190
David Sodman2b406362017-12-15 13:33:47 -08002191void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002192{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002193 ATRACE_CALL();
2194 ALOGV("postComposition");
2195
Brian Andersonf6386862016-10-31 16:34:13 -07002196 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002197 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002198 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002199 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002200 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002201 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002202
David Sodman73beded2017-11-15 11:56:06 -08002203 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002204 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002205 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002206 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002207 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2208 ->getRenderSurface()
2209 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002210 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002211 } else {
2212 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2213 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002214
David Sodman73beded2017-11-15 11:56:06 -08002215 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002216 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2217 mPreviousPresentFences[0] = displayDevice
2218 ? getHwComposer().getPresentFence(*displayDevice->getId())
2219 : Fence::NO_FENCE;
2220 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002221 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002222
Ana Krulece588e312018-09-18 12:32:24 -07002223 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002224 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002225
Lloyd Piqueab039b52019-02-13 14:22:42 -08002226 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2227 // be sampled a little later than when we started doing work for this frame,
2228 // but that should be okay since updateCompositorTiming has snapping logic.
2229 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2230 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002231 CompositorTiming compositorTiming;
2232 {
David Sodman99974d22017-11-28 12:04:33 -08002233 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2234 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002235 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002236
Edgar Arriaga844fa672020-01-16 14:21:42 -08002237 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002238 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2239 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002240 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002241 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002242 }
Robert Carr2047fae2016-11-28 14:09:09 -08002243 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002244
Valerie Hau4b678442020-04-14 10:50:42 -07002245 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2246 mTransactionCompletedThread.sendCallbacks();
2247
Ady Abraham92fa2f42020-02-11 15:33:56 -08002248 if (displayDevice && displayDevice->isPrimary() &&
Peiyong Lin65248e02020-04-18 21:15:07 -07002249 displayDevice->getPowerMode() == hal::PowerMode::ON && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002250 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002251 }
2252
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002253 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002254 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2255 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002256 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002257 }
2258 }
2259
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002260 if (mAnimCompositionPending) {
2261 mAnimCompositionPending = false;
2262
Brian Anderson4e606e32017-03-16 15:34:57 -07002263 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002264 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002265 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002266 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002267 // The HWC doesn't support present fences, so use the refresh
2268 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002269 const nsecs_t presentTime =
2270 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002271 mAnimFrameTracker.setActualPresentTime(presentTime);
2272 }
2273 mAnimFrameTracker.advanceFrame();
2274 }
Dan Stozab90cf072015-03-05 11:05:59 -08002275
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002276 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002277 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002278 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002279 }
2280
Vishnu Nair9b079a22020-01-21 14:36:08 -08002281 if (mReusedClientComposition) {
2282 mTimeStats->incrementClientCompositionReusedFrames();
2283 }
2284
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002285 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002286
Alec Mouri717bcb62020-02-10 17:07:19 -08002287 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2288 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2289 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2290
Lloyd Pique32cbe282018-10-19 13:09:22 -07002291 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2292 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002293 return;
2294 }
2295
2296 nsecs_t currentTime = systemTime();
2297 if (mHasPoweredOff) {
2298 mHasPoweredOff = false;
2299 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002300 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002301 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002302 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2303 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002304 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002305 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002306 }
David Sodman4a36e932017-11-07 14:29:47 -08002307 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002308 }
David Sodman4a36e932017-11-07 14:29:47 -08002309 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002310
Alec Mouri4dde1782019-09-30 17:27:13 -07002311 // Cleanup any outstanding resources due to rendering a prior frame.
2312 getRenderEngine().cleanupPostRender();
2313
Dan Stoza436ccf32018-06-21 12:10:12 -07002314 {
2315 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002316 if (mTexturePool.size() < mTexturePoolSize) {
2317 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002318 const size_t offset = mTexturePool.size();
2319 mTexturePool.resize(mTexturePoolSize);
2320 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2321 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002322 } else if (mTexturePool.size() > mTexturePoolSize) {
2323 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2324 const size_t offset = mTexturePoolSize;
2325 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2326 mTexturePool.resize(mTexturePoolSize);
2327 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002328 }
2329 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002330
Kevin DuBois413287f2019-02-25 08:46:47 -08002331 if (mLumaSampling && mRegionSamplingThread) {
2332 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002333 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002334
2335 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2336 // side-effect of getTotalSize(), so we check that again here
2337 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002338 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002339 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2340 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002341}
2342
Lloyd Pique7eebe692020-04-22 22:40:06 -07002343FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2344 return displayDevice.getViewport().toFloatRect();
2345}
2346
Vishnu Nair4351ad52019-02-11 14:13:02 -08002347void SurfaceFlinger::computeLayerBounds() {
2348 for (const auto& pair : mDisplays) {
2349 const auto& displayDevice = pair.second;
2350 const auto display = displayDevice->getCompositionDisplay();
2351 for (const auto& layer : mDrawingState.layersSortedByZ) {
2352 // only consider the layers on the given layer stack
2353 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002354 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002355 }
2356
Lloyd Pique7eebe692020-04-22 22:40:06 -07002357 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002358 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002359 }
2360 }
2361}
2362
David Sodmanfa9b2af2017-12-24 13:28:59 -08002363void SurfaceFlinger::postFrame()
2364{
2365 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002366 const auto display = getDefaultDisplayDeviceLocked();
2367 if (display && getHwComposer().isConnected(*display->getId())) {
2368 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002369 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2370 logFrameStats();
2371 }
2372 }
2373}
2374
Mathias Agopian87baae12012-07-31 12:38:26 -07002375void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002376{
Mathias Agopian841cde52012-03-01 15:44:37 -08002377 ATRACE_CALL();
2378
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002379 // here we keep a copy of the drawing state (that is the state that's
2380 // going to be overwritten by handleTransactionLocked()) outside of
2381 // mStateLock so that the side-effects of the State assignment
2382 // don't happen with mStateLock held (which can cause deadlocks).
2383 State drawingState(mDrawingState);
2384
Mathias Agopianca4d3602011-05-19 15:38:14 -07002385 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002386 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002387
Mathias Agopianca4d3602011-05-19 15:38:14 -07002388 // Here we're guaranteed that some transaction flags are set
2389 // so we can call handleTransactionLocked() unconditionally.
2390 // We call getTransactionFlags(), which will also clear the flags,
2391 // with mStateLock held to guarantee that mCurrentState won't change
2392 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002393
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002394 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002395 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002396 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002397
Mathias Agopianca4d3602011-05-19 15:38:14 -07002398 mDebugInTransaction = 0;
2399 invalidateHwcGeometry();
2400 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002401}
2402
Lloyd Piqueba04e622017-12-14 17:11:26 -08002403void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2404 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405 const std::optional<DisplayIdentificationInfo> info =
2406 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002407
Dominik Laskowski075d3172018-05-24 15:50:06 -07002408 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002409 continue;
2410 }
2411
Dominik Laskowski55c85402020-01-21 16:25:47 -08002412 const DisplayId displayId = info->id;
2413 const auto it = mPhysicalDisplayTokens.find(displayId);
2414
Peiyong Line9d809e2020-04-14 13:10:48 -07002415 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002416 if (it == mPhysicalDisplayTokens.end()) {
2417 ALOGV("Creating display %s", to_string(displayId).c_str());
2418
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002419 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002420 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002421 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002422
Dominik Laskowski075d3172018-05-24 15:50:06 -07002423 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002424 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2425 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002426 state.isSecure = true; // All physical displays are currently considered secure.
2427 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002428
2429 sp<IBinder> token = new BBinder();
2430 mCurrentState.displays.add(token, state);
2431 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2432
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002434 } else {
2435 ALOGV("Recreating display %s", to_string(displayId).c_str());
2436
2437 const auto token = it->second;
2438 auto& state = mCurrentState.displays.editValueFor(token);
2439 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002440 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002441 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002442 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002443
Dominik Laskowski55c85402020-01-21 16:25:47 -08002444 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002445 if (index >= 0) {
2446 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2447 mInterceptor->saveDisplayDeletion(state.sequenceId);
2448 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002449 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002450 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002451 }
2452
2453 processDisplayChangesLocked();
2454 }
2455
2456 mPendingHotplugEvents.clear();
2457}
2458
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002459void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002460 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2461 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002462}
2463
Lloyd Pique99d3da52018-01-22 17:48:03 -08002464sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002465 const wp<IBinder>& displayToken,
2466 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002467 const DisplayDeviceState& state,
2468 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002470 auto displayId = compositionDisplay->getDisplayId();
2471 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002472 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002473 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002474 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002475 creationArgs.hasWideColorGamut = false;
2476 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002477
Dominik Laskowski55c85402020-01-21 16:25:47 -08002478 if (const auto& physical = state.physical) {
2479 creationArgs.connectionType = physical->type;
2480 }
2481
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002482 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002483 creationArgs.isPrimary = isInternalDisplay;
2484
2485 if (useColorManagement && displayId) {
2486 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002487 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002488 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002489 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002490 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002491
Dominik Laskowski7e045462018-05-30 13:02:02 -07002492 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002493 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002494 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002495 }
tangrobin6753a022018-08-10 10:58:54 +08002496 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002497
Dominik Laskowski075d3172018-05-24 15:50:06 -07002498 if (displayId) {
2499 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002500 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002501 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002502 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002503
Lloyd Pique90c115d2018-09-18 21:39:42 -07002504 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002505 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002506 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002507
Lloyd Pique99d3da52018-01-22 17:48:03 -08002508 // Make sure that composition can never be stalled by a virtual display
2509 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002510 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002511 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002512 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2513 }
2514
Dominik Laskowski718f9602019-11-09 20:01:35 -08002515 creationArgs.physicalOrientation =
2516 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002517
Lloyd Pique99d3da52018-01-22 17:48:03 -08002518 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002519 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002520
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002521 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522
2523 if (maxFrameBufferAcquiredBuffers >= 3) {
2524 nativeWindowSurface->preallocateBuffers();
2525 }
2526
2527 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002528 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002529 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002530 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002531 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002532 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002533 display->getCompositionDisplay()->setColorProfile(
2534 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2535 RenderIntent::COLORIMETRIC,
2536 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002537 if (!state.isVirtual()) {
2538 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002539 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2540 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002541 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002542
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002543 display->setLayerStack(state.layerStack);
2544 display->setProjection(state.orientation, state.viewport, state.frame);
2545 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002546
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002547 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002548}
2549
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002550void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2551 const DisplayDeviceState& state) {
2552 int width = 0;
2553 int height = 0;
2554 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2555 if (state.physical) {
2556 const auto& activeConfig =
2557 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2558 width = activeConfig->getWidth();
2559 height = activeConfig->getHeight();
2560 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2561 } else if (state.surface != nullptr) {
2562 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2563 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2564 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2565 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2566 int intPixelFormat;
2567 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2568 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2569 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2570 } else {
2571 // Virtual displays without a surface are dormant:
2572 // they have external state (layer stack, projection,
2573 // etc.) but no internal state (i.e. a DisplayDevice).
2574 return;
2575 }
2576
2577 compositionengine::DisplayCreationArgsBuilder builder;
2578 if (const auto& physical = state.physical) {
2579 builder.setPhysical({physical->id, physical->type});
2580 }
2581 builder.setPixels(ui::Size(width, height));
2582 builder.setPixelFormat(pixelFormat);
2583 builder.setIsSecure(state.isSecure);
2584 builder.setLayerStackId(state.layerStack);
2585 builder.setPowerAdvisor(&mPowerAdvisor);
2586 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2587 builder.setName(state.displayName);
2588 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2589
2590 sp<compositionengine::DisplaySurface> displaySurface;
2591 sp<IGraphicBufferProducer> producer;
2592 sp<IGraphicBufferProducer> bqProducer;
2593 sp<IGraphicBufferConsumer> bqConsumer;
2594 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2595
2596 std::optional<DisplayId> displayId = compositionDisplay->getId();
2597
2598 if (state.isVirtual()) {
2599 sp<VirtualDisplaySurface> vds =
2600 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2601 bqConsumer, state.displayName);
2602
2603 displaySurface = vds;
2604 producer = vds;
2605 } else {
2606 ALOGE_IF(state.surface != nullptr,
2607 "adding a supported display, but rendering "
2608 "surface is provided (%p), ignoring it",
2609 state.surface.get());
2610
2611 LOG_ALWAYS_FATAL_IF(!displayId);
2612 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2613 maxGraphicsWidth, maxGraphicsHeight);
2614 producer = bqProducer;
2615 }
2616
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002617 LOG_FATAL_IF(!displaySurface);
2618 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2619 displaySurface, producer);
2620 mDisplays.emplace(displayToken, display);
2621 if (!state.isVirtual()) {
2622 LOG_FATAL_IF(!displayId);
2623 dispatchDisplayHotplugEvent(displayId->value, true);
2624 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002625
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002626 if (display->isPrimary()) {
2627 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002628 }
2629}
2630
2631void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2632 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2633 // Save display ID before disconnecting.
2634 const auto displayId = display->getId();
2635 display->disconnect();
2636
2637 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002638 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002639 dispatchDisplayHotplugEvent(displayId->value, false);
2640 }
2641 }
2642
2643 mDisplays.erase(displayToken);
2644}
2645
2646void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2647 const DisplayDeviceState& currentState,
2648 const DisplayDeviceState& drawingState) {
2649 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2650 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002651 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002652 // changing the surface is like destroying and recreating the DisplayDevice
2653 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2654 display->disconnect();
2655 }
2656 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002657 if (const auto& physical = currentState.physical) {
2658 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2659 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002660 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002661 if (currentState.physical) {
2662 initializeDisplays();
2663 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002664 return;
2665 }
2666
2667 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2668 if (currentState.layerStack != drawingState.layerStack) {
2669 display->setLayerStack(currentState.layerStack);
2670 }
2671 if ((currentState.orientation != drawingState.orientation) ||
2672 (currentState.viewport != drawingState.viewport) ||
2673 (currentState.frame != drawingState.frame)) {
2674 display->setProjection(currentState.orientation, currentState.viewport,
2675 currentState.frame);
2676 }
2677 if (currentState.width != drawingState.width ||
2678 currentState.height != drawingState.height) {
2679 display->setDisplaySize(currentState.width, currentState.height);
2680 if (display->isPrimary()) {
2681 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2682 }
2683 }
2684 }
2685}
2686
Lloyd Pique347200f2017-12-14 17:00:15 -08002687void SurfaceFlinger::processDisplayChangesLocked() {
2688 // here we take advantage of Vector's copy-on-write semantics to
2689 // improve performance by skipping the transaction entirely when
2690 // know that the lists are identical
2691 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2692 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2693 if (!curr.isIdenticalTo(draw)) {
2694 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002695
2696 // find the displays that were removed
2697 // (ie: in drawing state but not in current state)
2698 // also handle displays that changed
2699 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002700 for (size_t i = 0; i < draw.size(); i++) {
2701 const wp<IBinder>& displayToken = draw.keyAt(i);
2702 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002703 if (j < 0) {
2704 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002705 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002706 } else {
2707 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002708 const DisplayDeviceState& currentState = curr[j];
2709 const DisplayDeviceState& drawingState = draw[i];
2710 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002712 }
2713
2714 // find displays that were added
2715 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002716 for (size_t i = 0; i < curr.size(); i++) {
2717 const wp<IBinder>& displayToken = curr.keyAt(i);
2718 if (draw.indexOfKey(displayToken) < 0) {
2719 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002720 }
2721 }
2722 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002723
2724 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002725}
2726
Mathias Agopian87baae12012-07-31 12:38:26 -07002727void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002728{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002729 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2730
Dan Stoza7dde5992015-05-22 09:51:44 -07002731 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002732 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002733 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002734 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002735
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736 /*
2737 * Traversal of the children
2738 * (perform the transaction for each of them if needed)
2739 */
2740
Marissa Wall06255332019-03-27 13:48:27 -07002741 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002742 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002744 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745
2746 const uint32_t flags = layer->doTransaction(0);
2747 if (flags & Layer::eVisibleRegion)
2748 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002749
2750 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002751 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002752 }
Robert Carr2047fae2016-11-28 14:09:09 -08002753 });
Marissa Wall06255332019-03-27 13:48:27 -07002754 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755 }
2756
2757 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002758 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759 */
2760
Mathias Agopiane57f2922012-08-09 16:29:12 -07002761 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002762 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002763 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002764 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002766 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002767 // The transform hint might have changed for some layers
2768 // (either because a display has changed, or because a layer
2769 // as changed).
2770 //
2771 // Walk through all the layers in currentLayers,
2772 // and update their transform hint.
2773 //
2774 // If a layer is visible only on a single display, then that
2775 // display is used to calculate the hint, otherwise we use the
2776 // default display.
2777 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002778 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002779 // the hint is set before we acquire a buffer from the surface texture.
2780 //
2781 // NOTE: layer transactions have taken place already, so we use their
2782 // drawing state. However, SurfaceFlinger's own transaction has not
2783 // happened yet, so we must use the current state layer list
2784 // (soon to become the drawing state list).
2785 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002786 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002787 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002788 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002789 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002790 // NOTE: we rely on the fact that layers are sorted by
2791 // layerStack first (so we don't have to traverse the list
2792 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002793 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002794 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002795 currentlayerStack = layerStack;
2796 // figure out if this layerstack is mirrored
2797 // (more than one display) if so, pick the default display,
2798 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002799 hintDisplay = nullptr;
2800 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002801 if (display->getCompositionDisplay()
2802 ->belongsInOutput(layer->getLayerStack(),
2803 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002804 if (hintDisplay) {
2805 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002806 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002807 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002808 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002809 }
2810 }
2811 }
2812 }
Chet Haase91d25932013-04-11 15:24:55 -07002813
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002814 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002815 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2816 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002817
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002818 // could be null when this layer is using a layerStack
2819 // that is not visible on any display. Also can occur at
2820 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002821 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002822 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002823
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002824 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002825 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002826 if (hintDisplay) {
2827 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002828 }
Robert Carr2047fae2016-11-28 14:09:09 -08002829
2830 first = false;
2831 });
Mathias Agopian84300952012-11-21 16:02:13 -08002832 }
2833
2834
Mathias Agopian3559b072012-08-15 13:46:03 -07002835 /*
2836 * Perform our own transaction if needed
2837 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002838
2839 if (mLayersAdded) {
2840 mLayersAdded = false;
2841 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002842 mVisibleRegionsDirty = true;
2843 }
2844
2845 // some layers might have been removed, so
2846 // we need to update the regions they're exposing.
2847 if (mLayersRemoved) {
2848 mLayersRemoved = false;
2849 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002850 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002851 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002852 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002853 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002854 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002855 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002856 }
Robert Carr2047fae2016-11-28 14:09:09 -08002857 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 }
2859
Vishnu Nairec0ab382019-02-13 15:32:56 -08002860 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002862}
2863
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002864void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002865 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002866 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002867 return;
2868 }
2869
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002870 if (mVisibleRegionsDirty || mInputInfoChanged) {
2871 mInputInfoChanged = false;
2872 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002873 } else if (mInputWindowCommands.syncInputWindows) {
2874 // If the caller requested to sync input windows, but there are no
2875 // changes to input windows, notify immediately.
2876 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002877 }
2878
Arthur Hung6cbb9752019-09-05 16:38:18 +08002879 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002880}
2881
2882void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002883 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002884
2885 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2886 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002887 // When calculating the screen bounds we ignore the transparent region since it may
2888 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002889 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002890 }
2891 });
chaviw291d88a2019-02-14 10:33:58 -08002892
2893 mInputFlinger->setInputWindows(inputHandles,
2894 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2895 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002896}
2897
Vishnu Nairec0ab382019-02-13 15:32:56 -08002898void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002899 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002900 mPendingInputWindowCommands.clear();
2901}
2902
Riley Andrews03414a12014-07-01 14:22:59 -07002903void SurfaceFlinger::updateCursorAsync()
2904{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002905 compositionengine::CompositionRefreshArgs refreshArgs;
2906 for (const auto& [_, display] : mDisplays) {
2907 if (display->getId()) {
2908 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002909 }
2910 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002911
2912 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002913}
2914
Ady Abraham2139f732019-11-13 18:56:40 -08002915void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002916 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2917 // If this is called from the main thread mStateLock must be locked before
2918 // Currently the only way to call this function from the main thread is from
2919 // Sheduler::chooseRefreshRateForContent
2920
2921 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002922 changeRefreshRateLocked(refreshRate, event);
2923}
2924
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002925void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2926 if (mScheduler) {
2927 // In practice it's not allowed to hotplug in/out the primary display once it's been
2928 // connected during startup, but some tests do it, so just warn and return.
2929 ALOGW("Can't re-init scheduler");
2930 return;
2931 }
2932
Ady Abraham2139f732019-11-13 18:56:40 -08002933 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002934 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002935 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002936 primaryDisplayId),
2937 currentConfig);
2938 mRefreshRateStats =
2939 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002940 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002941 mRefreshRateStats->setConfigMode(currentConfig);
2942
Ady Abraham9e16a482019-12-03 17:19:41 -08002943 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2944
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002945 // start the EventThread
2946 mScheduler =
2947 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002948 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002949 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002950 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002951 impl::EventThread::InterceptVSyncsCallback());
2952 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002953 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002954 [this](nsecs_t timestamp) {
2955 mInterceptor->saveVSyncEvent(timestamp);
2956 });
2957
2958 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2959 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002960 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002961
2962 mRegionSamplingThread =
2963 new RegionSamplingThread(*this, *mScheduler,
2964 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002965 // Dispatch a config change request for the primary display on scheduler
2966 // initialization, so that the EventThreads always contain a reference to a
2967 // prior configuration.
2968 //
2969 // This is a bit hacky, but this avoids a back-pointer into the main SF
2970 // classes from EventThread, and there should be no run-time binder cost
2971 // anyway since there are no connected apps at this point.
2972 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002973 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Alec Mouri60aee1c2019-10-28 16:18:59 -07002974 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2975 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002976}
2977
Mathias Agopian4fec8732012-06-29 14:12:52 -07002978void SurfaceFlinger::commitTransaction()
2979{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002980 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002981 mTransactionPending = false;
2982 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002983 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002984}
2985
Lloyd Pique58e24a32019-08-01 15:50:14 -07002986void SurfaceFlinger::commitTransactionLocked() {
2987 if (!mLayersPendingRemoval.isEmpty()) {
2988 // Notify removed layers now that they can't be drawn from
2989 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002990 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002991
2992 // Ensure any buffers set to display on any children are released.
2993 if (l->isRemovedFromCurrentState()) {
2994 l->latchAndReleaseBuffer();
2995 }
2996
2997 // If the layer has been removed and has no parent, then it will not be reachable
2998 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2999 // ensure we can copy its current to drawing state.
3000 if (!l->getParent()) {
3001 mOffscreenLayers.emplace(l.get());
3002 }
3003 }
3004 mLayersPendingRemoval.clear();
3005 }
3006
3007 // If this transaction is part of a window animation then the next frame
3008 // we composite should be considered an animation as well.
3009 mAnimCompositionPending = mAnimTransactionPending;
3010
3011 mDrawingState = mCurrentState;
3012 // clear the "changed" flags in current state
3013 mCurrentState.colorMatrixChanged = false;
3014
Edgar Arriaga844fa672020-01-16 14:21:42 -08003015 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003016 layer->commitChildList();
3017
3018 // If the layer can be reached when traversing mDrawingState, then the layer is no
3019 // longer offscreen. Remove the layer from the offscreenLayer set.
3020 if (mOffscreenLayers.count(layer)) {
3021 mOffscreenLayers.erase(layer);
3022 }
3023 });
3024
3025 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003026 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003027}
3028
chaviw74d90ad2019-04-26 14:45:26 -07003029void SurfaceFlinger::commitOffscreenLayers() {
3030 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003031 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003032 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3033 if (!trFlags) return;
3034
3035 layer->doTransaction(0);
3036 layer->commitChildList();
3037 });
3038 }
3039}
3040
Chia-I Wuab0c3192017-08-01 11:29:00 -07003041void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003042 for (const auto& [token, displayDevice] : mDisplays) {
3043 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003044 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003045 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003046 }
3047 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003048}
3049
Dan Stoza6b9454d2014-11-07 16:00:59 -08003050bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003051{
Ady Abraham09bd3922019-04-08 10:44:56 -07003052 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003053 ALOGV("handlePageFlip");
3054
Brian Andersond6927fb2016-07-23 23:37:30 -07003055 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003056
Mathias Agopian4fec8732012-06-29 14:12:52 -07003057 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003058 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003059 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003060
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003061 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3062
Eric Penner51c59cd2014-07-28 19:51:58 -07003063 // Store the set of layers that need updates. This set must not change as
3064 // buffers are being latched, as this could result in a deadlock.
3065 // Example: Two producers share the same command stream and:
3066 // 1.) Layer 0 is latched
3067 // 2.) Layer 0 gets a new frame
3068 // 2.) Layer 1 gets a new frame
3069 // 3.) Layer 1 is latched.
3070 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3071 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003072 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003073 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003074 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003075 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003076 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003077 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003078 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003079 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003080 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003081 } else {
3082 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003083 }
Robert Carr2047fae2016-11-28 14:09:09 -08003084 });
3085
chaviw49a108c2019-08-12 11:23:06 -07003086 // The client can continue submitting buffers for offscreen layers, but they will not
3087 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3088 // layers to ensure dequeueBuffer doesn't block indefinitely.
3089 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003090 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003091 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3092 }
3093
Lloyd Piquef2c79392018-12-20 16:23:33 -08003094 if (!mLayersWithQueuedFrames.empty()) {
3095 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3096 // writes to Layer current state. See also b/119481871
3097 Mutex::Autolock lock(mStateLock);
3098
3099 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003100 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003101 mLayersPendingRefresh.push_back(layer);
3102 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003103 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003104 if (layer->isBufferLatched()) {
3105 newDataLatched = true;
3106 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003107 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003108 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003109
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003110 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003111
3112 // If we will need to wake up at some time in the future to deal with a
3113 // queued frame that shouldn't be displayed during this vsync period, wake
3114 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003115 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003116 signalLayerUpdate();
3117 }
3118
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003119 // enter boot animation on first buffer latch
3120 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3121 ALOGI("Enter boot animation");
3122 mBootStage = BootStage::BOOTANIMATION;
3123 }
3124
Edgar Arriaga844fa672020-01-16 14:21:42 -08003125 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003126
Dan Stoza6b9454d2014-11-07 16:00:59 -08003127 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003128 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129}
3130
Mathias Agopianad456f92011-01-13 17:53:01 -08003131void SurfaceFlinger::invalidateHwcGeometry()
3132{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003133 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003134}
3135
Robert Carrc0df3122019-04-11 13:18:21 -07003136status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3137 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3138 const sp<IBinder>& parentHandle,
3139 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003140 // add this layer to the current state list
3141 {
3142 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003143 sp<Layer> parent;
3144 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003145 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003146 if (parent == nullptr) {
3147 return NAME_NOT_FOUND;
3148 }
3149 } else {
3150 parent = parentLayer;
3151 }
3152
Ady Abraham0a525092020-03-03 12:51:24 -08003153 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003154 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003155 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003156 return NO_MEMORY;
3157 }
Robert Carrc0df3122019-04-11 13:18:21 -07003158
3159 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3160
Robert Carrb89ea9d2018-12-10 13:01:14 -08003161 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003162 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003163 } else if (parent == nullptr) {
3164 lbc->onRemovedFromCurrentState();
3165 } else if (parent->isRemovedFromCurrentState()) {
3166 parent->addChild(lbc);
3167 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003168 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003169 parent->addChild(lbc);
3170 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003171
Yiwei Zhang243b3782018-05-15 17:40:04 -07003172 if (gbc != nullptr) {
3173 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3174 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3175 mMaxGraphicBufferProducerListSize,
3176 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3177 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003178 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003179 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003180 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003181 }
3182
Mathias Agopian96f08192010-06-02 23:28:45 -07003183 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003184 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003185
Dan Stoza7d89d062015-04-30 13:29:25 -07003186 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003187}
3188
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003189void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3190 static_cast<void>(schedule([=] {
3191 Mutex::Autolock lock(mStateLock);
3192 mGraphicBufferProducerList.erase(binder);
3193 }));
3194}
3195
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003196uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003197 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003198}
3199
Mathias Agopian3f844832013-08-07 21:24:32 -07003200uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003201 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202}
3203
Mathias Agopian3f844832013-08-07 21:24:32 -07003204uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003205 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003206}
3207
3208uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003209 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003210 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003211 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003213 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 }
3215 return old;
3216}
3217
Marissa Wall713b63f2018-10-17 15:42:43 -07003218bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003219 // to prevent onHandleDestroyed from being called while the lock is held,
3220 // we must keep a copy of the transactions (specifically the composer
3221 // states) around outside the scope of the lock
3222 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003223 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003224 {
3225 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003226
Valerie Haufce31b82019-04-30 16:41:14 -07003227 auto it = mTransactionQueues.begin();
3228 while (it != mTransactionQueues.end()) {
3229 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003230
Valerie Haufce31b82019-04-30 16:41:14 -07003231 while (!transactionQueue.empty()) {
3232 const auto& transaction = transactionQueue.front();
3233 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3234 transaction.states)) {
3235 setTransactionFlags(eTransactionFlushNeeded);
3236 break;
3237 }
3238 transactions.push_back(transaction);
3239 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3240 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003241 transaction.buffer, transaction.postTime,
3242 transaction.privileged, transaction.hasListenerCallbacks,
3243 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003244 transactionQueue.pop();
3245 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003246 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003247
Valerie Haufce31b82019-04-30 16:41:14 -07003248 if (transactionQueue.empty()) {
3249 it = mTransactionQueues.erase(it);
3250 mTransactionCV.broadcast();
3251 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003252 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003253 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003254 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003255 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003256 return flushedATransaction;
3257}
3258
3259bool SurfaceFlinger::transactionFlushNeeded() {
3260 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003261}
3262
chaviwca27f252018-02-06 16:46:39 -08003263
Marissa Wall17b4e452018-12-26 16:32:34 -08003264bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3265 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003266
3267 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003268 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3269 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3270 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3271 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3272 return false;
3273 }
3274
Marissa Wall713b63f2018-10-17 15:42:43 -07003275 for (const ComposerState& state : states) {
3276 const layer_state_t& s = state.state;
3277 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3278 continue;
3279 }
3280 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003281 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003282 }
3283 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003284 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003285}
3286
Valerie Hau9dab9732019-08-20 09:29:25 -07003287void SurfaceFlinger::setTransactionState(
3288 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3289 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3290 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3291 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003292 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003293
Valerie Haubc6ddb12019-03-08 11:10:15 -08003294 const int64_t postTime = systemTime();
3295
Robert Carr14167e02019-02-13 13:50:55 -08003296 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3297
Mathias Agopian698c0872011-06-28 19:09:31 -07003298 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003299
Marissa Wall713b63f2018-10-17 15:42:43 -07003300 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003301 auto itr = mTransactionQueues.find(applyToken);
3302 // if this is an animation frame, wait until prior animation frame has
3303 // been applied by SF
3304 if (flags & eAnimation) {
3305 while (itr != mTransactionQueues.end()) {
3306 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3307 if (CC_UNLIKELY(err != NO_ERROR)) {
3308 ALOGW_IF(err == TIMED_OUT,
3309 "setTransactionState timed out "
3310 "waiting for animation frame to apply");
3311 break;
3312 }
3313 itr = mTransactionQueues.find(applyToken);
3314 }
3315 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003316
Ady Abraham5facfb12020-04-22 15:18:31 -07003317 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003318 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003319 if (!pendingTransactions) {
3320 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3321 }
3322
3323 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003324 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003325 uncacheBuffer, postTime, privileged,
3326 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003327 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003328 return;
3329 }
3330
Valerie Haubc6ddb12019-03-08 11:10:15 -08003331 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003332 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3333 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003334}
3335
Valerie Hau9dab9732019-08-20 09:29:25 -07003336void SurfaceFlinger::applyTransactionState(
3337 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3338 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3339 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3340 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3341 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003342 uint32_t transactionFlags = 0;
3343
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003344 if (flags & eAnimation) {
3345 // For window updates that are part of an animation we must wait for
3346 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003347 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003348 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003349 if (CC_UNLIKELY(err != NO_ERROR)) {
3350 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003351 // caller after a few seconds.
3352 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3353 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003354 mAnimTransactionPending = false;
3355 break;
3356 }
3357 }
3358 }
3359
chaviwca27f252018-02-06 16:46:39 -08003360 for (const DisplayState& display : displays) {
3361 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003362 }
3363
Valerie Hau9dab9732019-08-20 09:29:25 -07003364 // start and end registration for listeners w/ no surface so they can get their callback. Note
3365 // that listeners with SurfaceControls will start registration during setClientStateLocked
3366 // below.
3367 for (const auto& listener : listenerCallbacks) {
3368 mTransactionCompletedThread.startRegistration(listener);
3369 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003370 }
3371
Valerie Hau9dab9732019-08-20 09:29:25 -07003372 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003373 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003374 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003375 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3376 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003377 }
3378
Valerie Hau9dab9732019-08-20 09:29:25 -07003379 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003380 mTransactionCompletedThread.endRegistration(listenerCallback);
3381 }
3382
Marissa Walle2ffb422018-10-12 11:33:52 -07003383 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003384 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003385 mTransactionCompletedThread.sendCallbacks();
3386 }
3387 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003388
chaviw273171b2018-12-26 11:46:30 -08003389 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3390
Marissa Wall947d34e2019-03-29 14:03:53 -07003391 if (uncacheBuffer.isValid()) {
3392 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003393 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003394 }
3395
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003396 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3397 // anyway. This can be used as a flush mechanism for previous async transactions.
3398 // Empty animation transaction can be used to simulate back-pressure, so also force a
3399 // transaction for empty animation transactions.
3400 if (transactionFlags == 0 &&
3401 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003402 transactionFlags = eTransactionNeeded;
3403 }
3404
Marissa Wall06255332019-03-27 13:48:27 -07003405 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3406 // so we don't have to wake up again next frame to preform an uneeded traversal.
3407 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3408 transactionFlags = transactionFlags & (~eTraversalNeeded);
3409 mTraversalNeededMainThread = true;
3410 }
3411
Mathias Agopian386aa982011-11-07 21:58:03 -08003412 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003413 if (mInterceptor->isEnabled()) {
3414 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003415 }
Irvel468051e2016-06-13 16:44:44 -07003416
Mathias Agopian386aa982011-11-07 21:58:03 -08003417 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003418 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3419 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003420 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003421
3422 // if this is a synchronous transaction, wait for it to take effect
3423 // before returning.
3424 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003425 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003426 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003427 if (flags & eAnimation) {
3428 mAnimTransactionPending = true;
3429 }
chaviw4fe36852019-04-15 16:25:49 -07003430 if (mPendingInputWindowCommands.syncInputWindows) {
3431 mPendingSyncInputWindows = true;
3432 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003433
3434 // applyTransactionState can be called by either the main SF thread or by
3435 // another process through setTransactionState. While a given process may wish
3436 // to wait on synchronous transactions, the main SF thread should never
3437 // be blocked. Therefore, we only wait if isMainThread is false.
3438 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003439 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3440 if (CC_UNLIKELY(err != NO_ERROR)) {
3441 // just in case something goes wrong in SF, return to the
3442 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003443 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3444 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003445 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003446 break;
3447 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003448 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003449 }
3450}
3451
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003452uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3453 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3454 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003455
Mathias Agopiane57f2922012-08-09 16:29:12 -07003456 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003457 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3458
3459 const uint32_t what = s.what;
3460 if (what & DisplayState::eSurfaceChanged) {
3461 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3462 state.surface = s.surface;
3463 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003464 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003465 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003466 if (what & DisplayState::eLayerStackChanged) {
3467 if (state.layerStack != s.layerStack) {
3468 state.layerStack = s.layerStack;
3469 flags |= eDisplayTransactionNeeded;
3470 }
3471 }
3472 if (what & DisplayState::eDisplayProjectionChanged) {
3473 if (state.orientation != s.orientation) {
3474 state.orientation = s.orientation;
3475 flags |= eDisplayTransactionNeeded;
3476 }
3477 if (state.frame != s.frame) {
3478 state.frame = s.frame;
3479 flags |= eDisplayTransactionNeeded;
3480 }
3481 if (state.viewport != s.viewport) {
3482 state.viewport = s.viewport;
3483 flags |= eDisplayTransactionNeeded;
3484 }
3485 }
3486 if (what & DisplayState::eDisplaySizeChanged) {
3487 if (state.width != s.width) {
3488 state.width = s.width;
3489 flags |= eDisplayTransactionNeeded;
3490 }
3491 if (state.height != s.height) {
3492 state.height = s.height;
3493 flags |= eDisplayTransactionNeeded;
3494 }
3495 }
3496
Mathias Agopiane57f2922012-08-09 16:29:12 -07003497 return flags;
3498}
3499
Steven Thomasd4071902020-03-24 16:02:53 -07003500bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003501 IPCThreadState* ipc = IPCThreadState::self();
3502 const int pid = ipc->getCallingPid();
3503 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003504 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003505 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3506 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003507 return false;
3508 }
3509 return true;
3510}
3511
Marissa Wall3dad52d2019-03-22 14:03:19 -07003512uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003513 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3514 bool privileged,
3515 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003516 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003517
Valerie Hau9dab9732019-08-20 09:29:25 -07003518 for (auto& listener : s.listeners) {
3519 // note that startRegistration will not re-register if the listener has
3520 // already be registered for a prior surface control
3521 mTransactionCompletedThread.startRegistration(listener);
3522 listenerCallbacks.insert(listener);
3523 }
3524
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003525 sp<Layer> layer = nullptr;
3526 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003527 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003528 } else {
3529 // The client may provide us a null handle. Treat it as if the layer was removed.
3530 ALOGW("Attempt to set client state with a null layer handle");
3531 }
chaviw8b3871a2017-11-01 17:41:01 -07003532 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003533 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003534 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003535 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003536 }
chaviw8b3871a2017-11-01 17:41:01 -07003537 return 0;
3538 }
3539
chaviw8b3871a2017-11-01 17:41:01 -07003540 uint32_t flags = 0;
3541
Garfield Tan8a3083e2018-12-03 13:21:07 -08003542 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003543
3544 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3545 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003546 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003547 layer->pushPendingState();
3548 }
3549
Valerie Hau871d6352020-01-29 08:44:02 -08003550 // Only set by BLAST adapter layers
3551 if (what & layer_state_t::eProducerDisconnect) {
3552 layer->onDisconnect();
3553 }
3554
chaviw8b3871a2017-11-01 17:41:01 -07003555 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003556 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003557 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003558 }
chaviw8b3871a2017-11-01 17:41:01 -07003559 }
3560 if (what & layer_state_t::eLayerChanged) {
3561 // NOTE: index needs to be calculated before we update the state
3562 const auto& p = layer->getParent();
3563 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003564 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003565 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003566 mCurrentState.layersSortedByZ.removeAt(idx);
3567 mCurrentState.layersSortedByZ.add(layer);
3568 // we need traversal (state changed)
3569 // AND transaction (list changed)
3570 flags |= eTransactionNeeded|eTraversalNeeded;
3571 }
chaviw8b3871a2017-11-01 17:41:01 -07003572 } else {
3573 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003574 flags |= eTransactionNeeded|eTraversalNeeded;
3575 }
3576 }
chaviw8b3871a2017-11-01 17:41:01 -07003577 }
3578 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003579 // NOTE: index needs to be calculated before we update the state
3580 const auto& p = layer->getParent();
3581 if (p == nullptr) {
3582 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3583 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3584 mCurrentState.layersSortedByZ.removeAt(idx);
3585 mCurrentState.layersSortedByZ.add(layer);
3586 // we need traversal (state changed)
3587 // AND transaction (list changed)
3588 flags |= eTransactionNeeded|eTraversalNeeded;
3589 }
3590 } else {
3591 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3592 flags |= eTransactionNeeded|eTraversalNeeded;
3593 }
chaviw8b3871a2017-11-01 17:41:01 -07003594 }
3595 }
3596 if (what & layer_state_t::eSizeChanged) {
3597 if (layer->setSize(s.w, s.h)) {
3598 flags |= eTraversalNeeded;
3599 }
3600 }
3601 if (what & layer_state_t::eAlphaChanged) {
3602 if (layer->setAlpha(s.alpha))
3603 flags |= eTraversalNeeded;
3604 }
3605 if (what & layer_state_t::eColorChanged) {
3606 if (layer->setColor(s.color))
3607 flags |= eTraversalNeeded;
3608 }
Peiyong Lind3788632018-09-18 16:01:31 -07003609 if (what & layer_state_t::eColorTransformChanged) {
3610 if (layer->setColorTransform(s.colorTransform)) {
3611 flags |= eTraversalNeeded;
3612 }
3613 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003614 if (what & layer_state_t::eBackgroundColorChanged) {
3615 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3616 flags |= eTraversalNeeded;
3617 }
3618 }
chaviw8b3871a2017-11-01 17:41:01 -07003619 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003620 // TODO: b/109894387
3621 //
3622 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3623 // rotation. To see the problem observe that if we have a square parent, and a child
3624 // of the same size, then we rotate the child 45 degrees around it's center, the child
3625 // must now be cropped to a non rectangular 8 sided region.
3626 //
3627 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3628 // private API, and the WindowManager only uses rotation in one case, which is on a top
3629 // level layer in which cropping is not an issue.
3630 //
3631 // However given that abuse of rotation matrices could lead to surfaces extending outside
3632 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3633 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3634 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003635 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003636 flags |= eTraversalNeeded;
3637 }
3638 if (what & layer_state_t::eTransparentRegionChanged) {
3639 if (layer->setTransparentRegionHint(s.transparentRegion))
3640 flags |= eTraversalNeeded;
3641 }
3642 if (what & layer_state_t::eFlagsChanged) {
3643 if (layer->setFlags(s.flags, s.mask))
3644 flags |= eTraversalNeeded;
3645 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003646 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003647 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003648 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003649 if (what & layer_state_t::eCornerRadiusChanged) {
3650 if (layer->setCornerRadius(s.cornerRadius))
3651 flags |= eTraversalNeeded;
3652 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003653 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003654 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3655 }
chaviw8b3871a2017-11-01 17:41:01 -07003656 if (what & layer_state_t::eLayerStackChanged) {
3657 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3658 // We only allow setting layer stacks for top level layers,
3659 // everything else inherits layer stack from its parent.
3660 if (layer->hasParent()) {
3661 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003662 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003663 } else if (idx < 0) {
3664 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003665 "that also does not appear in the top level layer list. Something"
3666 " has gone wrong.",
3667 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003668 } else if (layer->setLayerStack(s.layerStack)) {
3669 mCurrentState.layersSortedByZ.removeAt(idx);
3670 mCurrentState.layersSortedByZ.add(layer);
3671 // we need traversal (state changed)
3672 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003673 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003674 }
3675 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003676 if (what & layer_state_t::eDeferTransaction_legacy) {
3677 if (s.barrierHandle_legacy != nullptr) {
3678 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3679 } else if (s.barrierGbp_legacy != nullptr) {
3680 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003681 if (authenticateSurfaceTextureLocked(gbp)) {
3682 const auto& otherLayer =
3683 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003684 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003685 } else {
3686 ALOGE("Attempt to defer transaction to to an"
3687 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003688 }
3689 }
chaviw8b3871a2017-11-01 17:41:01 -07003690 // We don't trigger a traversal here because if no other state is
3691 // changed, we don't want this to cause any more work
3692 }
chaviw8b3871a2017-11-01 17:41:01 -07003693 if (what & layer_state_t::eReparentChildren) {
3694 if (layer->reparentChildren(s.reparentHandle)) {
3695 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003696 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003697 }
chaviw8b3871a2017-11-01 17:41:01 -07003698 if (what & layer_state_t::eDetachChildren) {
3699 layer->detachChildren();
3700 }
3701 if (what & layer_state_t::eOverrideScalingModeChanged) {
3702 layer->setOverrideScalingMode(s.overrideScalingMode);
3703 // We don't trigger a traversal here because if no other state is
3704 // changed, we don't want this to cause any more work
3705 }
Marissa Wall61c58622018-07-18 10:12:20 -07003706 if (what & layer_state_t::eTransformChanged) {
3707 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3708 }
3709 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3710 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3711 flags |= eTraversalNeeded;
3712 }
3713 if (what & layer_state_t::eCropChanged) {
3714 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3715 }
Marissa Wall861616d2018-10-22 12:52:23 -07003716 if (what & layer_state_t::eFrameChanged) {
3717 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3718 }
Marissa Wall61c58622018-07-18 10:12:20 -07003719 if (what & layer_state_t::eAcquireFenceChanged) {
3720 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3721 }
3722 if (what & layer_state_t::eDataspaceChanged) {
3723 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3724 }
3725 if (what & layer_state_t::eHdrMetadataChanged) {
3726 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3727 }
3728 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3729 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3730 }
3731 if (what & layer_state_t::eApiChanged) {
3732 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3733 }
3734 if (what & layer_state_t::eSidebandStreamChanged) {
3735 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3736 }
Robert Carr720e5062018-07-30 17:45:14 -07003737 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003738 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003739 layer->setInputInfo(s.inputInfo);
3740 flags |= eTraversalNeeded;
3741 } else {
3742 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3743 }
Robert Carr720e5062018-07-30 17:45:14 -07003744 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003745 if (what & layer_state_t::eMetadataChanged) {
3746 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3747 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003748 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3749 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3750 flags |= eTraversalNeeded;
3751 }
3752 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003753 if (what & layer_state_t::eShadowRadiusChanged) {
3754 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3755 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003756 if (what & layer_state_t::eFrameRateSelectionPriority) {
3757 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3758 flags |= eTraversalNeeded;
3759 }
3760 }
Steven Thomas3172e202020-01-06 19:25:30 -08003761 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003762 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3763 "SurfaceFlinger::setClientStateLocked") &&
3764 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3765 Layer::FrameRate::convertCompatibility(
3766 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003767 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003768 }
Steven Thomas3172e202020-01-06 19:25:30 -08003769 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003770 // This has to happen after we reparent children because when we reparent to null we remove
3771 // child layers from current state and remove its relative z. If the children are reparented in
3772 // the same transaction, then we have to make sure we reparent the children first so we do not
3773 // lose its relative z order.
3774 if (what & layer_state_t::eReparent) {
3775 bool hadParent = layer->hasParent();
3776 if (layer->reparent(s.parentHandleForChild)) {
3777 if (!hadParent) {
3778 mCurrentState.layersSortedByZ.remove(layer);
3779 }
3780 flags |= eTransactionNeeded | eTraversalNeeded;
3781 }
3782 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003783 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003784 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3785 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003786 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3787 }
3788 }
Marissa Wall78b72202019-03-15 14:58:34 -07003789 bool bufferChanged = what & layer_state_t::eBufferChanged;
3790 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3791 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003792 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003793 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003794 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3795 if (success) {
3796 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3797 success = ClientCache::getInstance()
3798 .registerErasedRecipient(s.cachedBuffer,
3799 wp<ClientCache::ErasedRecipient>(this));
3800 if (!success) {
3801 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3802 }
3803 }
Marissa Wall78b72202019-03-15 14:58:34 -07003804 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003805 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003806 } else if (bufferChanged) {
3807 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003808 }
Marissa Wall78b72202019-03-15 14:58:34 -07003809 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003810 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3811 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003812 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003813 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003814 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003815 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3816 // Do not put anything that updates layer state or modifies flags after
3817 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003818 return flags;
3819}
3820
chaviw273171b2018-12-26 11:46:30 -08003821uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3822 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003823 if (inputWindowCommands.syncInputWindows) {
3824 flags |= eTraversalNeeded;
3825 }
3826
Vishnu Nairec0ab382019-02-13 15:32:56 -08003827 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003828 return flags;
3829}
3830
chaviwfe94a222019-08-21 13:52:59 -07003831status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3832 sp<IBinder>* outHandle) {
3833 if (!mirrorFromHandle) {
3834 return NAME_NOT_FOUND;
3835 }
3836
3837 sp<Layer> mirrorLayer;
3838 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003839 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003840
3841 {
3842 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003843 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003844 if (!mirrorFrom) {
3845 return NAME_NOT_FOUND;
3846 }
3847
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003848 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3849 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003850 if (result != NO_ERROR) {
3851 return result;
3852 }
3853
3854 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3855 }
3856
3857 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3858}
3859
Marissa Wall2d814fb2019-04-09 18:52:57 +00003860status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3861 uint32_t h, PixelFormat format, uint32_t flags,
3862 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003863 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003864 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3865 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003866 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003867 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003868 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003869 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003870 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003871
Robert Carrc0df3122019-04-11 13:18:21 -07003872 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3873 "Expected only one of parentLayer or parentHandle to be non-null. "
3874 "Programmer error?");
3875
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003876 status_t result = NO_ERROR;
3877
3878 sp<Layer> layer;
3879
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003880 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003881
Evan Roskya1f1e152019-01-24 16:17:46 -08003882 bool primaryDisplayOnly = false;
3883
3884 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3885 // TODO b/64227542
3886 if (metadata.has(METADATA_WINDOW_TYPE)) {
3887 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3888 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003889 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003890 primaryDisplayOnly = true;
3891 }
3892 }
3893
Mathias Agopian3165cc22012-08-08 19:42:09 -07003894 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003895 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003896 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3897 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003898
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003899 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003900 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003901 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003902 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003903 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003904 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003905 // check if buffer size is set for color layer.
3906 if (w > 0 || h > 0) {
3907 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3908 int(w), int(h));
3909 return BAD_VALUE;
3910 }
3911
Vishnu Nairfa247b12020-02-11 08:58:26 -08003912 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3913 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003914 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003915 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003916 // check if buffer size is set for container layer.
3917 if (w > 0 || h > 0) {
3918 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3919 int(w), int(h));
3920 return BAD_VALUE;
3921 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003922 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3923 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003924 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003925 default:
3926 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003927 break;
3928 }
3929
Dan Stoza7d89d062015-04-30 13:29:25 -07003930 if (result != NO_ERROR) {
3931 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003933
Evan Roskya1f1e152019-01-24 16:17:46 -08003934 if (primaryDisplayOnly) {
3935 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003936 }
3937
Robert Carrb89ea9d2018-12-10 13:01:14 -08003938 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003939 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3940 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003941 if (result != NO_ERROR) {
3942 return result;
3943 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003944 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003945
3946 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003947 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003948}
3949
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003950std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3951 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003952
3953 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003954 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003955
Dan Stoza436ccf32018-06-21 12:10:12 -07003956 // Grab the state lock since we're accessing mCurrentState
3957 Mutex::Autolock lock(mStateLock);
3958
Cody Northropbc755282017-03-31 12:00:08 -06003959 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003960 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003961 while (matchFound) {
3962 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003963 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003964 if (layer->getName() == uniqueName) {
3965 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003966 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003967 }
3968 });
3969 }
3970
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003971 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003972 return uniqueName;
3973}
3974
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003975status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003976 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003977 LayerMetadata metadata, PixelFormat& format,
3978 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003979 sp<IGraphicBufferProducer>* gbp,
3980 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003981 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003982 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003983 case PIXEL_FORMAT_TRANSPARENT:
3984 case PIXEL_FORMAT_TRANSLUCENT:
3985 format = PIXEL_FORMAT_RGBA_8888;
3986 break;
3987 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003988 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003989 break;
3990 }
3991
chaviwb4c6e582019-08-16 14:35:07 -07003992 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003993 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003994 args.textureName = getNewTexture();
3995 {
3996 // Grab the SF state lock during this since it's the only safe way to access
3997 // RenderEngine when creating a BufferLayerConsumer
3998 // TODO: Check if this lock is still needed here
3999 Mutex::Autolock lock(mStateLock);
4000 layer = getFactory().createBufferQueueLayer(args);
4001 }
4002
Marissa Wallfd668622018-05-10 10:21:13 -07004003 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004004 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004005 *handle = layer->getHandle();
4006 *gbp = layer->getProducer();
4007 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004008 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004009
Marissa Wallfd668622018-05-10 10:21:13 -07004010 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004011 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004012}
4013
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004014status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004015 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004016 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004017 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004018 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004019 args.displayDevice = getDefaultDisplayDevice();
4020 args.textureName = getNewTexture();
4021 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004022 if (outTransformHint) {
4023 *outTransformHint = layer->getTransformHint();
4024 }
Marissa Wall61c58622018-07-18 10:12:20 -07004025 *handle = layer->getHandle();
4026 *outLayer = layer;
4027
4028 return NO_ERROR;
4029}
4030
Vishnu Nairfa247b12020-02-11 08:58:26 -08004031status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4032 uint32_t h, uint32_t flags, LayerMetadata metadata,
4033 sp<IBinder>* handle, sp<Layer>* outLayer) {
4034 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004035 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004036 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004037 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004038}
4039
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004040status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004041 uint32_t w, uint32_t h, uint32_t flags,
4042 LayerMetadata metadata, sp<IBinder>* handle,
4043 sp<Layer>* outLayer) {
4044 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004045 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004046 *handle = (*outLayer)->getHandle();
4047 return NO_ERROR;
4048}
4049
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004050void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004051 mLayersPendingRemoval.add(layer);
4052 mLayersRemoved = true;
4053 setTransactionFlags(eTransactionNeeded);
4054}
4055
Robert Carr695d5282018-12-18 15:27:58 -08004056void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004057{
Robert Carr2e102c92018-10-23 12:11:15 -07004058 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004059 // If a layer has a parent, we allow it to out-live it's handle
4060 // with the idea that the parent holds a reference and will eventually
4061 // be cleaned up. However no one cleans up the top-level so we do so
4062 // here.
4063 if (layer->getParent() == nullptr) {
4064 mCurrentState.layersSortedByZ.remove(layer);
4065 }
4066 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004067
4068 auto it = mLayersByLocalBinderToken.begin();
4069 while (it != mLayersByLocalBinderToken.end()) {
4070 if (it->second == layer) {
4071 it = mLayersByLocalBinderToken.erase(it);
4072 } else {
4073 it++;
4074 }
4075 }
4076
Robert Carr695d5282018-12-18 15:27:58 -08004077 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004078}
4079
Mathias Agopianb60314a2012-04-10 22:09:54 -07004080// ---------------------------------------------------------------------------
4081
Andy McFadden13a082e2012-08-24 10:16:42 -07004082void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004083 const auto display = getDefaultDisplayDeviceLocked();
4084 if (!display) return;
4085
4086 const sp<IBinder> token = display->getDisplayToken().promote();
4087 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004088
Jesse Hall01e29052013-02-19 16:13:35 -08004089 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004090 Vector<ComposerState> state;
4091 Vector<DisplayState> displays;
4092 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004093 d.what = DisplayState::eDisplayProjectionChanged |
4094 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004095 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004096 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004097 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004098 d.frame.makeInvalid();
4099 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004100 d.width = 0;
4101 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004102 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004103 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4104 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004105
Peiyong Lin65248e02020-04-18 21:15:07 -07004106 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004107
Dominik Laskowski83b88212018-12-11 13:34:06 -08004108 const nsecs_t vsyncPeriod = getVsyncPeriod();
4109 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004110
Brian Andersond0010582017-03-07 13:20:31 -08004111 // Use phase of 0 since phase is not known.
4112 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004113 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004114 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004115}
4116
4117void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004118 // Async since we may be called from the main thread.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004119 static_cast<void>(schedule([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004120}
4121
Peiyong Line9d809e2020-04-14 13:10:48 -07004122void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, hal::Vsync enabled) {
Ady Abraham27c70212019-06-11 10:52:26 -07004123 if (mHWCVsyncState != enabled) {
4124 getHwComposer().setVsyncEnabled(displayId, enabled);
4125 mHWCVsyncState = enabled;
4126 }
4127}
4128
Peiyong Lin65248e02020-04-18 21:15:07 -07004129void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004130 if (display->isVirtual()) {
4131 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004132 return;
4133 }
4134
Dominik Laskowski075d3172018-05-24 15:50:06 -07004135 const auto displayId = display->getId();
4136 LOG_ALWAYS_FATAL_IF(!displayId);
4137
Dominik Laskowski34157762018-10-31 13:07:19 -07004138 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004139
Peiyong Lin65248e02020-04-18 21:15:07 -07004140 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004141 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004142 return;
4143 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004144
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004145 display->setPowerMode(mode);
4146
Lloyd Pique4dccc412018-01-22 17:21:36 -08004147 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004148 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004149 }
4150
Peiyong Lin65248e02020-04-18 21:15:07 -07004151 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004152 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4153 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4154 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004155 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004156 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004157 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004158 mScheduler->onScreenAcquired(mAppConnectionHandle);
4159 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004160 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004161
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004162 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004163 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004164 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004165 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004166 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004167 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4168 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004169 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004170 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004171 mScheduler->disableHardwareVsync(true);
4172 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004173 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004174
Ady Abraham27c70212019-06-11 10:52:26 -07004175 // Make sure HWVsync is disabled before turning off the display
Peiyong Line9d809e2020-04-14 13:10:48 -07004176 setVsyncEnabledInHWC(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004177
Dominik Laskowski075d3172018-05-24 15:50:06 -07004178 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004179 mVisibleRegionsDirty = true;
4180 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004181 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004182 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004183 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004184 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004185 mScheduler->onScreenAcquired(mAppConnectionHandle);
4186 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004187 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004188 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004189 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004190 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004191 mScheduler->disableHardwareVsync(true);
4192 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004193 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004194 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004195 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004196 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004197 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004198 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004199
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004200 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004201 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004202 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004203 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004204 }
4205
Dominik Laskowski34157762018-10-31 13:07:19 -07004206 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004207}
4208
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004209void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004210 schedule([=]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004211 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004212 if (!display) {
4213 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4214 displayToken.get());
4215 } else if (display->isVirtual()) {
4216 ALOGW("Attempt to set power mode %d for virtual display", mode);
4217 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004218 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004219 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004220 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004221}
4222
Dominik Laskowskic2867142019-01-21 11:33:38 -08004223status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4224 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004225 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004226
Mathias Agopianbd115332013-04-18 16:41:04 -07004227 IPCThreadState* ipc = IPCThreadState::self();
4228 const int pid = ipc->getCallingPid();
4229 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004230
Mathias Agopianbd115332013-04-18 16:41:04 -07004231 if ((uid != AID_SHELL) &&
4232 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004233 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4234 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004235 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004236 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004237 // (this would indicate SF is stuck, but we want to be able to
4238 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004239 status_t err = mStateLock.timedLock(s2ns(1));
4240 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004241 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004242 StringAppendF(&result,
4243 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4244 "(no locks held)\n",
4245 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004246 }
4247
Dominik Laskowskic2867142019-01-21 11:33:38 -08004248 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004249 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004250 {"--dispsync"s,
4251 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004252 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004253 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4254 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4255 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4256 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4257 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4258 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004259 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004260 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4261 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004262
Dominik Laskowskic2867142019-01-21 11:33:38 -08004263 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004264
Dominik Laskowski46470112019-08-02 13:13:11 -07004265 const auto it = dumpers.find(flag);
4266 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004267 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004268 } else if (!asProto) {
4269 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004270 }
4271
Mathias Agopian9795c422009-08-26 16:36:26 -07004272 if (locked) {
4273 mStateLock.unlock();
4274 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004275
Dominik Laskowski46470112019-08-02 13:13:11 -07004276 if (it == dumpers.end()) {
4277 const LayersProto layersProto = dumpProtoFromMainThread();
4278 if (asProto) {
4279 result.append(layersProto.SerializeAsString());
4280 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004281 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004282 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4283 result.append(LayerProtoParser::layerTreeToString(layerTree));
4284 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004285 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004286 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004287 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004288 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004289 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004290 return NO_ERROR;
4291}
4292
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004293status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4294 if (asProto && mTracing.isEnabled()) {
4295 mTracing.writeToFileAsync();
4296 }
4297
4298 return doDump(fd, DumpArgs(), asProto);
4299}
4300
Dominik Laskowskic2867142019-01-21 11:33:38 -08004301void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004302 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004303 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004304}
4305
Dominik Laskowskic2867142019-01-21 11:33:38 -08004306void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004307 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004308
Dominik Laskowskic2867142019-01-21 11:33:38 -08004309 if (args.size() > 1) {
4310 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004311 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004312 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004313 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004314 }
Robert Carr2047fae2016-11-28 14:09:09 -08004315 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004316 } else {
4317 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318 }
4319}
4320
Dominik Laskowskic2867142019-01-21 11:33:38 -08004321void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004322 const bool clearAll = args.size() < 2;
4323 const auto name = clearAll ? String8() : String8(args[1]);
4324
Edgar Arriaga844fa672020-01-16 14:21:42 -08004325 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004326 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004327 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004328 }
Robert Carr2047fae2016-11-28 14:09:09 -08004329 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004330
Svetoslavd85084b2014-03-20 10:28:31 -07004331 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004332}
4333
Dominik Laskowskic2867142019-01-21 11:33:38 -08004334void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4335 mTimeStats->parseArgs(asProto, args, result);
4336}
4337
Jamie Gennis6547ff42013-07-16 20:12:42 -07004338// This should only be called from the main thread. Otherwise it would need
4339// the lock and should use mCurrentState rather than mDrawingState.
4340void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004341 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004342 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004343 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004344
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004345 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004346}
4347
Yiwei Zhang5434a782018-12-05 18:06:32 -08004348void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004349 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004350
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004351 if (isLayerTripleBufferingDisabled())
4352 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004353
Yiwei Zhang5434a782018-12-05 18:06:32 -08004354 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4355 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4356 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4357 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4358 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4359 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004360 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004361}
4362
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004363void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004364 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004365
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004366 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004367 result.append("\n");
4368
Ady Abraham9e16a482019-12-03 17:19:41 -08004369 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004370 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004371 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004372 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004373
Steven Thomasd4071902020-03-24 16:02:53 -07004374 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004375 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004376 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004377 ", min: %.2f Hz, max: %.2f Hz",
Steven Thomasd4071902020-03-24 16:02:53 -07004378 policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004379 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4380 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004381 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4382 if (currentPolicy != policy) {
4383 StringAppendF(&result,
4384 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
4385 ", min: %.2f Hz, max: %.2f Hz\n\n",
4386 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
4387 currentPolicy.maxRefreshRate);
4388 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004389
Ana Krulecc2870422019-01-29 19:00:58 -08004390 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004391 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004392}
4393
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4395 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004396 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4397 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004398 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004399 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004400 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004401 }
David Sodman4a36e932017-11-07 14:29:47 -08004402 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004403 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004404 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004405 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4406 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004407}
4408
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004409void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4410 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004411 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4412 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004413 for (const auto& segment : history) {
4414 if (!segment.usedThirdBuffer) {
4415 stats.twoBufferTime += segment.totalTime;
4416 }
4417 if (segment.occupancyAverage < 1.0f) {
4418 stats.doubleBufferedTime += segment.totalTime;
4419 } else if (segment.occupancyAverage < 2.0f) {
4420 stats.tripleBufferedTime += segment.totalTime;
4421 }
4422 ++stats.numSegments;
4423 stats.totalTime += segment.totalTime;
4424 }
4425}
4426
Yiwei Zhang5434a782018-12-05 18:06:32 -08004427void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4428 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004429
4430 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4431 const size_t count = currentLayers.size();
4432 for (size_t i=0 ; i<count ; i++) {
4433 currentLayers[i]->dumpFrameEvents(result);
4434 }
4435}
4436
Yiwei Zhang5434a782018-12-05 18:06:32 -08004437void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004438 result.append("Buffering stats:\n");
4439 result.append(" [Layer name] <Active time> <Two buffer> "
4440 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004441 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004442 typedef std::tuple<std::string, float, float, float> BufferTuple;
4443 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004444 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004445 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004446 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004447 if (stats.numSegments == 0) {
4448 continue;
4449 }
4450 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4451 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4452 stats.totalTime;
4453 float doubleBufferRatio = static_cast<float>(
4454 stats.doubleBufferedTime) / stats.totalTime;
4455 float tripleBufferRatio = static_cast<float>(
4456 stats.tripleBufferedTime) / stats.totalTime;
4457 sorted.insert({activeTime, {name, twoBufferRatio,
4458 doubleBufferRatio, tripleBufferRatio}});
4459 }
4460 for (const auto& sortedPair : sorted) {
4461 float activeTime = sortedPair.first;
4462 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004463 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4464 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004465 }
4466 result.append("\n");
4467}
4468
Yiwei Zhang5434a782018-12-05 18:06:32 -08004469void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004470 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004471 const auto displayId = display->getId();
4472 if (!displayId) {
4473 continue;
4474 }
4475 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004476 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004477 continue;
4478 }
4479
Yiwei Zhang5434a782018-12-05 18:06:32 -08004480 StringAppendF(&result,
4481 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4482 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004483 uint8_t port;
4484 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004485 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004486 result.append("no identification data\n");
4487 continue;
4488 }
4489
4490 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004491 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004492 continue;
4493 }
4494
4495 const auto edid = parseEdid(data);
4496 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004497 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004498 continue;
4499 }
4500
Yiwei Zhang5434a782018-12-05 18:06:32 -08004501 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004502 result.append(edid->displayName.data(), edid->displayName.length());
4503 result.append("\"\n");
4504 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004505}
4506
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004507void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4508 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004509 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004510 uint8_t port;
4511 DisplayIdentificationData data;
4512
4513 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4514 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4515 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4516 }
4517}
4518
Yiwei Zhang5434a782018-12-05 18:06:32 -08004519void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004520 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004521 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4522 StringAppendF(&result, "DisplayColorSetting: %s\n",
4523 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004524
4525 // TODO: print out if wide-color mode is active or not
4526
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004527 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004528 const auto displayId = display->getId();
4529 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004530 continue;
4531 }
4532
Yiwei Zhang5434a782018-12-05 18:06:32 -08004533 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004534 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004535 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004537 }
4538
Lloyd Pique32cbe282018-10-19 13:09:22 -07004539 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004540 StringAppendF(&result, " Current color mode: %s (%d)\n",
4541 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004542 }
4543 result.append("\n");
4544}
4545
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004546LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4547 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
4548 const auto display = getDefaultDisplayDeviceLocked();
4549
chaviw1d044282017-09-27 12:19:28 -07004550 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004551 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004552 layer->writeToProto(layersProto, traceFlags, display);
chaviw08f3cb22020-01-13 13:17:21 -08004553 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004554
chaviw1d044282017-09-27 12:19:28 -07004555 return layersProto;
4556}
4557
Alec Mouri6b9e9912020-01-21 10:50:24 -08004558void SurfaceFlinger::dumpHwc(std::string& result) const {
4559 getHwComposer().dump(result);
4560}
4561
Vishnu Nair0f085c62019-08-30 08:49:12 -07004562void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4563 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4564 // it.
4565 LayerProto* rootProto = layersProto.add_layers();
4566 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4567 rootProto->set_id(offscreenRootLayerId);
4568 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004569 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004570
4571 for (Layer* offscreenLayer : mOffscreenLayers) {
4572 // Add layer as child of the fake root
4573 rootProto->add_children(offscreenLayer->sequence);
4574
4575 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004576 LayerProto* layerProto =
4577 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004578 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004579 }
4580}
4581
Vishnu Nair8406fd72019-07-30 11:29:31 -07004582LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004583 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004584}
4585
Vishnu Nair0f085c62019-08-30 08:49:12 -07004586void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4587 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004588 result.append(schedule([this] {
4589 std::string result;
4590 for (Layer* offscreenLayer : mOffscreenLayers) {
4591 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4592 [&](Layer* layer) {
4593 layer->dumpCallingUidPid(result);
4594 });
4595 }
4596 return result;
4597 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004598}
4599
Dominik Laskowskic2867142019-01-21 11:33:38 -08004600void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4601 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004602 Colorizer colorizer(colorize);
4603
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004604 // figure out if we're stuck somewhere
4605 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004606 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004607 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4608
4609 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004610 * Dump library configuration.
4611 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004612
4613 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004614 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004615 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004616 appendSfConfigString(result);
4617 appendUiConfigString(result);
4618 appendGuiConfigString(result);
4619 result.append("\n");
4620
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004621 result.append("\nDisplay identification data:\n");
4622 dumpDisplayIdentificationData(result);
4623
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004624 result.append("\nWide-Color information:\n");
4625 dumpWideColorInfo(result);
4626
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004627 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004628 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004629 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004630 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004631 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004632
Andy McFadden41d67d72014-04-25 16:58:34 -07004633 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004634 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004635 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004636 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004637 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004638
Dan Stozab90cf072015-03-05 11:05:59 -08004639 dumpStaticScreenStats(result);
4640 result.append("\n");
4641
Alec Mouri40189b02019-03-05 15:07:54 -08004642 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4643 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4644 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004645
Dan Stozae77c7662016-05-13 11:37:28 -07004646 dumpBufferingStats(result);
4647
Andy McFadden4803b742012-09-24 19:07:20 -07004648 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004649 * Dump the visible layer list
4650 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004651 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004652 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004653 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4654 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004655 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004656
Chia-I Wu2f884132018-09-13 15:17:58 -07004657 {
Lloyd Pique207def92019-02-28 16:09:52 -08004658 StringAppendF(&result, "Composition layers\n");
4659 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004660 auto* compositionState = layer->getCompositionState();
4661 if (!compositionState) return;
4662
4663 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4664 layer->getDebugName() ? layer->getDebugName()
4665 : "<unknown>");
4666 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004667 });
4668 }
4669
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004670 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004671 * Dump Display state
4672 */
4673
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004674 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004676 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004677 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004678 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004679 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004680 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004681
4682 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004683 * Dump CompositionEngine state
4684 */
4685
4686 mCompositionEngine->dump(result);
4687
4688 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004689 * Dump SurfaceFlinger global state
4690 */
4691
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004692 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004693 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004694 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004695
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004696 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004697
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004698 DebugEGLImageTracker::getInstance()->dump(result);
4699
Dominik Laskowski075d3172018-05-24 15:50:06 -07004700 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004701 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4702 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004703 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4704 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004705 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004706 StringAppendF(&result,
4707 " transaction-flags : %08x\n"
4708 " gpu_to_cpu_unsupported : %d\n",
4709 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004710
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004711 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004712 displayId && getHwComposer().isConnected(*displayId)) {
4713 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004714 StringAppendF(&result,
4715 " refresh-rate : %f fps\n"
4716 " x-dpi : %f\n"
4717 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004718 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4719 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004720 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004721
Yiwei Zhang5434a782018-12-05 18:06:32 -08004722 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004723
Dan Stozae22aec72016-08-01 13:20:59 -07004724 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004725 * Tracing state
4726 */
4727 mTracing.dump(result);
4728 result.append("\n");
4729
4730 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004731 * HWC layer minidump
4732 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004733 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004734 const auto displayId = display->getId();
4735 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004736 continue;
4737 }
4738
Yiwei Zhang5434a782018-12-05 18:06:32 -08004739 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004740 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004741 const sp<DisplayDevice> displayDevice = display;
4742 mCurrentState.traverseInZOrder(
4743 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004744 result.append("\n");
4745 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004746
4747 /*
4748 * Dump HWComposer state
4749 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004750 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004751 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004752 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004753 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004754 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004755 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004756
4757 /*
4758 * Dump gralloc state
4759 */
4760 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4761 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004762
4763 /*
4764 * Dump VrFlinger state if in use.
4765 */
4766 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4767 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004768 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004769 result.append("\n");
4770 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004771
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004772 result.append(mTimeStats->miniDump());
4773 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004774}
4775
Chia-I Wu28f320b2018-05-03 11:02:56 -07004776void SurfaceFlinger::updateColorMatrixLocked() {
4777 mat4 colorMatrix;
4778 if (mGlobalSaturationFactor != 1.0f) {
4779 // Rec.709 luma coefficients
4780 float3 luminance{0.213f, 0.715f, 0.072f};
4781 luminance *= 1.0f - mGlobalSaturationFactor;
4782 mat4 saturationMatrix = mat4(
4783 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4784 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4785 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4786 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4787 );
4788 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4789 } else {
4790 colorMatrix = mClientColorMatrix * mDaltonizer();
4791 }
4792
4793 if (mCurrentState.colorMatrix != colorMatrix) {
4794 mCurrentState.colorMatrix = colorMatrix;
4795 mCurrentState.colorMatrixChanged = true;
4796 setTransactionFlags(eTransactionNeeded);
4797 }
4798}
4799
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004800status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004801#pragma clang diagnostic push
4802#pragma clang diagnostic error "-Wswitch-enum"
4803 switch (static_cast<ISurfaceComposerTag>(code)) {
4804 // These methods should at minimum make sure that the client requested
4805 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004806 case BOOT_FINISHED:
4807 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004808 case CREATE_DISPLAY:
4809 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004810 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004811 case GET_ANIMATION_FRAME_STATS:
4812 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004813 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004814 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004815 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004816 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4817 case SET_AUTO_LOW_LATENCY_MODE:
4818 case GET_GAME_CONTENT_TYPE_SUPPORT:
4819 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004820 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004821 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004822 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004823 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004824 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004825 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004826 case SET_GLOBAL_SHADOW_SETTINGS:
4827 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4828 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4829 // necessary permission dynamically. Don't use the permission cache for this check.
4830 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4831 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004832 IPCThreadState* ipc = IPCThreadState::self();
4833 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4834 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004835 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004836 }
Robert Carr1db73f62016-12-21 12:58:51 -08004837 return OK;
4838 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004839 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004840 IPCThreadState* ipc = IPCThreadState::self();
4841 const int pid = ipc->getCallingPid();
4842 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004843 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4844 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004845 return PERMISSION_DENIED;
4846 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004847 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004848 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004849 // Used by apps to hook Choreographer to SurfaceFlinger.
4850 case CREATE_DISPLAY_EVENT_CONNECTION:
4851 // The following calls are currently used by clients that do not
4852 // request necessary permissions. However, they do not expose any secret
4853 // information, so it is OK to pass them.
4854 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004855 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004856 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004857 case GET_PHYSICAL_DISPLAY_IDS:
4858 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004859 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004860 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004861 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004862 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004863 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864 case GET_DISPLAY_STATS:
4865 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4866 // Calling setTransactionState is safe, because you need to have been
4867 // granted a reference to Client* and Handle* to do anything with it.
4868 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004869 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004870 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004871 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004872 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004873 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004874 // setFrameRate() is deliberately available for apps to call without any
4875 // special permissions.
4876 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004877 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4878 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004879 return OK;
4880 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004881 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004882 case CAPTURE_SCREEN:
4883 case ADD_REGION_SAMPLING_LISTENER:
4884 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004885 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004886 IPCThreadState* ipc = IPCThreadState::self();
4887 const int pid = ipc->getCallingPid();
4888 const int uid = ipc->getCallingUid();
4889 if ((uid != AID_GRAPHICS) &&
4890 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4891 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4892 return PERMISSION_DENIED;
4893 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004894 return OK;
4895 }
chaviw93df2ea2019-04-30 16:45:12 -07004896 case CAPTURE_SCREEN_BY_ID: {
4897 IPCThreadState* ipc = IPCThreadState::self();
4898 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004899 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004900 return OK;
4901 }
4902 return PERMISSION_DENIED;
4903 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004904 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004905
4906 // These codes are used for the IBinder protocol to either interrogate the recipient
4907 // side of the transaction for its canonical interface descriptor or to dump its state.
4908 // We let them pass by default.
4909 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4910 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4911 code == IBinder::SYSPROPS_TRANSACTION) {
4912 return OK;
4913 }
Ady Abraham07e54702020-04-16 15:05:37 -07004914 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004915 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004916 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004917 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4918 return OK;
4919 }
4920 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4921 return PERMISSION_DENIED;
4922#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004923}
4924
Ana Krulec13be8ad2018-08-21 02:43:56 +00004925status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4926 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004927 status_t credentialCheck = CheckTransactCodeCredentials(code);
4928 if (credentialCheck != OK) {
4929 return credentialCheck;
4930 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004931
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004932 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4933 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004934 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004935 IPCThreadState* ipc = IPCThreadState::self();
4936 const int uid = ipc->getCallingUid();
4937 if (CC_UNLIKELY(uid != AID_SYSTEM
4938 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004939 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004940 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004941 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004942 return PERMISSION_DENIED;
4943 }
4944 int n;
4945 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004946 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004947 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004948 return NO_ERROR;
4949 case 1002: // SHOW_UPDATES
4950 n = data.readInt32();
4951 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004952 invalidateHwcGeometry();
4953 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004954 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004955 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004956 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004957 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004958 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004959 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004960 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004961 setTransactionFlags(
4962 eTransactionNeeded|
4963 eDisplayTransactionNeeded|
4964 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004965 return NO_ERROR;
4966 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004967 case 1006:{ // send empty update
4968 signalRefresh();
4969 return NO_ERROR;
4970 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004971 case 1008: // toggle use of hw composer
4972 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004973 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004974 invalidateHwcGeometry();
4975 repaintEverything();
4976 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004977 case 1009: // toggle use of transform hint
4978 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004979 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004980 invalidateHwcGeometry();
4981 repaintEverything();
4982 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004983 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004984 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004985 reply->writeInt32(0);
4986 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004987 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004988 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 return NO_ERROR;
4990 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004991 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004992 if (!display) {
4993 return NAME_NOT_FOUND;
4994 }
4995
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004996 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004997 return NO_ERROR;
4998 }
4999 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005000 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005001 // daltonize
5002 n = data.readInt32();
5003 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005004 case 1:
5005 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5006 break;
5007 case 2:
5008 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5009 break;
5010 case 3:
5011 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5012 break;
5013 default:
5014 mDaltonizer.setType(ColorBlindnessType::None);
5015 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005016 }
5017 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005018 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005019 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005020 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005021 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005022
5023 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005024 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005025 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005026 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005027 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005028 // apply a color matrix
5029 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005030 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005031 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005032 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005033 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005034 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005035 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005036 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005037 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005038 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005039 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005040
5041 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5042 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005043 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005044 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5045 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5046 }
5047
Chia-I Wu28f320b2018-05-03 11:02:56 -07005048 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005049 return NO_ERROR;
5050 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005051 case 1016: { // Unused.
5052 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005053 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005054 case 1017: {
5055 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005056 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005057 return NO_ERROR;
5058 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005059 case 1018: { // Modify Choreographer's phase offset
5060 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005061 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005062 return NO_ERROR;
5063 }
5064 case 1019: { // Modify SurfaceFlinger's phase offset
5065 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005066 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005067 return NO_ERROR;
5068 }
Irvel468051e2016-06-13 16:44:44 -07005069 case 1020: { // Layer updates interceptor
5070 n = data.readInt32();
5071 if (n) {
5072 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005073 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005074 }
5075 else{
5076 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005077 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005078 }
5079 return NO_ERROR;
5080 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005081 case 1021: { // Disable HWC virtual displays
5082 n = data.readInt32();
5083 mUseHwcVirtualDisplays = !n;
5084 return NO_ERROR;
5085 }
Romain Guy0147a172017-06-01 13:53:56 -07005086 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005087 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005088 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005089
Chia-I Wu28f320b2018-05-03 11:02:56 -07005090 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005091 return NO_ERROR;
5092 }
Romain Guy54f154a2017-10-24 21:40:32 +01005093 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005094 int32_t colorMode;
5095
Chia-I Wu0d711262018-05-21 15:19:35 -07005096 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005097 if (data.readInt32(&colorMode) == NO_ERROR) {
5098 mForceColorMode = static_cast<ColorMode>(colorMode);
5099 }
Romain Guy54f154a2017-10-24 21:40:32 +01005100 invalidateHwcGeometry();
5101 repaintEverything();
5102 return NO_ERROR;
5103 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005104 // Deprecate, use 1030 to check whether the device is color managed.
5105 case 1024: {
5106 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005107 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005108 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005109 n = data.readInt32();
5110 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005111 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005112 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005113 reply->writeInt32(NO_ERROR);
5114 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005115 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005116 mTracingEnabledChanged = mTracing.disable();
5117 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005118 reply->writeInt32(mTracing.writeToFile());
5119 } else {
5120 reply->writeInt32(NO_ERROR);
5121 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005122 }
5123 return NO_ERROR;
5124 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005125 case 1026: { // Get layer tracing status
5126 reply->writeBool(mTracing.isEnabled());
5127 return NO_ERROR;
5128 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005129 // Is a DisplayColorSetting supported?
5130 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005131 const auto display = getDefaultDisplayDevice();
5132 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005133 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005134 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005135
5136 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5137 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005138 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005139 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005140 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005141 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005142 reply->writeBool(true);
5143 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005144 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005145 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005146 break;
5147 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005148 reply->writeBool(
5149 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005150 break;
5151 }
5152 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005153 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005154 // Is VrFlinger active?
5155 case 1028: {
5156 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005157 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005158 return NO_ERROR;
5159 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005160 // Set buffer size for SF tracing (value in KB)
5161 case 1029: {
5162 n = data.readInt32();
5163 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5164 ALOGW("Invalid buffer size: %d KB", n);
5165 reply->writeInt32(BAD_VALUE);
5166 return BAD_VALUE;
5167 }
5168
5169 ALOGD("Updating trace buffer to %d KB", n);
5170 mTracing.setBufferSize(n * 1024);
5171 reply->writeInt32(NO_ERROR);
5172 return NO_ERROR;
5173 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005174 // Is device color managed?
5175 case 1030: {
5176 reply->writeBool(useColorManagement);
5177 return NO_ERROR;
5178 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005179 // Override default composition data space
5180 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5181 // && adb shell stop zygote && adb shell start zygote
5182 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5183 // adb shell stop zygote && adb shell start zygote
5184 case 1031: {
5185 Mutex::Autolock _l(mStateLock);
5186 n = data.readInt32();
5187 if (n) {
5188 n = data.readInt32();
5189 if (n) {
5190 Dataspace dataspace = static_cast<Dataspace>(n);
5191 if (!validateCompositionDataspace(dataspace)) {
5192 return BAD_VALUE;
5193 }
5194 mDefaultCompositionDataspace = dataspace;
5195 }
5196 n = data.readInt32();
5197 if (n) {
5198 Dataspace dataspace = static_cast<Dataspace>(n);
5199 if (!validateCompositionDataspace(dataspace)) {
5200 return BAD_VALUE;
5201 }
5202 mWideColorGamutCompositionDataspace = dataspace;
5203 }
5204 } else {
5205 // restore composition data space.
5206 mDefaultCompositionDataspace = defaultCompositionDataspace;
5207 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5208 }
5209 return NO_ERROR;
5210 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005211 // Set trace flags
5212 case 1033: {
5213 n = data.readUint32();
5214 ALOGD("Updating trace flags to 0x%x", n);
5215 mTracing.setTraceFlags(n);
5216 reply->writeInt32(NO_ERROR);
5217 return NO_ERROR;
5218 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005219 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005220 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005221 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005222 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005223 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005224 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005225 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005226 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005227 } else {
5228 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005229 }
5230 return NO_ERROR;
5231 }
Ady Abraham34392f72019-04-10 11:29:27 -07005232 case 1035: {
5233 n = data.readInt32();
5234 mDebugDisplayConfigSetByBackdoor = false;
5235 if (n >= 0) {
5236 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005237 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005238 if (result != NO_ERROR) {
5239 return result;
5240 }
5241 mDebugDisplayConfigSetByBackdoor = true;
5242 }
5243 return NO_ERROR;
5244 }
Ady Abraham07e54702020-04-16 15:05:37 -07005245 case 1036: {
5246 if (data.readInt32() > 0) {
5247 status_t result =
5248 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5249 if (result != NO_ERROR) {
5250 return result;
5251 }
5252 } else {
5253 mDebugFrameRateFlexibilityToken = nullptr;
5254 }
5255 return NO_ERROR;
5256 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005257 }
5258 }
5259 return err;
5260}
5261
Steven Thomas6d8110b2017-08-31 18:24:21 -07005262void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005263 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005264 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005265}
5266
Ana Krulec7d1d6832018-12-27 11:10:09 -08005267void SurfaceFlinger::repaintEverythingForHWC() {
5268 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005269 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005270 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005271}
5272
Ady Abrahama09852a2020-02-20 14:23:42 -08005273void SurfaceFlinger::kernelTimerChanged(bool expired) {
5274 static bool updateOverlay =
5275 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5276 if (!updateOverlay || !mRefreshRateOverlay) return;
5277
5278 // Update the overlay on the main thread to avoid race conditions with
5279 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005280 static_cast<void>(schedule([=]() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahama09852a2020-02-20 14:23:42 -08005281 if (mRefreshRateOverlay) {
5282 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5283 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005284 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005285 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5286 if (mDesiredActiveConfigChanged) {
5287 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5288 mDesiredActiveConfig.configId);
5289 }
5290
5291 return mRefreshRateConfigs->getCurrentRefreshRate();
5292 }();
5293 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5294
5295 if (current != min) {
5296 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5297 mEventQueue->invalidate();
5298 }
5299 }
5300 }));
5301}
5302
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005303// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5304class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005305public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005306 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5307 ~WindowDisconnector() {
5308 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005309 }
5310
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005311private:
5312 ANativeWindow* mWindow;
5313 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005314};
5315
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005316status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005317 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005318 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5319 const Rect& sourceCrop, uint32_t reqWidth,
5320 uint32_t reqHeight, bool useIdentityTransform,
5321 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005322 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005323
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005324 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005325
Dominik Laskowski718f9602019-11-09 20:01:35 -08005326 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5327 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5328 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5329 renderAreaRotation = ui::Transform::ROT_0;
5330 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005331
Chia-I Wu20261cb2018-08-23 12:55:44 -07005332 sp<DisplayDevice> display;
5333 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005334 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005335
Chia-I Wu20261cb2018-08-23 12:55:44 -07005336 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005337 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005338
Chia-I Wucb023152018-08-28 12:57:23 -07005339 // set the requested width/height to the logical display viewport size
5340 // by default
5341 if (reqWidth == 0 || reqHeight == 0) {
5342 reqWidth = uint32_t(display->getViewport().width());
5343 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005344 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005345 }
5346
Peiyong Lin0e003c92018-09-17 11:09:51 -07005347 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005348 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005349 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5350 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005351 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005352 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005353}
5354
chaviw93df2ea2019-04-30 16:45:12 -07005355static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5356 switch (colorMode) {
5357 case ColorMode::DISPLAY_P3:
5358 case ColorMode::BT2100_PQ:
5359 case ColorMode::BT2100_HLG:
5360 case ColorMode::DISPLAY_BT2020:
5361 return Dataspace::DISPLAY_P3;
5362 default:
5363 return Dataspace::V0_SRGB;
5364 }
5365}
5366
Martin Liu4a322352020-03-24 21:30:38 +08005367status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5368 static constexpr int kFifoPriority = 2;
5369 static constexpr int kOtherPriority = 0;
5370
5371 struct sched_param param = {0};
5372 int sched_policy;
5373 if (enabled) {
5374 sched_policy = SCHED_FIFO;
5375 param.sched_priority = kFifoPriority;
5376 } else {
5377 sched_policy = SCHED_OTHER;
5378 param.sched_priority = kOtherPriority;
5379 }
5380
5381 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5382 return -errno;
5383 }
5384 return NO_ERROR;
5385}
5386
chaviw93df2ea2019-04-30 16:45:12 -07005387const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5388 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5389 if (displayToken) {
5390 return getDisplayDeviceLocked(displayToken);
5391 }
5392 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5393 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005394 return getDisplayByLayerStack(displayOrLayerStack);
5395}
5396
5397const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005398 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005399 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005400 return display;
5401 }
5402 }
5403 return nullptr;
5404}
5405
5406status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5407 sp<GraphicBuffer>* outBuffer) {
5408 sp<DisplayDevice> display;
5409 uint32_t width;
5410 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005411 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005412 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005413 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005414 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5415 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005416 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005417 }
5418
5419 width = uint32_t(display->getViewport().width());
5420 height = uint32_t(display->getViewport().height());
5421
Dominik Laskowski718f9602019-11-09 20:01:35 -08005422 const auto orientation = display->getOrientation();
5423 captureOrientation = ui::Transform::toRotationFlags(orientation);
5424
5425 switch (captureOrientation) {
5426 case ui::Transform::ROT_90:
5427 captureOrientation = ui::Transform::ROT_270;
5428 break;
5429
5430 case ui::Transform::ROT_270:
5431 captureOrientation = ui::Transform::ROT_90;
5432 break;
5433
5434 case ui::Transform::ROT_INVALID:
5435 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5436 captureOrientation = ui::Transform::ROT_0;
5437 break;
5438
5439 default:
5440 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005441 }
chaviw93df2ea2019-04-30 16:45:12 -07005442 *outDataspace =
5443 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5444 }
5445
5446 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5447 false /* captureSecureLayers */);
5448
5449 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5450 std::placeholders::_1);
5451 bool ignored = false;
5452 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5453 false /* useIdentityTransform */,
5454 ignored /* outCapturedSecureLayers */);
5455}
5456
Robert Carr866455f2019-04-02 16:28:26 -07005457status_t SurfaceFlinger::captureLayers(
5458 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5459 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5460 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5461 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005462 ATRACE_CALL();
5463
5464 class LayerRenderArea : public RenderArea {
5465 public:
Robert Carr578038f2018-03-09 12:25:24 -08005466 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005467 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005468 bool childrenOnly, const Rect& displayViewport)
5469 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005470 mLayer(layer),
5471 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005472 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005473 mFlinger(flinger),
5474 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005475 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005476 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005477 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005478 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005479 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005480 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005481 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005482 }
chaviwa76b2712017-09-20 12:02:26 -07005483 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005484 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005485 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005486 Rect getSourceCrop() const override {
5487 if (mCrop.isEmpty()) {
5488 return getBounds();
5489 } else {
5490 return mCrop;
5491 }
5492 }
Robert Carr578038f2018-03-09 12:25:24 -08005493 class ReparentForDrawing {
5494 public:
5495 const sp<Layer>& oldParent;
5496 const sp<Layer>& newParent;
5497
Vishnu Nair4351ad52019-02-11 14:13:02 -08005498 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5499 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005500 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005501 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005502 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5503 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005504 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005505 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005506 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005507 };
5508
5509 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005510 const Rect sourceCrop = getSourceCrop();
5511 // no need to check rotation because there is none
5512 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5513 sourceCrop.height() != getReqHeight();
5514
Robert Carr578038f2018-03-09 12:25:24 -08005515 if (!mChildrenOnly) {
5516 mTransform = mLayer->getTransform().inverse();
5517 drawLayers();
5518 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005519 uint32_t w = static_cast<uint32_t>(getWidth());
5520 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005521 // In the "childrenOnly" case we reparent the children to a screenshot
5522 // layer which has no properties set and which does not draw.
5523 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005524 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5525 "Screenshot Parent"s, w, h, 0,
5526 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005527
Vishnu Nair4351ad52019-02-11 14:13:02 -08005528 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005529 drawLayers();
5530 }
5531 }
chaviwa76b2712017-09-20 12:02:26 -07005532
chaviwa76b2712017-09-20 12:02:26 -07005533 private:
chaviw7206d492017-11-10 16:16:12 -08005534 const sp<Layer> mLayer;
5535 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005536
Peiyong Linefefaac2018-08-17 12:27:51 -07005537 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005538 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005539
5540 SurfaceFlinger* mFlinger;
5541 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005542 };
5543
Robert Carrc0df3122019-04-11 13:18:21 -07005544 int reqWidth = 0;
5545 int reqHeight = 0;
5546 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005547 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005548 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005549 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005550 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005551 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005552
Alec Mouri9a02eda2020-04-21 17:39:34 -07005553 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005554 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5555 ALOGE("captureLayers called with an invalid or removed parent");
5556 return NAME_NOT_FOUND;
5557 }
5558
5559 const int uid = IPCThreadState::self()->getCallingUid();
5560 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5561 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5562 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5563 return PERMISSION_DENIED;
5564 }
5565
Vishnu Nairefc42e22019-12-03 17:36:12 -08005566 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005567 if (sourceCrop.width() <= 0) {
5568 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005569 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005570 }
5571
5572 if (sourceCrop.height() <= 0) {
5573 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005574 crop.bottom = parentSourceBounds.getHeight();
5575 }
5576
5577 if (crop.isEmpty() || frameScale <= 0.0f) {
5578 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5579 // crop was not specified, or an invalid frame scale was provided.
5580 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005581 }
5582 reqWidth = crop.width() * frameScale;
5583 reqHeight = crop.height() * frameScale;
5584
5585 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005586 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005587 if (excludeLayer != nullptr) {
5588 excludeLayers.emplace(excludeLayer);
5589 } else {
5590 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5591 return NAME_NOT_FOUND;
5592 }
5593 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005594
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005595 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005596 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005597 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005598 }
5599
5600 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005601 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005602
Chia-I Wu20261cb2018-08-23 12:55:44 -07005603 // really small crop or frameScale
5604 if (reqWidth <= 0) {
5605 reqWidth = 1;
5606 }
5607 if (reqHeight <= 0) {
5608 reqHeight = 1;
5609 }
5610
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005611 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5612 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005613 auto traverseLayers = [parent, childrenOnly,
5614 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005615 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5616 if (!layer->isVisible()) {
5617 return;
Robert Carr578038f2018-03-09 12:25:24 -08005618 } else if (childrenOnly && layer == parent.get()) {
5619 return;
chaviwa76b2712017-09-20 12:02:26 -07005620 }
Robert Carr866455f2019-04-02 16:28:26 -07005621
5622 sp<Layer> p = layer;
5623 while (p != nullptr) {
5624 if (excludeLayers.count(p) != 0) {
5625 return;
5626 }
5627 p = p->getParent();
5628 }
5629
chaviwa76b2712017-09-20 12:02:26 -07005630 visitor(layer);
5631 });
5632 };
Robert Carr108b2c72019-04-02 16:32:58 -07005633
5634 bool outCapturedSecureLayers = false;
5635 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5636 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005637}
5638
5639status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5640 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005641 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005642 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005643 bool useIdentityTransform,
5644 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005645 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005646
Peiyong Lin0e003c92018-09-17 11:09:51 -07005647 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005648 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5649 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005650 *outBuffer =
5651 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5652 static_cast<android_pixel_format>(reqPixelFormat), 1,
5653 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005654
Robert Carr108b2c72019-04-02 16:32:58 -07005655 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005656 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005657}
5658
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005659status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5660 TraverseLayersFunction traverseLayers,
5661 const sp<GraphicBuffer>& buffer,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005662 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005663 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005664 const int uid = IPCThreadState::self()->getCallingUid();
5665 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5666
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005667 status_t result;
5668 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005669
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005670 do {
5671 std::tie(result, syncFd) =
5672 schedule([&] {
5673 if (mRefreshPending) {
5674 ATRACE_NAME("Skipping screenshot for now");
5675 return std::make_pair(EAGAIN, -1);
5676 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005677
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005678 status_t result = NO_ERROR;
5679 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005680
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005681 Mutex::Autolock lock(mStateLock);
5682 renderArea.render([&] {
5683 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5684 useIdentityTransform, forSystem, &fd,
5685 regionSampling, outCapturedSecureLayers);
5686 });
5687
5688 return std::make_pair(result, fd);
5689 }).get();
5690 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005691
5692 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005693 sync_wait(syncFd, -1);
5694 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005695 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005696
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005697 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005698}
5699
chaviwa76b2712017-09-20 12:02:26 -07005700void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005701 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005702 ANativeWindowBuffer* buffer, bool useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005703 bool regionSampling, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005704 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005705
chaviwa76b2712017-09-20 12:02:26 -07005706 const auto reqWidth = renderArea.getReqWidth();
5707 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005708 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005709 const auto transform = renderArea.getTransform();
5710 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005711 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005712
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005713 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005714 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005715
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005716 // assume that bounds are never offset, and that they are the same as the
5717 // buffer bounds.
5718 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005719 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005720 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005721
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005722 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5723 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005724
chaviw50da5042018-04-09 13:49:37 -07005725 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005726
Vishnu Nair9b079a22020-01-21 14:36:08 -08005727 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005728 fillLayer.source.buffer.buffer = nullptr;
5729 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005730 fillLayer.geometry.boundaries =
5731 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005732 fillLayer.alpha = half(alpha);
5733 clientCompositionLayers.push_back(fillLayer);
5734
Yichi Chen40773d92020-04-01 10:10:18 +08005735 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005736 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005737 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005738 const bool supportProtectedContent = false;
5739 Region clip(renderArea.getBounds());
5740 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5741 clip,
5742 useIdentityTransform,
Alec Mouri5a6d8572020-03-23 23:56:15 -07005743 layer->needsFilteringForScreenshots(renderArea.getDisplayDevice(), transform) ||
5744 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005745 renderArea.isSecure(),
5746 supportProtectedContent,
5747 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005748 displayViewport,
5749 clientCompositionDisplay.outputDataspace,
5750 true, /* realContentIsVisible */
5751 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005752 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005753 std::vector<compositionengine::LayerFE::LayerSettings> results =
5754 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005755 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005756 for (auto& settings : results) {
5757 settings.geometry.positionTransform =
5758 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupinf11eba52020-04-20 18:42:31 -07005759 // There's no need to process blurs when we're executing region sampling,
5760 // we're just trying to understand what we're drawing, and doing so without
5761 // blurs is already a pretty good approximation.
5762 if (regionSampling) {
5763 settings.backgroundBlurRadius = 0;
5764 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005765 }
Yichi Chen40773d92020-04-01 10:10:18 +08005766 clientCompositionLayers.insert(clientCompositionLayers.end(),
5767 std::make_move_iterator(results.begin()),
5768 std::make_move_iterator(results.end()));
5769 renderedLayers.push_back(layer);
5770 }
chaviwa76b2712017-09-20 12:02:26 -07005771 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005772
Yichi Chen40773d92020-04-01 10:10:18 +08005773 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5774 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005775 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005776 clientCompositionLayerPointers.begin(),
5777 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005778
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005779 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005780 // Use an empty fence for the buffer fence, since we just created the buffer so
5781 // there is no need for synchronization with the GPU.
5782 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005783 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005784 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005785 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005786 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005787
5788 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005789
5790 if (*outSyncFd >= 0) {
5791 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5792 for (auto* layer : renderedLayers) {
5793 layer->onLayerDisplayed(releaseFence);
5794 }
5795 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005796}
5797
chaviwa76b2712017-09-20 12:02:26 -07005798status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5799 TraverseLayersFunction traverseLayers,
5800 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005801 bool useIdentityTransform, bool forSystem,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005802 int* outSyncFd, bool regionSampling,
5803 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005804 ATRACE_CALL();
5805
chaviwa76b2712017-09-20 12:02:26 -07005806 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005807 outCapturedSecureLayers =
5808 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005809 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005810
Robert Carr03480e22018-01-04 16:02:06 -08005811 // We allow the system server to take screenshots of secure layers for
5812 // use in situations like the Screen-rotation animation and place
5813 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005814 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005815 ALOGW("FB is protected: PERMISSION_DENIED");
5816 return PERMISSION_DENIED;
5817 }
Lucas Dupinf11eba52020-04-20 18:42:31 -07005818 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5819 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005820 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005821}
5822
chaviw95ef3c42019-02-14 10:55:09 -08005823void SurfaceFlinger::setInputWindowsFinished() {
5824 Mutex::Autolock _l(mStateLock);
5825
5826 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005827
chaviw95ef3c42019-02-14 10:55:09 -08005828 mTransactionCV.broadcast();
5829}
chaviw5f21a5e2019-02-14 10:00:34 -08005830
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005831// ---------------------------------------------------------------------------
5832
Edgar Arriaga844fa672020-01-16 14:21:42 -08005833void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5834 layersSortedByZ.traverse(visitor);
5835}
5836
Dan Stoza412903f2017-04-27 13:42:17 -07005837void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5838 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005839}
5840
Dan Stoza412903f2017-04-27 13:42:17 -07005841void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5842 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005843}
5844
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005845void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005846 const LayerVector::Visitor& visitor) {
5847 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005848 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005849 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005850 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005851 continue;
5852 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005853 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005854 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005855 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005856 return;
5857 }
chaviwa76b2712017-09-20 12:02:26 -07005858 if (!layer->isVisible()) {
5859 return;
5860 }
5861 visitor(layer);
5862 });
5863 }
5864}
5865
Steven Thomasd4071902020-03-24 16:02:53 -07005866status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5867 const sp<DisplayDevice>& display,
5868 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005869 Mutex::Autolock lock(mStateLock);
5870
Steven Thomasd4071902020-03-24 16:02:53 -07005871 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5872 "Can only set override policy on the primary display");
5873 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5874
Dominik Laskowski22488f62019-03-28 09:53:04 -07005875 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005876 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5877 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5878 // it should go thru setDesiredActiveConfig, similar to primary display.
5879 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5880 const auto displayId = display->getId();
5881 LOG_ALWAYS_FATAL_IF(!displayId);
5882
Peiyong Line9d809e2020-04-14 13:10:48 -07005883 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005884 constraints.desiredTimeNanos = systemTime();
5885 constraints.seamlessRequired = false;
5886
Peiyong Line9d809e2020-04-14 13:10:48 -07005887 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005888 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5889 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005890 constraints, &timeline) < 0) {
5891 return BAD_VALUE;
5892 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005893 if (timeline.refreshRequired) {
5894 repaintEverythingForHWC();
5895 }
5896
Steven Thomasd4071902020-03-24 16:02:53 -07005897 display->setActiveConfig(policy->defaultConfig);
5898 const nsecs_t vsyncPeriod = getHwComposer()
5899 .getConfigs(*displayId)[policy->defaultConfig.value()]
5900 ->getVsyncPeriod();
5901 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5902 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005903 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005904 }
5905
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005906 if (mDebugDisplayConfigSetByBackdoor) {
5907 // ignore this request as config is overridden by backdoor
5908 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005909 }
5910
Steven Thomasd4071902020-03-24 16:02:53 -07005911 status_t setPolicyResult = overridePolicy
5912 ? mRefreshRateConfigs->setOverridePolicy(policy)
5913 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5914 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005915 return BAD_VALUE;
5916 }
Steven Thomasd4071902020-03-24 16:02:53 -07005917 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005918 return NO_ERROR;
5919 }
Steven Thomasd4071902020-03-24 16:02:53 -07005920 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005921
5922 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
Steven Thomasd4071902020-03-24 16:02:53 -07005923 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
5924 currentPolicy.maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005925
5926 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5927 // that listeners that care about a change in allowed configs can get the notification.
5928 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005929 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005930 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5931 .getVsyncPeriod();
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005932 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005933 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005934
Ana Krulec3f6a2062020-01-23 15:48:01 -08005935 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005936 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005937 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5938 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005939 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005940 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005941 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005942
Ady Abrahamabc27602020-04-08 17:20:29 -07005943 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5944 ALOGV("switching to Scheduler preferred config %d",
5945 preferredRefreshRate.getConfigId().value());
5946 setDesiredActiveConfig(
5947 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005948 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005949 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5950 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005951 }
5952
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005953 return NO_ERROR;
5954}
5955
Ana Krulec0782b882019-10-15 17:34:54 -07005956status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005957 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005958 float maxRefreshRate) {
5959 ATRACE_CALL();
5960
5961 if (!displayToken) {
5962 return BAD_VALUE;
5963 }
5964
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005965 auto future = schedule([=]() -> status_t {
Ana Krulec234bb162019-11-10 22:55:55 +01005966 const auto display = getDisplayDeviceLocked(displayToken);
5967 if (!display) {
5968 ALOGE("Attempt to set desired display configs for invalid display token %p",
5969 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005970 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01005971 } else if (display->isVirtual()) {
5972 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005973 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01005974 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005975 using Policy = scheduler::RefreshRateConfigs::Policy;
5976 const Policy policy{HwcConfigIndexType(defaultConfig), minRefreshRate, maxRefreshRate};
5977 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005978
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005979 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
5980 }
5981 });
5982
5983 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01005984}
5985
5986status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005987 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005988 float* outMinRefreshRate,
5989 float* outMaxRefreshRate) {
5990 ATRACE_CALL();
5991
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005992 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005993 return BAD_VALUE;
5994 }
5995
5996 Mutex::Autolock lock(mStateLock);
5997 const auto display = getDisplayDeviceLocked(displayToken);
5998 if (!display) {
5999 return NAME_NOT_FOUND;
6000 }
6001
6002 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006003 scheduler::RefreshRateConfigs::Policy policy =
6004 mRefreshRateConfigs->getDisplayManagerPolicy();
6005 *outDefaultConfig = policy.defaultConfig.value();
6006 *outMinRefreshRate = policy.minRefreshRate;
6007 *outMaxRefreshRate = policy.maxRefreshRate;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006008 return NO_ERROR;
6009 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006010 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006011 } else {
6012 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006013 LOG_FATAL_IF(!displayId);
6014
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006015 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6016 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6017 *outMinRefreshRate = 1e9f / vsyncPeriod;
6018 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6019 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006020 }
Ana Krulec0782b882019-10-15 17:34:54 -07006021}
6022
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006023void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006024 mFlinger->setInputWindowsFinished();
6025}
6026
Alec Mouri9a02eda2020-04-21 17:39:34 -07006027wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6028 Mutex::Autolock _l(mStateLock);
6029 return fromHandleLocked(handle);
6030}
6031
6032wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006033 BBinder* b = nullptr;
6034 if (handle) {
6035 b = handle->localBinder();
6036 }
Robert Carrc0df3122019-04-11 13:18:21 -07006037 if (b == nullptr) {
6038 return nullptr;
6039 }
6040 auto it = mLayersByLocalBinderToken.find(b);
6041 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006042 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006043 }
6044 return nullptr;
6045}
6046
Dominik Laskowski75848362019-11-11 17:57:20 -08006047void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006048 mNumLayers++;
6049 mScheduler->registerLayer(layer);
6050}
6051
6052void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6053 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006054 removeFromOffscreenLayers(layer);
6055}
6056
6057// WARNING: ONLY CALL THIS FROM LAYER DTOR
6058// Here we add children in the current state to offscreen layers and remove the
6059// layer itself from the offscreen layer list. Since
6060// this is the dtor, it is safe to access the current state. This keeps us
6061// from dangling children layers such that they are not reachable from the
6062// Drawing state nor the offscreen layer list
6063// See b/141111965
6064void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6065 for (auto& child : layer->getCurrentChildren()) {
6066 mOffscreenLayers.emplace(child.get());
6067 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006068 mOffscreenLayers.erase(layer);
6069}
6070
Alec Mouri4545a8a2019-08-08 20:05:32 -07006071void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6072 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6073}
6074
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006075status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6076 float lightPosY, float lightPosZ,
6077 float lightRadius) {
6078 Mutex::Autolock _l(mStateLock);
6079 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6080 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6081 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6082 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6083 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6084
6085 // these values are overridden when calculating the shadow settings for a layer.
6086 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6087 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006088 return NO_ERROR;
6089}
6090
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006091const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6092 const {
6093 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6094 // on the work to remove the table in that bug rather than adding more to
6095 // it.
6096 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6097 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6098 // supported, and exposed via the
6099 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6100 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6101 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6102 };
6103 return genericLayerMetadataKeyMap;
6104}
6105
Steven Thomas62a4cf82020-01-31 12:04:03 -08006106status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6107 int8_t compatibility) {
6108 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6109 return BAD_VALUE;
6110 }
6111
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006112 static_cast<void>(schedule([=]() NO_THREAD_SAFETY_ANALYSIS {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006113 Mutex::Autolock lock(mStateLock);
6114 if (authenticateSurfaceTextureLocked(surface)) {
6115 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6116 if (layer->setFrameRate(
6117 Layer::FrameRate(frameRate,
6118 Layer::FrameRate::convertCompatibility(compatibility)))) {
6119 setTransactionFlags(eTraversalNeeded);
6120 }
6121 } else {
6122 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6123 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006124 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006125 return NO_ERROR;
6126 }));
6127
Steven Thomas62a4cf82020-01-31 12:04:03 -08006128 return NO_ERROR;
6129}
6130
Steven Thomasd4071902020-03-24 16:02:53 -07006131status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6132 if (!outToken) {
6133 return BAD_VALUE;
6134 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006135
6136 auto future = schedule([this] {
6137 status_t result = NO_ERROR;
6138 sp<IBinder> token;
6139
Steven Thomasd4071902020-03-24 16:02:53 -07006140 if (mFrameRateFlexibilityTokenCount == 0) {
6141 // |mStateLock| not needed as we are on the main thread
6142 const auto display = getDefaultDisplayDeviceLocked();
6143
6144 // This is a little racy, but not in a way that hurts anything. As we grab the
6145 // defaultConfig from the display manager policy, we could be setting a new display
6146 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6147 // matter for the override policy though, since we set allowGroupSwitching to true, so
6148 // it's not a problem.
6149 scheduler::RefreshRateConfigs::Policy overridePolicy;
6150 overridePolicy.defaultConfig =
6151 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6152 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006153 constexpr bool kOverridePolicy = true;
6154 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006155 }
6156
6157 if (result == NO_ERROR) {
6158 mFrameRateFlexibilityTokenCount++;
6159 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6160 // below, is something to consider carefully. The lifetime of the
6161 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6162 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6163 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6164 // in this case, for two reasons:
6165 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6166 // the program exits is via a crash. So we won't have a situation where the
6167 // SurfaceFlinger object is dead but the process is still up.
6168 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6169 // if condition 1 were changed, the problem would only show up when running CTS tests,
6170 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006171 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006172 [this]() { onFrameRateFlexibilityTokenReleased(); });
6173 ALOGD("Frame rate flexibility token acquired. count=%d",
6174 mFrameRateFlexibilityTokenCount);
6175 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006176
6177 return std::make_pair(result, token);
6178 });
6179
6180 status_t result;
6181 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006182 return result;
6183}
6184
6185void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006186 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006187 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6188 "Failed tracking frame rate flexibility tokens");
6189 mFrameRateFlexibilityTokenCount--;
6190 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6191 if (mFrameRateFlexibilityTokenCount == 0) {
6192 // |mStateLock| not needed as we are on the main thread
6193 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006194 constexpr bool kOverridePolicy = true;
6195 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006196 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6197 }
6198 }));
6199}
6200
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006201} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006202
Mathias Agopian3f844832013-08-07 21:24:32 -07006203#if defined(__gl_h_)
6204#error "don't include gl/gl.h in this file"
6205#endif
6206
6207#if defined(__gl2_h_)
6208#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006209#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006210
6211// TODO(b/129481165): remove the #pragma below and fix conversion issues
6212#pragma clang diagnostic pop // ignored "-Wconversion"