blob: 37620339428b70120e4c2c1786576f77b3babaa2 [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"
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020#pragma clang diagnostic ignored "-Wextra"
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080021
Alec Mourie7d1d4a2019-02-05 01:13:46 +000022//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080023#define ATRACE_TAG ATRACE_TAG_GRAPHICS
24
Alec Mouri5f487d42020-02-06 09:26:19 -080025#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080026
Dominik Laskowski298b08e2022-02-15 13:45:02 -080027#include <android-base/parseint.h>
Ana Krulecb9afd792020-06-11 13:16:15 -070028#include <android-base/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080029#include <android-base/stringprintf.h>
30#include <android-base/strings.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080031#include <android/configuration.h>
Huihong Luo6fac5232021-11-22 16:05:23 -080032#include <android/gui/IDisplayEventConnection.h>
Huihong Luoa79ddf42022-02-17 00:01:38 -080033#include <android/gui/StaticDisplayInfo.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080034#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
35#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
36#include <android/hardware/configstore/1.1/types.h>
Lais Andrade3a6e47d2020-04-02 11:20:16 +010037#include <android/hardware/power/Boost.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080038#include <android/native_window.h>
Chris Ye0783e992020-06-02 21:34:49 -070039#include <android/os/IInputFlinger.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070040#include <binder/IPCThreadState.h>
41#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070042#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070043#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080044#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070045#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070046#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070047#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080048#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080049#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070050#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070051#include <compositionengine/impl/OutputCompositionState.h>
John Reckdb1a16b2021-07-09 13:05:52 -040052#include <compositionengine/impl/OutputLayerCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080053#include <configstore/Utils.h>
54#include <cutils/compiler.h>
55#include <cutils/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080056#include <ftl/fake_guard.h>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080057#include <ftl/future.h>
Dominik Laskowski9f410f02022-01-08 16:22:46 -080058#include <ftl/small_map.h>
Huihong Luo3bdef862022-03-03 11:57:19 -080059#include <gui/AidlStatusUtil.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070060#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070061#include <gui/DebugEGLImageTracker.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080062#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080063#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080064#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080065#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080066#include <gui/Surface.h>
rnlee60f46b52021-05-21 15:14:07 -070067#include <gui/TraceUtils.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000068#include <hidl/ServiceManagement.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080069#include <layerproto/LayerProtoParser.h>
70#include <log/log.h>
71#include <private/android_filesystem_config.h>
72#include <private/gui/SyncFeatures.h>
Wei Wang976a6452021-06-11 15:26:00 -070073#include <processgroup/processgroup.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070074#include <renderengine/RenderEngine.h>
Vishnu Nairdbbe3852022-01-12 20:22:11 -080075#include <renderengine/impl/ExternalTexture.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080076#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <ui/ColorSpace.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070078#include <ui/DataspaceUtils.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070079#include <ui/DebugUtils.h>
Marin Shalamanov045b7002021-01-07 16:56:24 +010080#include <ui/DisplayId.h>
Marin Shalamanova7fe3042021-01-29 21:02:08 +010081#include <ui/DisplayMode.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070082#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080083#include <ui/DisplayState.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010084#include <ui/DynamicDisplayInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070085#include <ui/GraphicBufferAllocator.h>
86#include <ui/PixelFormat.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010087#include <ui/StaticDisplayInfo.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070089#include <utils/String16.h>
90#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070091#include <utils/Timers.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070092#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093
Alec Mouri5f487d42020-02-06 09:26:19 -080094#include <algorithm>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080095#include <cerrno>
Alec Mouri5f487d42020-02-06 09:26:19 -080096#include <cinttypes>
97#include <cmath>
98#include <cstdint>
99#include <functional>
Xiang Wang839fe5b2022-04-04 17:39:38 +0000100#include <memory>
Alec Mouri5f487d42020-02-06 09:26:19 -0800101#include <mutex>
102#include <optional>
Michael Wright44753b12020-07-08 13:48:11 +0100103#include <type_traits>
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105
Alec Mouriff793872022-01-13 17:45:06 -0800106#include <ui/DisplayIdentification.h>
Vishnu Nair03ccbd62021-12-01 17:21:16 -0800107#include "BackgroundExecutor.h"
Robert Carr578038f2018-03-09 12:25:24 -0800108#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -0700109#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -0700110#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200111#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200112#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800113#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800114#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700115#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700116#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700117#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100118#include "DisplayHardware/Hal.h"
Xiang Wang839fe5b2022-04-04 17:39:38 +0000119#include "DisplayHardware/PowerAdvisor.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700120#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200121#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800122#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700123#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700124#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800125#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700126#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700127#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400128#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800129#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500130#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200131#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800132#include "LayerVector.h"
133#include "MonitoredProducer.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800134#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800135#include "NativeWindowSurface.h"
136#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700137#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700138#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700139#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700140#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700141#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700142#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700143#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800144#include "StartPropertySetThread.h"
145#include "SurfaceFlingerProperties.h"
146#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800147#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200148#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500149#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800150
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500151#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500152#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
153
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700154#undef NO_THREAD_SAFETY_ANALYSIS
155#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800156 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500157
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800158namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700159
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700160using namespace std::string_literals;
161
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800162using namespace hardware::configstore;
163using namespace hardware::configstore::V1_0;
164using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800165
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800166using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
167using aidl::android::hardware::graphics::composer3::Capability;
168using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800169using CompositionStrategyPredictionState = android::compositionengine::impl::
170 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800171
Yiwei Zhang5434a782018-12-05 18:06:32 -0800172using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700173using gui::DisplayInfo;
Huihong Luo6fac5232021-11-22 16:05:23 -0800174using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500175using gui::IWindowInfosListener;
chaviw98318de2021-05-19 16:45:23 -0500176using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800177using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700178using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700179using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800180using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700181using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900182
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800183using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
184
Peiyong Line9d809e2020-04-14 13:10:48 -0700185namespace hal = android::hardware::graphics::composer::hal;
186
Steven Thomasb02664d2017-07-26 18:48:28 -0700187namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700188
189#pragma clang diagnostic push
190#pragma clang diagnostic error "-Wswitch-enum"
191
192bool isWideColorMode(const ColorMode colorMode) {
193 switch (colorMode) {
194 case ColorMode::DISPLAY_P3:
195 case ColorMode::ADOBE_RGB:
196 case ColorMode::DCI_P3:
197 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700198 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700199 case ColorMode::BT2100_PQ:
200 case ColorMode::BT2100_HLG:
201 return true;
202 case ColorMode::NATIVE:
203 case ColorMode::STANDARD_BT601_625:
204 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
205 case ColorMode::STANDARD_BT601_525:
206 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
207 case ColorMode::STANDARD_BT709:
208 case ColorMode::SRGB:
209 return false;
210 }
211 return false;
212}
213
214#pragma clang diagnostic pop
215
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100216// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700217constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800218
219float getDensityFromProperty(const char* property, bool required) {
220 char value[PROPERTY_VALUE_MAX];
221 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
222 if (!density && required) {
223 ALOGE("%s must be defined as a build property", property);
224 return FALLBACK_DENSITY;
225 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700226 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800227}
228
Peiyong Lin9d846a52018-11-05 13:18:20 -0800229// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
230bool validateCompositionDataspace(Dataspace dataspace) {
231 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
232}
233
ramindani32cf0602022-03-02 02:30:29 +0000234std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700235 const auto displayIdleTimerMsKey = [displayId] {
236 std::stringstream ss;
237 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
238 return ss.str();
239 }();
240
ramindani32cf0602022-03-02 02:30:29 +0000241 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
242 if (displayIdleTimerMs > 0) {
243 return std::chrono::milliseconds(displayIdleTimerMs);
244 }
245
246 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
247 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
248 return std::chrono::milliseconds(millis);
249}
250
251bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700252 const auto displaySupportKernelIdleTimerKey = [displayId] {
253 std::stringstream ss;
254 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
255 return ss.str();
256 }();
257
Ady Abraham6d885932021-09-03 18:05:48 -0700258 const auto displaySupportKernelIdleTimer =
259 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000260 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700261}
262
Steven Thomasb02664d2017-07-26 18:48:28 -0700263} // namespace anonymous
264
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265// ---------------------------------------------------------------------------
266
Mathias Agopian99b49842011-06-27 16:05:52 -0700267const String16 sHardwareTest("android.permission.HARDWARE_TEST");
268const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800269const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700270const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400271const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700272const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500273const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000274const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500275
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800276const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700277
278// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700279int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700280bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800281bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800282int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100283uint32_t SurfaceFlinger::maxGraphicsWidth;
284uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600285bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700286bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700287Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
288ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
289Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
290ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000291LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700292
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800293std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
294 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800295 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700296 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800297 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700298 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800299 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700300 return std::string("Enhanced");
301 default:
302 return std::string("Unknown ") +
303 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800304 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800305}
306
Hongwei Wang46213ea2020-12-04 17:17:31 -0800307bool callingThreadHasRotateSurfaceFlingerAccess() {
308 IPCThreadState* ipc = IPCThreadState::self();
309 const int pid = ipc->getCallingPid();
310 const int uid = ipc->getCallingUid();
311 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
312 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
313}
314
Leon Scroggins9a20f722021-12-28 14:43:12 +0000315bool callingThreadHasInternalSystemWindowAccess() {
316 IPCThreadState* ipc = IPCThreadState::self();
317 const int pid = ipc->getCallingPid();
318 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500319 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
320 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000321}
322
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700323SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
324 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800325 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000326 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700327 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800328 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800329 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700330 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700331 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700332 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800333 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700334 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000335 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Dominik Laskowski91f635e2022-01-08 05:46:09 -0800336 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make(*this)) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700337 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700338}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800339
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700340SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800341 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800342
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900343 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700346
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900347 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700348
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900349 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800350
Brian Lindahla13f2d52020-03-05 11:54:17 +0100351 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
352 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
353
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900354 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900355 mDefaultCompositionDataspace =
356 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700357 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
358 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900359 defaultCompositionDataspace = mDefaultCompositionDataspace;
360 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
361 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
362 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
363 wideColorGamutCompositionPixelFormat =
364 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700365
Yichi Chenda901bf2019-06-28 14:58:27 +0800366 mColorSpaceAgnosticDataspace =
367 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
368
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700369 mLayerCachingEnabled = [] {
370 const bool enable =
371 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
372 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
373 }();
374
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900375 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800376
Sundong Ahn85131bd2019-02-18 15:51:53 +0900377 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800378
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800379 // debugging stuff...
380 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700381
Mathias Agopianb4b17302013-03-20 18:36:41 -0700382 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700383 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700384
Alec Mouri5f487d42020-02-06 09:26:19 -0800385 property_get("ro.build.type", value, "user");
386 mIsUserBuild = strcmp(value, "user") == 0;
387
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700388 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000389
390 // DDMS debugging deprecated (b/120782499)
391 property_get("debug.sf.ddms", value, "0");
392 int debugDdms = atoi(value);
393 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700394
Ady Abrahamadb9a992019-09-19 21:21:55 +0000395 property_get("debug.sf.enable_gl_backpressure", value, "0");
396 mPropagateBackpressureClientComposition = atoi(value);
397 ALOGI_IF(mPropagateBackpressureClientComposition,
398 "Enabling backpressure propagation for Client Composition");
399
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800400 property_get("ro.surface_flinger.supports_background_blur", value, "0");
401 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700402 mSupportsBlur = supportsBlurs;
403 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800404 property_get("ro.sf.blurs_are_expensive", value, "0");
405 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800406
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800407 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700408 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
409 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800410 mGraphicBufferProducerListSizeLogThreshold =
411 std::max(static_cast<int>(0.95 *
412 static_cast<double>(mMaxGraphicBufferProducerListSize)),
413 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700414
Dan Stozaec460082018-12-17 15:35:09 -0800415 property_get("debug.sf.luma_sampling", value, "1");
416 mLumaSampling = atoi(value);
417
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800418 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800419 mDisableClientCompositionCache = atoi(value);
420
Vishnu Nair3539d812022-02-26 09:20:17 -0800421 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800422 mPredictCompositionStrategy = atoi(value);
423
Romain Guy11d63f42017-07-20 12:47:14 -0700424 // We should be reading 'persist.sys.sf.color_saturation' here
425 // but since /data may be encrypted, we need to wait until after vold
426 // comes online to attempt to read the property. The property is
427 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800428
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700429 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800430 // Without the override SurfaceFlinger cannot connect to HIDL
431 // services that are not listed in the manifests. Considered
432 // deriving the setting from the set service name, but it
433 // would be brittle if the name that's not 'default' is used
434 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700435 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000436 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800437 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800438
Ady Abraham29d0da32020-07-16 18:39:33 -0700439 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400440
Dominik Laskowski46471e62022-01-14 15:34:03 -0800441 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
442 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800443 }
John Reck49d9ad32022-02-23 19:03:31 -0500444
445 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
ramindani4d48f902021-09-20 21:07:45 +0000446}
447
448LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
449 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
450 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000451 }
Ady Abraham9dada822022-02-03 10:26:59 -0800452
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000453 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800454 return LatchUnsignaledConfig::AutoSingleLayer;
455 }
456
457 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800458}
459
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700460SurfaceFlinger::~SurfaceFlinger() = default;
461
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700462void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800463 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700464 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800465
Dominik Laskowski756b7892021-08-04 12:53:59 -0700466 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000467 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800468
Andy McFadden13a082e2012-08-24 10:16:42 -0700469 // restore initial conditions (default device unblank, etc)
470 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800471
472 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700473 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800474}
475
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700476void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700477 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800478}
479
480sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700481 const sp<Client> client = new Client(this);
482 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800483}
484
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700485sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700486 // onTransact already checks for some permissions, but adding an additional check here.
487 // This is to ensure that only system and graphics can request to create a secure
488 // display. Secure displays can show secure content so we add an additional restriction on it.
489 const int uid = IPCThreadState::self()->getCallingUid();
490 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
491 ALOGE("Only privileged processes can create a secure display");
492 return nullptr;
493 }
494
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 class DisplayToken : public BBinder {
496 sp<SurfaceFlinger> flinger;
497 virtual ~DisplayToken() {
498 // no more references, this display must be terminated
499 Mutex::Autolock _l(flinger->mStateLock);
500 flinger->mCurrentState.displays.removeItem(this);
501 flinger->setTransactionFlags(eDisplayTransactionNeeded);
502 }
503 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700504 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505 : flinger(flinger) {
506 }
507 };
508
509 sp<BBinder> token = new DisplayToken(this);
510
511 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700512 // Display ID is assigned when virtual display is allocated by HWC.
513 DisplayDeviceState state;
514 state.isSecure = secure;
515 state.displayName = displayName;
516 mCurrentState.displays.add(token, state);
517 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700518 return token;
519}
520
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700521void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700522 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700523
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700524 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700525 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800526 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700527 return;
528 }
529
Dominik Laskowski075d3172018-05-24 15:50:06 -0700530 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700531 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800532 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700533 return;
534 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700535 mInterceptor->saveDisplayDeletion(state.sequenceId);
536 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700537 setTransactionFlags(eDisplayTransactionNeeded);
538}
539
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800540void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
541 auto& generator = mVirtualDisplayIdGenerators.hal;
542 if (!generator && enable) {
543 ALOGI("Enabling HAL virtual displays");
544 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
545 } else if (generator && !enable) {
546 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
547 generator.reset();
548 }
549}
550
Dominik Laskowski263eec42021-07-21 23:13:24 -0700551VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
552 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800553 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
554 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700555 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800556 return *id;
557 }
558
559 generator->releaseId(*id);
560 } else {
561 ALOGW("%s: Exhausted HAL virtual displays", __func__);
562 }
563
564 ALOGW("%s: Falling back to GPU virtual display", __func__);
565 }
566
567 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
568 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
569 return *id;
570}
571
572void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
573 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
574 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
575 generator->releaseId(*id);
576 }
577 return;
578 }
579
580 const auto id = GpuVirtualDisplayId::tryCast(displayId);
581 LOG_ALWAYS_FATAL_IF(!id);
582 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
583}
584
Ady Abrahamed3290f2021-05-17 15:12:14 -0700585std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800586 std::vector<PhysicalDisplayId> displayIds;
587 displayIds.reserve(mPhysicalDisplayTokens.size());
Ady Abraham2a0066d2021-07-15 20:16:58 -0700588 const auto defaultDisplayId = [this]() REQUIRES(mStateLock) {
589 if (const auto display = getDefaultDisplayDeviceLocked()) {
590 return display->getPhysicalId();
591 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700592
Ady Abraham2a0066d2021-07-15 20:16:58 -0700593 // fallback to the internal display id if the active display is unknown
594 return getInternalDisplayIdLocked();
595 }();
596 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800597
598 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700599 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200600 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800601 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700602 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700603
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800604 return displayIds;
605}
606
Vishnu Nair8c8db542021-09-17 19:51:45 -0700607status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
608 Mutex::Autolock lock(mStateLock);
609 *id = getInternalDisplayIdLocked();
610 return NO_ERROR;
611}
612
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800613sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
614 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200615 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700616}
617
Ady Abraham37965d42018-11-01 13:43:32 -0700618status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
619 if (!outGetColorManagement) {
620 return BAD_VALUE;
621 }
622 *outGetColorManagement = useColorManagement;
623 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700624}
625
Lloyd Pique441d5042018-10-18 16:49:51 -0700626HWComposer& SurfaceFlinger::getHwComposer() const {
627 return mCompositionEngine->getHwComposer();
628}
629
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700630renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
631 return mCompositionEngine->getRenderEngine();
632}
633
Lloyd Pique70d91362018-10-18 16:02:55 -0700634compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
635 return *mCompositionEngine.get();
636}
637
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100638void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700639 if (mBootFinished == true) {
640 ALOGE("Extra call to bootFinished");
641 return;
642 }
643 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700644 if (mStartPropertySetThread->join() != NO_ERROR) {
645 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800646 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700647
648 if (mRenderEnginePrimeCacheFuture.valid()) {
649 mRenderEnginePrimeCacheFuture.get();
650 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800651 const nsecs_t now = systemTime();
652 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000653 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700654
Mikael Pessa90092f42019-08-26 17:22:04 -0700655 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700656 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700657 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700658
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700659 // wait patiently for the window manager death
660 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700661 mWindowManager = defaultServiceManager()->getService(name);
662 if (mWindowManager != 0) {
663 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700664 }
665
666 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700667 // formerly we would just kill the process, but we now ask it to exit so it
668 // can choose where to stop the animation.
669 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700670
671 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
672 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
673 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700674
Denis Hsue70cc6c2020-06-17 10:17:30 +0800675 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
676
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000677 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800678 if (input == nullptr) {
679 ALOGE("Failed to link to input service");
680 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700681 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800682 }
683
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800684 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000685 mPowerAdvisor->onBootFinished();
686 mPowerAdvisor->enablePowerHint(mFlagManager.use_adpf_cpu_hint());
687 if (mPowerAdvisor->usePowerHintSession()) {
Xiang Wang76236e12022-03-22 17:25:30 +0000688 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
689 std::vector<int32_t> tidList;
690 tidList.emplace_back(gettid());
691 if (renderEngineTid.has_value()) {
692 tidList.emplace_back(*renderEngineTid);
693 }
Xiang Wang839fe5b2022-04-04 17:39:38 +0000694 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000695 ALOGW("Cannot start power hint session");
696 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000697 }
698
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800699 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800700
Ady Abraham8a82ba62020-01-17 12:43:17 -0800701 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800702 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800703 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800704 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800705}
706
Dan Stoza436ccf32018-06-21 12:10:12 -0700707uint32_t SurfaceFlinger::getNewTexture() {
708 {
709 std::lock_guard lock(mTexturePoolMutex);
710 if (!mTexturePool.empty()) {
711 uint32_t name = mTexturePool.back();
712 mTexturePool.pop_back();
713 ATRACE_INT("TexturePoolSize", mTexturePool.size());
714 return name;
715 }
716
717 // The pool was too small, so increase it for the future
718 ++mTexturePoolSize;
719 }
720
721 // The pool was empty, so we need to get a new texture name directly using a
722 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700723 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700724 uint32_t name = 0;
725 getRenderEngine().genTextures(1, &name);
726 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700727 };
728 if (std::this_thread::get_id() == mMainThreadId) {
729 return genTextures();
730 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700731 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700732 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700733}
734
Mathias Agopian3f844832013-08-07 21:24:32 -0700735void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700736 std::lock_guard lock(mTexturePoolMutex);
737 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
738 // to actually delete this or not based on mTexturePoolSize
739 mTexturePool.push_back(texture);
740 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700741}
742
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500743static std::optional<renderengine::RenderEngine::RenderEngineType>
744chooseRenderEngineTypeViaSysProp() {
745 char prop[PROPERTY_VALUE_MAX];
746 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
747
748 if (strcmp(prop, "gles") == 0) {
749 return renderengine::RenderEngine::RenderEngineType::GLES;
750 } else if (strcmp(prop, "threaded") == 0) {
751 return renderengine::RenderEngine::RenderEngineType::THREADED;
752 } else if (strcmp(prop, "skiagl") == 0) {
753 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
754 } else if (strcmp(prop, "skiaglthreaded") == 0) {
755 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
756 } else {
757 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
758 return {};
759 }
760}
761
Wei Wangf9b05ee2017-07-19 20:59:39 -0700762// Do not call property_set on main thread which will be blocked by init
763// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700764void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700765 ALOGI( "SurfaceFlinger's main thread ready to run. "
766 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700767 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800768
Steven Thomasb02664d2017-07-26 18:48:28 -0700769 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700770 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800771 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500772 auto builder = renderengine::RenderEngineCreationArgs::Builder()
773 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
774 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
775 .setUseColorManagerment(useColorManagement)
776 .setEnableProtectedContext(enable_protected_contents(false))
777 .setPrecacheToneMapperShaderOnly(false)
778 .setSupportsBackgroundBlur(mSupportsBlur)
779 .setContextPriority(
780 useContextPriority
781 ? renderengine::RenderEngine::ContextPriority::REALTIME
782 : renderengine::RenderEngine::ContextPriority::MEDIUM);
783 if (auto type = chooseRenderEngineTypeViaSysProp()) {
784 builder.setRenderEngineType(type.value());
785 }
786 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700787 mMaxRenderTargetSize =
788 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700789
790 // Set SF main policy after initializing RenderEngine which has its own policy.
791 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
792 ALOGW("Failed to set main task profile");
793 }
794
Alec Mourie4034bb2019-11-19 12:45:54 -0800795 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700796 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800797 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000798 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800799
Ady Abraham9dada822022-02-03 10:26:59 -0800800 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
801
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800802 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
803 enableHalVirtualDisplays(true);
804 }
805
Lloyd Piqueba04e622017-12-14 17:11:26 -0800806 // Process any initial hotplug and resulting display changes.
807 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700808 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700809 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200810 const auto displayId = display->getPhysicalId();
811 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700812 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800813
Mathias Agopian92a979a2012-08-02 18:32:23 -0700814 // initialize our drawing state
815 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700816
Andy McFadden13a082e2012-08-24 10:16:42 -0700817 // set initial conditions (e.g. unblank default device)
818 initializeDisplays();
819
Xiang Wang839fe5b2022-04-04 17:39:38 +0000820 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700821
Steven Thomas137d4bc2019-07-25 16:55:14 -0700822 char primeShaderCache[PROPERTY_VALUE_MAX];
823 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
824 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700825 if (setSchedFifo(false) != NO_ERROR) {
826 ALOGW("Can't set SCHED_OTHER for primeCache");
827 }
828
829 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
830
831 if (setSchedFifo(true) != NO_ERROR) {
832 ALOGW("Can't set SCHED_OTHER for primeCache");
833 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700834 }
Dan Stoza4e637772016-07-28 13:31:51 -0700835
Ady Abrahamed3290f2021-05-17 15:12:14 -0700836 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400837
Wei Wangf9b05ee2017-07-19 20:59:39 -0700838 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700839
840 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800841 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700842 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700843
844 if (mStartPropertySetThread->Start() != NO_ERROR) {
845 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800846 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800847
Dan Stoza9e56aa02015-11-02 13:00:03 -0800848 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700849}
850
Romain Guy11d63f42017-07-20 12:47:14 -0700851void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700852 Mutex::Autolock _l(mStateLock);
853
Romain Guy11d63f42017-07-20 12:47:14 -0700854 char value[PROPERTY_VALUE_MAX];
855
856 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800857 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700858 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800859 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100860
861 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700862 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800863
864 property_get("persist.sys.sf.color_mode", value, "0");
865 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700866}
867
Mathias Agopiana67e4182012-06-19 17:26:12 -0700868void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800869 // Start boot animation service by setting a property mailbox
870 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700871 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800872 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700873 if (mStartPropertySetThread->join() != NO_ERROR) {
874 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800875 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700876}
877
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800878// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800879
Brian Anderson6b376712017-04-04 10:51:39 -0700880status_t SurfaceFlinger::getSupportedFrameTimestamps(
881 std::vector<FrameEvent>* outSupported) const {
882 *outSupported = {
883 FrameEvent::REQUESTED_PRESENT,
884 FrameEvent::ACQUIRE,
885 FrameEvent::LATCH,
886 FrameEvent::FIRST_REFRESH_START,
887 FrameEvent::LAST_REFRESH_START,
888 FrameEvent::GPU_COMPOSITION_DONE,
889 FrameEvent::DEQUEUE_READY,
890 FrameEvent::RELEASE,
891 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800892
893 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
894
Ady Abrahamde549d42022-01-26 19:19:17 -0800895 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700896 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
897 }
898 return NO_ERROR;
899}
900
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800901status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
902 if (!displayToken || !state) {
903 return BAD_VALUE;
904 }
905
906 Mutex::Autolock lock(mStateLock);
907
908 const auto display = getDisplayDeviceLocked(displayToken);
909 if (!display) {
910 return NAME_NOT_FOUND;
911 }
912
913 state->layerStack = display->getLayerStack();
914 state->orientation = display->getOrientation();
915
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200916 const Rect layerStackRect = display->getLayerStackSpaceRect();
917 state->layerStackSpaceRect =
918 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800919
920 return NO_ERROR;
921}
922
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100923status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
924 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800925 if (!displayToken || !info) {
926 return BAD_VALUE;
927 }
928
929 Mutex::Autolock lock(mStateLock);
930
931 const auto display = getDisplayDeviceLocked(displayToken);
932 if (!display) {
933 return NAME_NOT_FOUND;
934 }
935
Dominik Laskowski55c85402020-01-21 16:25:47 -0800936 if (const auto connectionType = display->getConnectionType())
937 info->connectionType = *connectionType;
938 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800939 return INVALID_OPERATION;
940 }
941
942 if (mEmulatedDisplayDensity) {
943 info->density = mEmulatedDisplayDensity;
944 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100945 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800946 ? mInternalDisplayDensity
947 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800948 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700949 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800950
951 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200952 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000953 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800954
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800955 return NO_ERROR;
956}
957
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100958status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
959 ui::DynamicDisplayInfo* info) {
960 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700961 return BAD_VALUE;
962 }
963
Dominik Laskowski22488f62019-03-28 09:53:04 -0700964 Mutex::Autolock lock(mStateLock);
965
Marin Shalamanov5801c942020-12-17 17:00:13 +0100966 const auto display = getDisplayDeviceLocked(displayToken);
967 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700968 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700969 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700970
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700971 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
972 if (!displayId) {
973 return INVALID_OPERATION;
974 }
975
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800976 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700977
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100978 const auto& supportedModes = display->getSupportedModes();
979 info->supportedDisplayModes.clear();
980 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800981
982 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100983 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800984 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700985
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800986 auto [width, height] = mode->getResolution();
987 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700988
ramindani06e518e2022-03-14 18:47:53 +0000989 if (const auto physicalOrientation = display->getPhysicalOrientation();
990 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800991 std::swap(width, height);
992 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700993 }
994
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100995 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800996
Huan Songf7eeb102022-03-28 11:02:38 -0700997 outMode.xDpi = xDpi;
998 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800999
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001000 const nsecs_t period = mode->getVsyncPeriod();
1001 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001002
Ady Abraham8287e852020-08-12 14:44:58 -07001003 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001004 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001005 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1006 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1007 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001008
Andy McFadden91b2ca82014-06-13 14:04:23 -07001009 // This is how far in advance a buffer must be queued for
1010 // presentation at a given time. If you want a buffer to appear
1011 // on the screen at time N, you must submit the buffer before
1012 // (N - presentationDeadline).
1013 //
1014 // Normally it's one full refresh period (to give SF a chance to
1015 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001016 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001017 // composer or panel must be accounted for here.
1018 //
1019 // We add an additional 1ms to allow for processing time and
1020 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001021 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001022
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001023 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001024 }
1025
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001026 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001027 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001028 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001029
Marin Shalamanovb173f752021-02-16 19:38:36 +01001030 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001031 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001032 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001033 info->gameContentTypeSupported =
1034 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001035
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001036 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001037
1038 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001039 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1040 if (const auto modeId = display->translateModeId(*hwcId)) {
1041 info->preferredBootDisplayMode = modeId->value();
1042 }
1043 }
1044 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001045
Dan Stoza7f7da322014-05-02 15:26:25 -07001046 return NO_ERROR;
1047}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001048
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
1050 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001051 return BAD_VALUE;
1052 }
1053
Ady Abrahame90dd522020-12-29 12:08:45 -08001054 *stats = mScheduler->getDisplayStatInfo(systemTime());
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001055 return NO_ERROR;
1056}
1057
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001058void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001059 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001060
1061 if (!info.mode) {
1062 ALOGW("requested display mode is null");
1063 return;
1064 }
1065 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001066 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001067 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001068 return;
1069 }
1070
Ady Abraham690f4612021-07-01 23:24:03 -07001071 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001072 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001073
Alec Mouri754c98a2019-03-18 18:53:42 -07001074 // Start receiving vsync samples now, so that we can detect a period
1075 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001076 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001077 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001078 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001079 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001080
Ady Abraham690f4612021-07-01 23:24:03 -07001081 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001082 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001083 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001084}
1085
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001086status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001087 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001088
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001089 if (!displayToken) {
1090 return BAD_VALUE;
1091 }
Ady Abraham838de062019-02-04 10:24:03 -08001092
Dominik Laskowski756b7892021-08-04 12:53:59 -07001093 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001094 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001095 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001096 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001097 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001098 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001099 }
1100
1101 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001102 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001103 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001104 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001105
1106 const auto mode = display->getMode(DisplayModeId{modeId});
1107 if (!mode) {
1108 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1109 return BAD_VALUE;
1110 }
1111
1112 const auto fps = mode->getFps();
1113 // Keep the old switching type.
1114 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001115 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001116 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1117 allowGroupSwitching,
1118 {fps, fps}};
1119 constexpr bool kOverridePolicy = false;
1120
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001121 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001122 });
1123
1124 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001125}
1126
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001127void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001128 ATRACE_CALL();
1129
Dominik Laskowski22488f62019-03-28 09:53:04 -07001130 const auto display = getDefaultDisplayDeviceLocked();
1131 if (!display) {
1132 return;
1133 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001134
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001135 const auto upcomingModeInfo =
1136 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1137
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001138 if (!upcomingModeInfo.mode) {
1139 // There is no pending mode change. This can happen if the active
1140 // display changed and the mode change happened on a different display.
1141 return;
1142 }
1143
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001144 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001145 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1146 // We need to generate new sequenceId in order to recreate the display (and this
1147 // way the framebuffer).
1148 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001149 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001150 processDisplayChangesLocked();
1151
1152 // processDisplayChangesLocked will update all necessary components so we're done here.
1153 return;
1154 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001155
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001156 // We just created this display so we can call even if we are not on the main thread.
1157 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001158 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001159
Ady Abraham690f4612021-07-01 23:24:03 -07001160 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001161 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001162 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001163
Dominik Laskowski068173d2021-08-11 17:22:59 -07001164 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001165 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001166 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001167}
1168
Ady Abraham690f4612021-07-01 23:24:03 -07001169void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1170 display->clearDesiredActiveModeState();
1171 if (isDisplayActiveLocked(display)) {
1172 mScheduler->setModeChangePending(false);
1173 }
Ady Abraham53852a52019-05-28 18:07:44 -07001174}
1175
Ady Abraham690f4612021-07-01 23:24:03 -07001176void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1177 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1178 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001179 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001180 updatePhaseConfiguration(refreshRate);
1181}
1182
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001183void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001184 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001185
Marin Shalamanovdd594312021-11-09 16:37:37 +01001186 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1187
Ady Abraham690f4612021-07-01 23:24:03 -07001188 for (const auto& iter : mDisplays) {
1189 const auto& display = iter.second;
1190 if (!display || !display->isInternal()) {
1191 continue;
1192 }
1193
1194 // Store the local variable to release the lock.
1195 const auto desiredActiveMode = display->getDesiredActiveMode();
1196 if (!desiredActiveMode) {
1197 // No desired active mode pending to be applied
1198 continue;
1199 }
1200
1201 if (!isDisplayActiveLocked(display)) {
1202 // display is no longer the active display, so abort the mode change
1203 clearDesiredActiveModeState(display);
1204 continue;
1205 }
1206
1207 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1208 if (!desiredMode) {
1209 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1210 desiredActiveMode->mode->getId().value());
1211 clearDesiredActiveModeState(display);
1212 continue;
1213 }
1214
1215 const auto refreshRate = desiredMode->getFps();
1216 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1217 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1218 to_string(display->getId()).c_str());
1219
1220 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001221 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001222 desiredActiveModeChangeDone(display);
1223 continue;
1224 }
1225
1226 // Desired active mode was set, it is different than the mode currently in use, however
1227 // allowed modes might have changed by the time we process the refresh.
1228 // Make sure the desired mode is still allowed
1229 const auto displayModeAllowed =
1230 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1231 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001232 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001233 continue;
1234 }
1235
1236 // TODO(b/142753666) use constrains
1237 hal::VsyncPeriodChangeConstraints constraints;
1238 constraints.desiredTimeNanos = systemTime();
1239 constraints.seamlessRequired = false;
1240 hal::VsyncPeriodChangeTimeline outTimeline;
1241
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001242 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1243 display->initiateModeChange(*desiredActiveMode,
1244 constraints, &outTimeline));
1245
Ady Abraham690f4612021-07-01 23:24:03 -07001246 if (status != NO_ERROR) {
1247 // initiateModeChange may fail if a hotplug event is just about
1248 // to be sent. We just log the error in this case.
1249 ALOGW("initiateModeChange failed: %d", status);
1250 continue;
1251 }
1252 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1253
Marin Shalamanovdd594312021-11-09 16:37:37 +01001254 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001255 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001256 mSetActiveModePending = true;
1257 } else {
1258 // Updating the internal state should be done outside the loop,
1259 // because it can recreate a DisplayDevice and modify mDisplays
1260 // which will invalidate the iterator.
1261 displayToUpdateImmediately = display->getPhysicalId();
1262 }
1263 }
1264
1265 if (displayToUpdateImmediately) {
1266 updateInternalStateWithChangedMode();
1267
1268 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1269 const auto desiredActiveMode = display->getDesiredActiveMode();
1270 if (desiredActiveMode &&
1271 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1272 desiredActiveModeChangeDone(display);
1273 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001274 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001275}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001276
Alec Mouridea1ac52021-06-23 18:12:18 -07001277void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001278 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001279 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001280 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001281 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001282 for (const auto& [_, display] : mDisplays) {
1283 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001284 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001285 }
1286 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001287 });
1288
1289 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001290}
1291
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001292std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1293 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001294
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001295 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001296 // filter out all wide color modes. The typical reason why this happens is that the
1297 // hardware is not good enough to support GPU composition of wide color, and thus the
1298 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001299 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1300 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001301 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1302 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001303 }
Michael Wright28f24d02016-07-12 13:30:53 -07001304
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001305 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001306}
1307
Daniel Solomon42d04562019-01-20 21:03:19 -08001308status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1309 ui::DisplayPrimaries &primaries) {
1310 if (!displayToken) {
1311 return BAD_VALUE;
1312 }
1313
1314 // Currently we only support this API for a single internal display.
1315 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001316 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001317 }
1318
1319 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1320 return NO_ERROR;
1321}
1322
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001323status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001324 if (!displayToken) {
1325 return BAD_VALUE;
1326 }
1327
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001328 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001329 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001330 if (!display) {
1331 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1332 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001333 return NAME_NOT_FOUND;
1334 }
1335
1336 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001337 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1338 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001339 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001340 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001341
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001342 const auto modes = getDisplayColorModes(*display);
1343 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1344
1345 if (mode < ColorMode::NATIVE || !exists) {
1346 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1347 decodeColorMode(mode).c_str(), mode, displayToken.get());
1348 return BAD_VALUE;
1349 }
1350
1351 display->getCompositionDisplay()->setColorProfile(
1352 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1353
1354 return NO_ERROR;
1355 });
1356
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001357 // TODO(b/195698395): Propagate error.
1358 future.wait();
1359 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001360}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001361
Kriti Dang7defaf32021-11-15 11:55:43 +01001362status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001363 auto future = mScheduler->schedule(
1364 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1365
1366 *outSupport = future.get();
1367 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001368}
1369
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001370status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1371 ui::DisplayModeId modeId) {
1372 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001373 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001374 const auto display = getDisplayDeviceLocked(displayToken);
1375 if (!display) {
1376 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1377 return NAME_NOT_FOUND;
1378 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001379
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001380 if (display->isVirtual()) {
1381 ALOGE("%s: Invalid operation on virtual display", whence);
1382 return INVALID_OPERATION;
1383 }
1384
1385 const auto displayId = display->getPhysicalId();
1386 const auto mode = display->getMode(DisplayModeId{modeId});
1387 if (!mode) {
1388 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1389 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001390 return BAD_VALUE;
1391 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001392
1393 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001394 });
1395 return future.get();
1396}
1397
1398status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001399 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001400 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001401 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1402 return getHwComposer().clearBootDisplayMode(*displayId);
1403 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001404 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001405 return BAD_VALUE;
1406 }
1407 });
1408 return future.get();
1409}
1410
Galia Peycheva5492cb52019-10-30 14:13:16 +01001411void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001412 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001413 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001414 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1415 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1416 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001417 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001418 }
1419 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001420}
1421
Galia Peycheva5492cb52019-10-30 14:13:16 +01001422void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001423 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001424 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001425 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001426 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001427 getHwComposer().setContentType(*displayId, type);
1428 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001429 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001430 }
1431 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001432}
1433
Svetoslavd85084b2014-03-20 10:28:31 -07001434status_t SurfaceFlinger::clearAnimationFrameStats() {
1435 Mutex::Autolock _l(mStateLock);
1436 mAnimFrameTracker.clearStats();
1437 return NO_ERROR;
1438}
1439
1440status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1441 Mutex::Autolock _l(mStateLock);
1442 mAnimFrameTracker.getStats(outStats);
1443 return NO_ERROR;
1444}
1445
Kriti Dang49ad4132021-01-08 11:49:56 +01001446status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1447 const std::vector<ui::Hdr>& hdrTypes) {
1448 Mutex::Autolock lock(mStateLock);
1449
1450 auto display = getDisplayDeviceLocked(displayToken);
1451 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001452 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001453 return NAME_NOT_FOUND;
1454 }
1455
1456 display->overrideHdrTypes(hdrTypes);
1457 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1458 return NO_ERROR;
1459}
1460
Tej Singhe2751772021-04-06 22:05:29 -07001461status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1462 *success = mTimeStats->onPullAtom(atomId, pulledData);
1463 return NO_ERROR;
1464}
1465
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001466status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1467 ui::PixelFormat* outFormat,
1468 ui::Dataspace* outDataspace,
1469 uint8_t* outComponentMask) const {
1470 if (!outFormat || !outDataspace || !outComponentMask) {
1471 return BAD_VALUE;
1472 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001473
1474 Mutex::Autolock lock(mStateLock);
1475
1476 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1477 if (!displayId) {
1478 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001479 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001480
1481 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001482 outDataspace, outComponentMask);
1483}
1484
Kevin DuBois74e53772018-11-19 10:52:38 -08001485status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1486 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001487 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001488 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001489 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001490 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1491 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1492 componentMask, maxFrames);
1493 } else {
1494 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1495 return NAME_NOT_FOUND;
1496 }
1497 });
1498
1499 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001500}
1501
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001502status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1503 uint64_t maxFrames, uint64_t timestamp,
1504 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001505 Mutex::Autolock lock(mStateLock);
1506
1507 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1508 if (!displayId) {
1509 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001510 }
1511
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001512 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001513}
1514
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001515status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1516 if (!outSupported) {
1517 return BAD_VALUE;
1518 }
1519 *outSupported = getRenderEngine().supportsProtectedContent();
1520 return NO_ERROR;
1521}
1522
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001523status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1524 bool* outIsWideColorDisplay) const {
1525 if (!displayToken || !outIsWideColorDisplay) {
1526 return BAD_VALUE;
1527 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001528
1529 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001530 const auto display = getDisplayDeviceLocked(displayToken);
1531 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001532 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001533 }
Peiyong Linff84a152019-05-17 18:36:19 -07001534
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001535 *outIsWideColorDisplay =
1536 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001537 return NO_ERROR;
1538}
1539
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001540status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001541 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001542 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001543
Dominik Laskowski6505f792019-09-18 11:10:05 -07001544 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001545 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001546 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001547 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001548
Dominik Laskowski756b7892021-08-04 12:53:59 -07001549 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001550 return NO_ERROR;
1551}
1552
1553status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001554 Mutex::Autolock lock(mStateLock);
Ady Abrahame90dd522020-12-29 12:08:45 -08001555 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(when);
Ady Abraham56b42a42020-12-28 16:48:48 -08001556 const auto expectedPresent = calculateExpectedPresentTime(stats);
Ady Abraham9c53ee72020-07-22 21:16:18 -07001557 return mScheduler->injectVSync(when, /*expectedVSyncTime=*/expectedPresent,
1558 /*deadlineTimestamp=*/expectedPresent)
1559 ? NO_ERROR
1560 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001561}
1562
Huihong Luo05539a12022-02-23 10:29:40 -08001563status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001564 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001565 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001566 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001567 mDrawingState.traverseInZOrder([&](Layer* layer) {
1568 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1569 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001570 });
1571
1572 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001573 return NO_ERROR;
1574}
1575
Peiyong Linc6780972018-10-28 15:24:08 -07001576status_t SurfaceFlinger::getCompositionPreference(
1577 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1578 Dataspace* outWideColorGamutDataspace,
1579 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001580 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001581 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001582 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001583 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001584 return NO_ERROR;
1585}
1586
Dan Stozaec460082018-12-17 15:35:09 -08001587status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1588 const sp<IBinder>& stopLayerHandle,
1589 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001590 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001591 return BAD_VALUE;
1592 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001593
1594 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1595 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001596 return NO_ERROR;
1597}
1598
Dan Stozaec460082018-12-17 15:35:09 -08001599status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001600 if (!listener) {
1601 return BAD_VALUE;
1602 }
Dan Stozaec460082018-12-17 15:35:09 -08001603 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001604 return NO_ERROR;
1605}
Dan Gittik57e63c52019-01-18 16:37:54 +00001606
Alec Mouria9a68a62021-03-04 19:14:50 -08001607status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001608 if (!listener) {
1609 return BAD_VALUE;
1610 }
1611
Alec Mouria9a68a62021-03-04 19:14:50 -08001612 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001613 return NO_ERROR;
1614}
1615
1616status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1617 if (!listener) {
1618 return BAD_VALUE;
1619 }
1620 mFpsReporter->removeListener(listener);
1621 return NO_ERROR;
1622}
1623
Galia Peycheva8f04b302021-04-27 13:25:38 +02001624status_t SurfaceFlinger::addTunnelModeEnabledListener(
1625 const sp<gui::ITunnelModeEnabledListener>& listener) {
1626 if (!listener) {
1627 return BAD_VALUE;
1628 }
1629
1630 mTunnelModeEnabledReporter->addListener(listener);
1631 return NO_ERROR;
1632}
1633
1634status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1635 const sp<gui::ITunnelModeEnabledListener>& listener) {
1636 if (!listener) {
1637 return BAD_VALUE;
1638 }
1639
1640 mTunnelModeEnabledReporter->removeListener(listener);
1641 return NO_ERROR;
1642}
1643
Dan Gittik57e63c52019-01-18 16:37:54 +00001644status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1645 bool* outSupport) const {
1646 if (!displayToken || !outSupport) {
1647 return BAD_VALUE;
1648 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001649
1650 Mutex::Autolock lock(mStateLock);
1651
Dan Gittik57e63c52019-01-18 16:37:54 +00001652 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1653 if (!displayId) {
1654 return NAME_NOT_FOUND;
1655 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001656 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001657 return NO_ERROR;
1658}
1659
Alec Mouricdf16792021-12-10 13:16:06 -08001660bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1661 bool hasHdrLayers = false;
1662 mDrawingState.traverse([&,
1663 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1664 hasHdrLayers |= (layer->isVisible() &&
1665 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1666 isHdrDataspace(layer->getDataSpace()));
1667 });
1668 return hasHdrLayers;
1669}
1670
John Reck22be6962021-03-10 12:59:54 -05001671status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1672 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001673 if (!displayToken) {
1674 return BAD_VALUE;
1675 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001676
Dominik Laskowski756b7892021-08-04 12:53:59 -07001677 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001678 return ftl::chain(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001679 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001680 const bool supportsDisplayBrightnessCommand =
1681 getHwComposer().getComposer()->isSupported(
1682 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1683 // If we support applying display brightness as a command, then we also support
1684 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001685 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001686 auto compositionDisplay = display->getCompositionDisplay();
1687 float currentDimmingRatio =
1688 compositionDisplay->editState().sdrWhitePointNits /
1689 compositionDisplay->editState().displayBrightnessNits;
1690 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1691 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001692 FTL_FAKE_GUARD(kMainThreadContext,
1693 display->stageBrightness(brightness.displayBrightness));
1694
Alec Mouri6da0e272022-02-07 12:45:57 -08001695 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1696 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001697 scheduleComposite(FrameHint::kNone);
1698 } else {
1699 scheduleCommit(FrameHint::kNone);
1700 }
1701 return ftl::yield<status_t>(OK);
1702 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001703 return getHwComposer()
1704 .setDisplayBrightness(display->getPhysicalId(),
1705 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001706 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001707 Hwc2::Composer::DisplayBrightnessOptions{
1708 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001709 }
Alec Mouricdf16792021-12-10 13:16:06 -08001710
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001711 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001712 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001713 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001714 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001715 }))
1716 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001717 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001718}
1719
John Reck88270902021-03-18 11:27:35 -04001720status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1721 const sp<gui::IHdrLayerInfoListener>& listener) {
1722 if (!displayToken) {
1723 return BAD_VALUE;
1724 }
1725
1726 Mutex::Autolock lock(mStateLock);
1727
1728 const auto display = getDisplayDeviceLocked(displayToken);
1729 if (!display) {
1730 return NAME_NOT_FOUND;
1731 }
1732 const auto displayId = display->getId();
1733 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1734 if (!hdrInfoReporter) {
1735 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1736 }
1737 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001738
1739
1740 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001741 return OK;
1742}
1743
1744status_t SurfaceFlinger::removeHdrLayerInfoListener(
1745 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1746 if (!displayToken) {
1747 return BAD_VALUE;
1748 }
1749
1750 Mutex::Autolock lock(mStateLock);
1751
1752 const auto display = getDisplayDeviceLocked(displayToken);
1753 if (!display) {
1754 return NAME_NOT_FOUND;
1755 }
1756 const auto displayId = display->getId();
1757 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1758 if (hdrInfoReporter) {
1759 hdrInfoReporter->removeListener(listener);
1760 }
1761 return OK;
1762}
1763
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001764status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001765 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001766 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001767
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001768 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001769 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001770 }
1771
1772 return NO_ERROR;
1773}
1774
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001775status_t SurfaceFlinger::getDisplayDecorationSupport(
1776 const sp<IBinder>& displayToken,
1777 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001778 if (!displayToken || !outSupport) {
1779 return BAD_VALUE;
1780 }
1781
1782 Mutex::Autolock lock(mStateLock);
1783
1784 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1785 if (!displayId) {
1786 return NAME_NOT_FOUND;
1787 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001788 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001789 return NO_ERROR;
1790}
1791
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001792// ----------------------------------------------------------------------------
1793
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001794sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham62f216c2020-10-13 19:07:23 -07001795 ISurfaceComposer::VsyncSource vsyncSource,
1796 ISurfaceComposer::EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001797 const auto& handle =
1798 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001799
Ady Abraham62f216c2020-10-13 19:07:23 -07001800 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001801}
1802
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001803void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001804 if (hint == FrameHint::kActive) {
1805 mScheduler->resetIdleTimer();
1806 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001807 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001808 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001809}
1810
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001811void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1812 mMustComposite = true;
1813 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001814}
1815
1816void SurfaceFlinger::scheduleRepaint() {
1817 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001818 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001819}
1820
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001821void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001822 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001823}
1824
Ady Abraham2492a022020-07-24 11:09:55 -07001825nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001826 if (const auto display = getDefaultDisplayDeviceLocked()) {
1827 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001828 }
1829
Marin Shalamanov045b7002021-01-07 16:56:24 +01001830 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001831}
1832
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001833void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1834 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001835 const std::string tracePeriod = [vsyncPeriod]() {
1836 if (ATRACE_ENABLED() && vsyncPeriod) {
1837 std::stringstream ss;
1838 ss << "(" << *vsyncPeriod << ")";
1839 return ss.str();
1840 }
1841 return std::string();
1842 }();
1843 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001844
Steven Thomas3cfac282017-02-06 12:29:30 -08001845 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001846 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1847 if (displayId) {
1848 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1849 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001850 display->onVsync(timestamp);
1851 }
1852
Dominik Laskowski075d3172018-05-24 15:50:06 -07001853 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001854 return;
1855 }
1856
Ady Abrahame1166472021-07-15 10:56:06 -07001857 const bool isActiveDisplay =
1858 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1859 if (!isActiveDisplay) {
1860 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001861 return;
1862 }
1863
Alec Mourif8e689c2019-05-20 18:32:22 -07001864 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001865 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001866 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001867 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001868 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001869}
1870
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001871void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001872 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1873 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001874}
1875
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001876void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1877 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001878 const bool connected = connection == hal::Connection::CONNECTED;
1879 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001880
Steven Thomasb02664d2017-07-26 18:48:28 -07001881 // Only lock if we're not on the main thread. This function is normally
1882 // called on a hwbinder thread, but for the primary display it's called on
1883 // the main thread with the state lock already held, so don't attempt to
1884 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001885 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001886
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001887 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001888
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001889 if (std::this_thread::get_id() == mMainThreadId) {
1890 // Process all pending hot plug events immediately if we are on the main thread.
1891 processDisplayHotplugEventsLocked();
1892 }
1893
Lloyd Piqueba04e622017-12-14 17:11:26 -08001894 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001895}
1896
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001897void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1898 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001899 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001900 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001901
1902 if (timeline.refreshRequired) {
1903 scheduleComposite(FrameHint::kNone);
1904 }
Ady Abraham7159f572019-10-11 11:10:18 -07001905}
1906
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001907void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001908 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001909 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1910}
1911
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001912void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001913 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001914 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001915}
1916
Yichi Chen3401b562022-01-17 15:42:35 +08001917void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001918 ATRACE_CALL();
1919 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001920}
1921
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001922void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001923 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001924
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001925 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001926 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001927 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001928
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001929 if (const auto display = getDefaultDisplayDeviceLocked();
1930 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001931 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001932 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001933 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001934}
1935
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001936SurfaceFlinger::FenceWithFenceTime SurfaceFlinger::previousFrameFence() {
Ady Abrahamccf4b472021-05-11 19:53:01 -07001937 const auto now = systemTime();
1938 const auto vsyncPeriod = mScheduler->getDisplayStatInfo(now).vsyncPeriod;
1939 const bool expectedPresentTimeIsTheNextVsync = mExpectedPresentTime - now <= vsyncPeriod;
1940 return expectedPresentTimeIsTheNextVsync ? mPreviousPresentFences[0]
1941 : mPreviousPresentFences[1];
Alec Mouri6d414b52020-03-17 11:18:05 -07001942}
1943
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001944bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001945 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001946 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001947
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001948 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001949 return false;
1950 }
1951
Dan Stoza59083052020-04-28 10:13:20 -07001952 const status_t status = fence->wait(graceTimeMs);
1953 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1954 // which calls wait(0) again internally
1955 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001956}
1957
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001958nsecs_t SurfaceFlinger::previousFramePresentTime() {
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001959 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001960
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001961 if (fence == FenceTime::NO_FENCE) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001962 return Fence::SIGNAL_TIME_INVALID;
1963 }
1964
1965 return fence->getSignalTime();
1966}
1967
Ady Abraham56b42a42020-12-28 16:48:48 -08001968nsecs_t SurfaceFlinger::calculateExpectedPresentTime(DisplayStatInfo stats) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001969 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham8cb21882020-08-26 18:22:05 -07001970 return mVsyncModulator->getVsyncConfig().sfOffset > 0 ? stats.vsyncTime
1971 : stats.vsyncTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001972}
1973
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001974bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1975 FTL_FAKE_GUARD(kMainThreadContext) {
Matt Buckleyef51fba2021-10-12 19:30:12 +00001976 // we set this once at the beginning of commit to ensure consistency throughout the whole frame
Xiang Wang839fe5b2022-04-04 17:39:38 +00001977 mPowerHintSessionData.sessionEnabled = mPowerAdvisor->usePowerHintSession();
Matt Buckleyef51fba2021-10-12 19:30:12 +00001978 if (mPowerHintSessionData.sessionEnabled) {
1979 mPowerHintSessionData.commitStart = systemTime();
1980 }
1981
Dan Stoza28d46a52020-04-28 09:54:54 -07001982 // calculate the expected present time once and use the cached
1983 // value throughout this frame to make sure all layers are
1984 // seeing this same value.
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001985 if (expectedVsyncTime >= frameTime) {
1986 mExpectedPresentTime = expectedVsyncTime;
Snild Dolkow819636c2021-01-22 14:42:08 +01001987 } else {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001988 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(frameTime);
Snild Dolkow819636c2021-01-22 14:42:08 +01001989 mExpectedPresentTime = calculateExpectedPresentTime(stats);
1990 }
1991
1992 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001993 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07001994
Matt Buckleyef51fba2021-10-12 19:30:12 +00001995 if (mPowerHintSessionData.sessionEnabled) {
Xiang Wang839fe5b2022-04-04 17:39:38 +00001996 mPowerAdvisor->setTargetWorkDuration(mExpectedPresentTime -
1997 mPowerHintSessionData.commitStart);
Matt Buckleyef51fba2021-10-12 19:30:12 +00001998 }
Ady Abraham893c99d2021-04-30 16:00:23 -07001999 const auto vsyncIn = [&] {
2000 if (!ATRACE_ENABLED()) return 0.f;
2001 return (mExpectedPresentTime - systemTime()) / 1e6f;
2002 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002003 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
2004 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002005
Dan Stoza28d46a52020-04-28 09:54:54 -07002006 // When Backpressure propagation is enabled we want to give a small grace period
2007 // for the present fence to fire instead of just giving up on this frame to handle cases
2008 // where present fence is just about to get signaled.
2009 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002010 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002011
2012 // Pending frames may trigger backpressure propagation.
2013 const TracedOrdinal<bool> framePending = {"PrevFramePending",
2014 previousFramePending(graceTimeForPresentFenceMs)};
2015
2016 // Frame missed counts for metrics tracking.
2017 // A frame is missed if the prior frame is still pending. If no longer pending,
2018 // then we still count the frame as missed if the predicted present time
2019 // was further in the past than when the fence actually fired.
2020
2021 // Add some slop to correct for drift. This should generally be
2022 // smaller than a typical frame duration, but should not be so small
2023 // that it reports reasonable drift as a missed frame.
Ady Abrahame90dd522020-12-29 12:08:45 -08002024 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(systemTime());
Dan Stoza28d46a52020-04-28 09:54:54 -07002025 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
2026 const nsecs_t previousPresentTime = previousFramePresentTime();
2027 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2028 framePending ||
2029 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002030 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002031 previousPresentTime - frameMissedSlop))};
2032 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2033 mHadDeviceComposition && frameMissed};
2034 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2035 mHadClientComposition && frameMissed};
2036
2037 if (frameMissed) {
2038 mFrameMissedCount++;
2039 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002040 }
2041
2042 if (hwcFrameMissed) {
2043 mHwcFrameMissedCount++;
2044 }
2045
2046 if (gpuFrameMissed) {
2047 mGpuFrameMissedCount++;
2048 }
2049
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002050 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002051 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002052 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002053 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002054 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002055 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002056 }
2057
2058 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002059 // the mode, hence we update SF.
2060 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002061 {
2062 Mutex::Autolock lock(mStateLock);
2063 updateInternalStateWithChangedMode();
2064 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002065 }
2066
John Reck2ec53912020-07-07 16:53:55 -07002067 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002068 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002069 scheduleCommit(FrameHint::kNone);
2070 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002071 }
2072 }
2073
Dan Stoza28d46a52020-04-28 09:54:54 -07002074 if (mTracingEnabledChanged) {
Vishnu Nair7891e962021-11-11 12:07:21 -08002075 mLayerTracingEnabled = mLayerTracing.isEnabled();
Dan Stoza28d46a52020-04-28 09:54:54 -07002076 mTracingEnabledChanged = false;
2077 }
2078
Ady Abraham29d0da32020-07-16 18:39:33 -07002079 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002080 Mutex::Autolock lock(mStateLock);
2081 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002082 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002083 }
2084 }
2085
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002086 // Composite if transactions were committed, or if requested by HWC.
2087 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002088 {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002089 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(stats.vsyncPeriod));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002090
chaviw6b9ffea2021-11-08 09:25:48 -06002091 bool needsTraversal = false;
2092 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002093 needsTraversal |= commitCreatedLayers();
2094 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002095 }
2096
2097 const bool shouldCommit =
2098 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2099 if (shouldCommit) {
2100 commitTransactions();
2101 }
2102
2103 if (transactionFlushNeeded()) {
2104 setTransactionFlags(eTransactionFlushNeeded);
2105 }
2106
2107 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002108 mustComposite |= latchBuffers();
2109
chaviw6b9ffea2021-11-08 09:25:48 -06002110 // This has to be called after latchBuffers because we want to include the layers that have
2111 // been latched in the commit callback
2112 if (!needsTraversal) {
2113 // Invoke empty transaction callbacks early.
2114 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2115 } else {
2116 // Invoke OnCommit callbacks.
2117 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2118 }
2119
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002120 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002121 }
2122
2123 // Layers need to get updated (in the previous line) before we can use them for
2124 // choosing the refresh rate.
2125 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2126 // and may eventually call to ~Layer() if it holds the last reference
2127 {
2128 Mutex::Autolock _l(mStateLock);
2129 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002130 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002131 }
2132
Dan Stoza28d46a52020-04-28 09:54:54 -07002133 updateCursorAsync();
2134 updateInputFlinger();
2135
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002136 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2137 // This will block and tracing should only be enabled for debugging.
2138 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
2139 }
2140
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002141 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002142
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002143 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002144}
2145
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002146void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2147 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002148 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002149
Matt Buckleyef51fba2021-10-12 19:30:12 +00002150 if (mPowerHintSessionData.sessionEnabled) {
2151 mPowerHintSessionData.compositeStart = systemTime();
2152 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07002153
Lloyd Piqueab039b52019-02-13 14:22:42 -08002154 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002155 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002156 refreshArgs.outputs.reserve(displays.size());
2157 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002158 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2159 }
2160 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002161 if (auto layerFE = layer->getCompositionEngineLayerFE())
2162 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002163 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002164 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002165 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002166 if (auto layerFE = layer->getCompositionEngineLayerFE())
2167 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002168 }
2169
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002170 refreshArgs.outputColorSetting = useColorManagement
2171 ? mDisplayColorSetting
2172 : compositionengine::OutputColorSetting::kUnmanaged;
2173 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2174 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002175
2176 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002177 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002178 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002179 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002180
2181 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2182 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2183 mDrawingState.colorMatrixChanged = false;
2184 }
2185
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002186 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002187
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002188 if (mDebugFlashDelay != 0) {
2189 refreshArgs.devOptForceClientComposition = true;
2190 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002191 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002192
Ady Abraham43065bd2021-12-10 17:22:15 -08002193 const auto expectedPresentTime = mExpectedPresentTime.load();
2194 const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
Ady Abrahamcaba2982021-06-16 16:45:04 -07002195 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2196 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002197 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002198 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002199 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002200
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002201 // Store the present time just before calling to the composition engine so we could notify
2202 // the scheduler.
2203 const auto presentTime = systemTime();
2204
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002205 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002206
2207 if (mPowerHintSessionData.sessionEnabled) {
2208 mPowerHintSessionData.presentEnd = systemTime();
2209 }
2210
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002211 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002212
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002213 if (mScheduler->onPostComposition(presentTime)) {
2214 scheduleComposite(FrameHint::kNone);
2215 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002216
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002217 postFrame();
2218 postComposition();
2219
Midas Chien50f52e22020-09-26 17:57:42 +08002220 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002221
Vishnu Nair9cf89262022-02-26 09:17:49 -08002222 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2223 TimeStats::ClientCompositionRecord clientCompositionRecord;
2224 for (const auto& [_, display] : displays) {
2225 const auto& state = display->getCompositionDisplay()->getState();
2226 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2227 mHadDeviceComposition |= state.usesDeviceComposition;
2228 mReusedClientComposition |= state.reusedClientComposition;
2229 clientCompositionRecord.predicted |=
2230 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2231 clientCompositionRecord.predictionSucceeded |=
2232 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002233 }
2234
Vishnu Nair9cf89262022-02-26 09:17:49 -08002235 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2236 clientCompositionRecord.reused = mReusedClientComposition;
2237 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2238 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2239
Yichi Chen28dee2c2020-07-06 21:24:14 +08002240 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002241 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2242 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002243
David Sodman7e4ae112018-02-09 15:02:28 -08002244 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002245 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002246 // This will block and should only be used for debugging.
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002247 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
Vishnu Nairdf529052019-06-07 14:53:14 -07002248 }
Robert Carr167bdde2021-07-28 11:26:51 -07002249
2250 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002251 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002252
2253 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002254 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002255 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002256
2257 // calculate total render time for performance hinting if adpf cpu hint is enabled,
2258 if (mPowerHintSessionData.sessionEnabled) {
2259 const nsecs_t flingerDuration =
2260 (mPowerHintSessionData.presentEnd - mPowerHintSessionData.commitStart);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002261 mPowerAdvisor->sendActualWorkDuration(flingerDuration, mPowerHintSessionData.presentEnd);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002262 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002263}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002264
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002265void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002266 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002267
Vishnu Nair4351ad52019-02-11 14:13:02 -08002268 if (mVisibleRegionsDirty) {
2269 computeLayerBounds();
2270 }
2271
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002272 for (auto& layer : mLayersPendingRefresh) {
2273 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002274 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002275 invalidateLayerStack(layer, visibleReg);
2276 }
2277 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002278}
2279
Ana Krulece588e312018-09-18 12:32:24 -07002280void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2281 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002282 // Update queue of past composite+present times and determine the
2283 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002284 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002285 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002286 while (!getBE().mCompositePresentTimes.empty()) {
2287 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002288 // Cached values should have been updated before calling this method,
2289 // which helps avoid duplicate syscalls.
2290 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2291 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2292 break;
2293 }
2294 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002295 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002296 }
2297
2298 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002299 while (getBE().mCompositePresentTimes.size() > 16) {
2300 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002301 }
2302
Ana Krulece588e312018-09-18 12:32:24 -07002303 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002304}
2305
Ana Krulece588e312018-09-18 12:32:24 -07002306void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2307 nsecs_t compositeToPresentLatency) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002308 // Avoid division by 0 by defaulting to 60Hz
2309 const auto vsyncPeriod = stats.vsyncPeriod ?: (60_Hz).getPeriodNsecs();
2310
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002311 // Integer division and modulo round toward 0 not -inf, so we need to
2312 // treat negative and positive offsets differently.
Ady Abraham8287e852020-08-12 14:44:58 -07002313 nsecs_t idealLatency = (mVsyncConfiguration->getCurrentConfigs().late.sfOffset > 0)
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002314 ? (vsyncPeriod -
2315 (mVsyncConfiguration->getCurrentConfigs().late.sfOffset % vsyncPeriod))
2316 : ((-mVsyncConfiguration->getCurrentConfigs().late.sfOffset) % vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002317
Ady Abraham8287e852020-08-12 14:44:58 -07002318 // Just in case mVsyncConfiguration->getCurrentConfigs().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002319 if (idealLatency <= 0) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002320 idealLatency = vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002321 }
2322
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002323 // Snap the latency to a value that removes scheduling jitter from the
2324 // composition and present times, which often have >1ms of jitter.
2325 // Reducing jitter is important if an app attempts to extrapolate
2326 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002327 // Snapping also allows an app to precisely calculate
Ady Abraham8287e852020-08-12 14:44:58 -07002328 // mVsyncConfiguration->getCurrentConfigs().late.sf with (presentLatency % interval).
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002329 const nsecs_t bias = vsyncPeriod / 2;
2330 const int64_t extraVsyncs = ((compositeToPresentLatency - idealLatency + bias) / vsyncPeriod);
Ady Abraham8d7e7842022-02-03 01:42:45 +00002331 const nsecs_t snappedCompositeToPresentLatency =
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002332 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002333
David Sodman99974d22017-11-28 12:04:33 -08002334 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002335 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002336 getBE().mCompositorTiming.interval = vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002337 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002338}
2339
John Reck49d9ad32022-02-23 19:03:31 -05002340bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
2341 if (!isHdrDataspace(layer->getDataSpace())) {
2342 return false;
2343 }
2344 if (mIgnoreHdrCameraLayers) {
2345 auto buffer = layer->getBuffer();
2346 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2347 return false;
2348 }
2349 }
2350 return true;
2351}
2352
ramindani06e518e2022-03-14 18:47:53 +00002353ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2354 bool isPrimary) const {
2355 const auto id = PhysicalDisplayId::tryCast(displayId);
2356 if (!id) {
2357 return ui::ROTATION_0;
2358 }
2359 if (getHwComposer().getComposer()->isSupported(
2360 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2361 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2362 case Hwc2::AidlTransform::ROT_90:
2363 return ui::ROTATION_90;
2364 case Hwc2::AidlTransform::ROT_180:
2365 return ui::ROTATION_180;
2366 case Hwc2::AidlTransform::ROT_270:
2367 return ui::ROTATION_270;
2368 default:
2369 return ui::ROTATION_0;
2370 }
2371 }
2372
2373 if (isPrimary) {
2374 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2375 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2376 case Values::ORIENTATION_90:
2377 return ui::ROTATION_90;
2378 case Values::ORIENTATION_180:
2379 return ui::ROTATION_180;
2380 case Values::ORIENTATION_270:
2381 return ui::ROTATION_270;
2382 default:
2383 break;
2384 }
2385 }
2386 return ui::ROTATION_0;
2387}
2388
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002389void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002390 ATRACE_CALL();
2391 ALOGV("postComposition");
2392
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002393 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002394
David Sodman73beded2017-11-15 11:56:06 -08002395 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002396 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002397 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002398 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002399 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002400 ->getRenderSurface()
2401 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002402 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002403 } else {
2404 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2405 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002406
David Sodman73beded2017-11-15 11:56:06 -08002407 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002408 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002409 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002410 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002411 mPreviousPresentFences[0].fenceTime =
2412 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2413
2414 getBE().mDisplayTimeline.push(mPreviousPresentFences[0].fenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002415
Vishnu Nair9a69a042021-06-18 13:19:49 -07002416 nsecs_t now = systemTime();
2417
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002418 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2419 // information from previous' frame classification is already available when sending jank info
2420 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002421 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002422 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002423
Vishnu Nair9a69a042021-06-18 13:19:49 -07002424 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002425
Lloyd Piqueab039b52019-02-13 14:22:42 -08002426 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2427 // be sampled a little later than when we started doing work for this frame,
2428 // but that should be okay since updateCompositorTiming has snapping logic.
2429 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002430 mPreviousPresentFences[0].fenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002431 CompositorTiming compositorTiming;
2432 {
David Sodman99974d22017-11-28 12:04:33 -08002433 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2434 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002435 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002436
Robert Carrc747ad02021-06-11 14:01:24 -07002437 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002438 layer->onPostComposition(display, glCompositionDoneFenceTime,
2439 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002440 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002441 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002442
John Reck88270902021-03-18 11:27:35 -04002443 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2444 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002445 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002446 {
2447 Mutex::Autolock lock(mStateLock);
2448 if (mFpsReporter) {
2449 mFpsReporter->dispatchLayerFps();
2450 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002451
2452 if (mTunnelModeEnabledReporter) {
2453 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2454 }
John Reck88270902021-03-18 11:27:35 -04002455 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002456 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2457 if (reporter && reporter->hasListeners()) {
2458 if (const auto display = getDisplayDeviceLocked(displayId)) {
2459 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002460 }
2461 }
2462 }
Robert Carr167bdde2021-07-28 11:26:51 -07002463 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2464 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002465 }
2466
Robert Carr167bdde2021-07-28 11:26:51 -07002467 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2468 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2469 HdrLayerInfoReporter::HdrLayerInfo info;
2470 int32_t maxArea = 0;
2471 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2472 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002473 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002474 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002475 const auto* outputLayer =
2476 compositionDisplay->getOutputLayerForLayer(layerFe);
2477 if (outputLayer) {
2478 info.numberOfHdrLayers++;
2479 const auto displayFrame = outputLayer->getState().displayFrame;
2480 const int32_t area = displayFrame.width() * displayFrame.height();
2481 if (area > maxArea) {
2482 maxArea = area;
2483 info.maxW = displayFrame.width();
2484 info.maxH = displayFrame.height();
2485 }
John Reckdb1a16b2021-07-09 13:05:52 -04002486 }
John Reck88270902021-03-18 11:27:35 -04002487 }
2488 }
Robert Carr167bdde2021-07-28 11:26:51 -07002489 });
2490 listener->dispatchHdrLayerInfo(info);
2491 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002492 }
2493
Robert Carr167bdde2021-07-28 11:26:51 -07002494 mSomeDataspaceChanged = false;
2495 mVisibleRegionsWereDirtyThisFrame = false;
2496
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002497 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002498 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002499 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002500
Ady Abrahamed3290f2021-05-17 15:12:14 -07002501 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002502 mPreviousPresentFences[0].fenceTime->isValid()) {
2503 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002504 }
2505
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002506 const bool isDisplayConnected =
2507 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002508
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002509 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002510 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002511 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002512 }
2513 }
2514
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002515 if (mAnimCompositionPending) {
2516 mAnimCompositionPending = false;
2517
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002518 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2519 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002520 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002521 // The HWC doesn't support present fences, so use the refresh
2522 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002523 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002524 mAnimFrameTracker.setActualPresentTime(presentTime);
2525 }
2526 mAnimFrameTracker.advanceFrame();
2527 }
Dan Stozab90cf072015-03-05 11:05:59 -08002528
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002529 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002530
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002531 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002532
Alec Mouri717bcb62020-02-10 17:07:19 -08002533 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2534 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2535 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2536
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002537 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002538 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002539 return;
2540 }
2541
2542 nsecs_t currentTime = systemTime();
2543 if (mHasPoweredOff) {
2544 mHasPoweredOff = false;
2545 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002546 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002547 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002548 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2549 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002550 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002551 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002552 }
David Sodman4a36e932017-11-07 14:29:47 -08002553 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002554 }
David Sodman4a36e932017-11-07 14:29:47 -08002555 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002556
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002557 // Cleanup any outstanding resources due to rendering a prior frame.
2558 getRenderEngine().cleanupPostRender();
2559
Dan Stoza436ccf32018-06-21 12:10:12 -07002560 {
2561 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002562 if (mTexturePool.size() < mTexturePoolSize) {
2563 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002564 const size_t offset = mTexturePool.size();
2565 mTexturePool.resize(mTexturePoolSize);
2566 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2567 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002568 } else if (mTexturePool.size() > mTexturePoolSize) {
2569 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2570 const size_t offset = mTexturePoolSize;
2571 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2572 mTexturePool.resize(mTexturePoolSize);
2573 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002574 }
2575 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002576
Dan Stoza45de5ba2019-04-25 14:12:09 -07002577 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2578 // side-effect of getTotalSize(), so we check that again here
2579 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002580 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002581 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2582 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002583}
2584
chaviw79468ab2021-10-27 11:11:24 -05002585FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002586 const ui::Size maxSize = [this] {
2587 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002588
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002589 // The LayerTraceGenerator tool runs without displays.
2590 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002591
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002592 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2593 [](ui::Size size, const auto& pair) -> ui::Size {
2594 const auto& display = pair.second;
2595 return {std::max(size.getWidth(), display->getWidth()),
2596 std::max(size.getHeight(), display->getHeight())};
2597 });
2598 }();
chaviwb09c6552021-08-12 17:20:43 -05002599
2600 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2601 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002602 const float xMax = maxSize.getWidth() * 10.f;
2603 const float yMax = maxSize.getHeight() * 10.f;
2604
2605 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002606}
2607
2608void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002609 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002610 for (const auto& layer : mDrawingState.layersSortedByZ) {
2611 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002612 }
2613}
2614
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002615void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002616 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002617 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002618 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002619 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2620 logFrameStats();
2621 }
2622 }
2623}
2624
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002625void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002626 ATRACE_CALL();
2627
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002628 // Keep a copy of the drawing state (that is going to be overwritten
2629 // by commitTransactionsLocked) outside of mStateLock so that the side
2630 // effects of the State assignment don't happen with mStateLock held,
2631 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002632 State drawingState(mDrawingState);
2633
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002634 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002635 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636
Mathias Agopianca4d3602011-05-19 15:38:14 -07002637 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002638 // so we can call commitTransactionsLocked unconditionally.
2639 // We clear the flags with mStateLock held to guarantee that
2640 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002641 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002642 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002643
Mathias Agopianca4d3602011-05-19 15:38:14 -07002644 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002645}
2646
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002647std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2648 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002649 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2650 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002651
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002652 int attempt = 0;
2653 constexpr int kMaxAttempts = 3;
2654 do {
2655 hwcModes = getHwComposer().getModes(displayId);
2656 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2657 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2658
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002659 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2660 return mode.hwcId == *activeModeHwcId;
2661 };
2662
2663 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2664 break;
2665 }
2666 } while (++attempt < kMaxAttempts);
2667
2668 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002669 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002670 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002671 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002672
2673 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002674 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2675 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002676 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002677
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002678 ui::DisplayModeId nextModeId = 1 +
2679 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2680 [](ui::DisplayModeId max, const auto& pair) {
2681 return std::max(max, pair.first.value());
2682 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002683
2684 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002685 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002686 const DisplayModeId id{nextModeId++};
2687 newModes.try_emplace(id,
2688 DisplayMode::Builder(hwcMode.hwcId)
2689 .setId(id)
2690 .setPhysicalDisplayId(displayId)
2691 .setResolution({hwcMode.width, hwcMode.height})
2692 .setVsyncPeriod(hwcMode.vsyncPeriod)
2693 .setDpiX(hwcMode.dpiX)
2694 .setDpiY(hwcMode.dpiY)
2695 .setGroup(hwcMode.configGroup)
2696 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002697 }
2698
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002699 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002700 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002701 [](const auto& lhs, const auto& rhs) {
2702 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002703 });
2704
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002705 // Keep IDs if modes have not changed.
2706 const auto& modes = sameModes ? oldModes : newModes;
2707 const DisplayModePtr activeMode =
2708 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2709 return pair.second->getHwcId() == activeModeHwcId;
2710 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002711
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002712 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002713}
2714
Lloyd Piqueba04e622017-12-14 17:11:26 -08002715void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2716 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002717 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002718 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002719
Dominik Laskowski075d3172018-05-24 15:50:06 -07002720 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002721 continue;
2722 }
2723
Marin Shalamanova524a092020-07-27 21:39:55 +02002724 const auto displayId = info->id;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002725 const auto it = mPhysicalDisplayTokens.find(displayId);
2726
Peiyong Line9d809e2020-04-14 13:10:48 -07002727 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002728 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002729
Dominik Laskowski55c85402020-01-21 16:25:47 -08002730 if (it == mPhysicalDisplayTokens.end()) {
2731 ALOGV("Creating display %s", to_string(displayId).c_str());
2732
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002734 state.physical = {.id = displayId,
2735 .type = getHwComposer().getDisplayConnectionType(displayId),
2736 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002737 .deviceProductInfo = std::move(info->deviceProductInfo),
2738 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002739 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002740 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002741 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002742
2743 sp<IBinder> token = new BBinder();
2744 mCurrentState.displays.add(token, state);
2745 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002746 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002747 } else {
2748 ALOGV("Recreating display %s", to_string(displayId).c_str());
2749
2750 const auto token = it->second;
2751 auto& state = mCurrentState.displays.editValueFor(token);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002752 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId
Marin Shalamanova903d032020-12-29 20:35:13 +01002753 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002754 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002755 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2756 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2757 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002758 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002759 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002760 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002761
Dominik Laskowski55c85402020-01-21 16:25:47 -08002762 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002763 if (index >= 0) {
2764 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2765 mInterceptor->saveDisplayDeletion(state.sequenceId);
2766 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002767 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002768 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002769 }
2770
2771 processDisplayChangesLocked();
2772 }
2773
2774 mPendingHotplugEvents.clear();
2775}
2776
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002777void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002778 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2779 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002780 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2781 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002782}
2783
Lloyd Pique99d3da52018-01-22 17:48:03 -08002784sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002785 const wp<IBinder>& displayToken,
2786 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002787 const DisplayDeviceState& state,
2788 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002789 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002790 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002791 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002792 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002793 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002794 creationArgs.hasWideColorGamut = false;
2795 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002796
Dominik Laskowski55c85402020-01-21 16:25:47 -08002797 if (const auto& physical = state.physical) {
2798 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002799 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002800 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002801 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2802 getKernelIdleTimerProperties(compositionDisplay->getId());
2803
Ady Abraham3efa3942021-06-24 19:01:25 -07002804 scheduler::RefreshRateConfigs::Config config =
2805 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2806 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002807 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002808 .idleTimerTimeout = idleTimerTimeoutMs,
2809 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002810 creationArgs.refreshRateConfigs =
2811 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2812 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002813 }
2814
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002815 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
2816 creationArgs.isPrimary = id == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002817
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002818 if (useColorManagement) {
2819 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2820 for (ColorMode colorMode : modes) {
2821 if (isWideColorMode(colorMode)) {
2822 creationArgs.hasWideColorGamut = true;
2823 }
2824
2825 std::vector<RenderIntent> renderIntents =
2826 getHwComposer().getRenderIntents(*id, colorMode);
2827 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002828 }
2829 }
tangrobin6753a022018-08-10 10:58:54 +08002830 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002831
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002832 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2833 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2834 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002835 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002836
Lloyd Pique90c115d2018-09-18 21:39:42 -07002837 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002838 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002839 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002840
Lloyd Pique99d3da52018-01-22 17:48:03 -08002841 // Make sure that composition can never be stalled by a virtual display
2842 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002843 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002844 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002845 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2846 }
2847
Dominik Laskowski718f9602019-11-09 20:01:35 -08002848 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002849 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2850 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002851
Lloyd Pique99d3da52018-01-22 17:48:03 -08002852 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002853 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002854
Lloyd Pique9370a482019-10-03 17:58:30 -07002855 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002856
Ady Abraham8565ad22021-06-22 17:45:44 -07002857 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002858
2859 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002860 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002861 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002862 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002863 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002864 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002865 display->getCompositionDisplay()->setColorProfile(
2866 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2867 RenderIntent::COLORIMETRIC,
2868 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002869 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002870 FTL_FAKE_GUARD(kMainThreadContext,
2871 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002872 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002873 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002874
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002875 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002876 display->setProjection(state.orientation, state.layerStackSpaceRect,
2877 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002878 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002879 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002880
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002881 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002882}
2883
Marin Shalamanovae685592020-02-12 17:12:22 +01002884void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2885 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002886 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002887 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2888 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002889 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002890 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2891 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002892 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002893 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002894 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002895 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002896 int format;
2897 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002898 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002899 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002900 } else {
2901 // Virtual displays without a surface are dormant:
2902 // they have external state (layer stack, projection,
2903 // etc.) but no internal state (i.e. a DisplayDevice).
2904 return;
2905 }
2906
2907 compositionengine::DisplayCreationArgsBuilder builder;
2908 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002909 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002910 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002911 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002912 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002913
Marin Shalamanov045b7002021-01-07 16:56:24 +01002914 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002915 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002916 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002917 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002918 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002919 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002920
2921 sp<compositionengine::DisplaySurface> displaySurface;
2922 sp<IGraphicBufferProducer> producer;
2923 sp<IGraphicBufferProducer> bqProducer;
2924 sp<IGraphicBufferConsumer> bqConsumer;
2925 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2926
Marin Shalamanovae685592020-02-12 17:12:22 +01002927 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002928 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2929 LOG_FATAL_IF(!displayId);
2930 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2931 bqProducer, bqConsumer, state.displayName);
2932 displaySurface = surface;
2933 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002934 } else {
2935 ALOGE_IF(state.surface != nullptr,
2936 "adding a supported display, but rendering "
2937 "surface is provided (%p), ignoring it",
2938 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002939 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2940 LOG_FATAL_IF(!displayId);
2941 displaySurface =
2942 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002943 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002944 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002945 producer = bqProducer;
2946 }
2947
Marin Shalamanov700e6392020-02-12 20:22:26 +01002948 LOG_FATAL_IF(!displaySurface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002949 const auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay),
2950 state, displaySurface, producer);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002951 mDisplays.emplace(displayToken, display);
Ady Abraham3efa3942021-06-24 19:01:25 -07002952 if (display->isPrimary()) {
2953 initScheduler(display);
2954 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002955 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002956 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002957 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002958}
2959
2960void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002961 auto display = getDisplayDeviceLocked(displayToken);
2962 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002963 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002964
2965 if (display->isVirtual()) {
2966 releaseVirtualDisplay(display->getVirtualId());
2967 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002968 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01002969 }
2970 }
2971
2972 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08002973
2974 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002975 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002976 // Destroy the display without holding the mStateLock.
2977 // This is a temporary solution until we can manage transaction queues without
2978 // holding the mStateLock.
2979 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
2980 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
2981 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
2982 // ends up running on the main thread causing a deadlock since setTransactionstate
2983 // will try to acquire the mStateLock. Instead we extend the lifetime of
2984 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
2985 // The display will be disconnected and removed from the mDisplays list so it will
2986 // not be accessible.
2987 }));
2988 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002989}
2990
2991void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2992 const DisplayDeviceState& currentState,
2993 const DisplayDeviceState& drawingState) {
2994 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2995 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002996
2997 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01002998 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02002999 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003000
Marin Shalamanovae685592020-02-12 17:12:22 +01003001 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3002 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003003 if (display->isVirtual()) {
3004 releaseVirtualDisplay(display->getVirtualId());
3005 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003006 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003007
Marin Shalamanovae685592020-02-12 17:12:22 +01003008 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003009
Marin Shalamanov700e6392020-02-12 20:22:26 +01003010 if (const auto& physical = currentState.physical) {
3011 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3012 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003013
Marin Shalamanovae685592020-02-12 17:12:22 +01003014 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003015
Marin Shalamanov700e6392020-02-12 20:22:26 +01003016 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003017 const auto display = getDisplayDeviceLocked(displayToken);
3018 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003019
3020 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003021 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003022 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003023 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003024 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003025 return;
3026 }
3027
3028 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3029 if (currentState.layerStack != drawingState.layerStack) {
3030 display->setLayerStack(currentState.layerStack);
3031 }
Evan Rosky2239b372021-05-20 13:43:47 -07003032 if (currentState.flags != drawingState.flags) {
3033 display->setFlags(currentState.flags);
3034 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003035 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003036 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3037 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3038 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3039 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003040 if (isDisplayActiveLocked(display)) {
3041 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003042 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003043 }
3044 if (currentState.width != drawingState.width ||
3045 currentState.height != drawingState.height) {
3046 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003047
Ady Abrahamed3290f2021-05-17 15:12:14 -07003048 if (isDisplayActiveLocked(display)) {
3049 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003050 }
3051 }
3052 }
3053}
Ady Abraham3efa3942021-06-24 19:01:25 -07003054void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003055 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003056 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003057 updatePhaseConfiguration(refreshRate);
3058 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003059}
Marin Shalamanovae685592020-02-12 17:12:22 +01003060
Lloyd Pique347200f2017-12-14 17:00:15 -08003061void SurfaceFlinger::processDisplayChangesLocked() {
3062 // here we take advantage of Vector's copy-on-write semantics to
3063 // improve performance by skipping the transaction entirely when
3064 // know that the lists are identical
3065 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3066 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3067 if (!curr.isIdenticalTo(draw)) {
3068 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003069
3070 // find the displays that were removed
3071 // (ie: in drawing state but not in current state)
3072 // also handle displays that changed
3073 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003074 for (size_t i = 0; i < draw.size(); i++) {
3075 const wp<IBinder>& displayToken = draw.keyAt(i);
3076 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003077 if (j < 0) {
3078 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003079 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003080 } else {
3081 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003082 const DisplayDeviceState& currentState = curr[j];
3083 const DisplayDeviceState& drawingState = draw[i];
3084 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003085 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003086 }
3087
3088 // find displays that were added
3089 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003090 for (size_t i = 0; i < curr.size(); i++) {
3091 const wp<IBinder>& displayToken = curr.keyAt(i);
3092 if (draw.indexOfKey(displayToken) < 0) {
3093 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003094 }
3095 }
3096 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003097
3098 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003099}
3100
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003101void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3102 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003103 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3104 if (displayTransactionNeeded) {
3105 processDisplayChangesLocked();
3106 processDisplayHotplugEventsLocked();
3107 }
Robert Carrb552ff52021-06-11 13:35:54 -07003108 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109
Robert Carre450fb52021-06-11 13:21:09 -07003110 if (mSomeChildrenChanged) {
3111 mVisibleRegionsDirty = true;
3112 mSomeChildrenChanged = false;
3113 }
3114
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003115 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003116 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003117 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003118 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003119 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003120 // the hint is set before we acquire a buffer from the surface texture.
3121 //
3122 // NOTE: layer transactions have taken place already, so we use their
3123 // drawing state. However, SurfaceFlinger's own transaction has not
3124 // happened yet, so we must use the current state layer list
3125 // (soon to become the drawing state list).
3126 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003127 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003128 ui::LayerStack layerStack;
3129
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003130 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003131 // NOTE: we rely on the fact that layers are sorted by
3132 // layerStack first (so we don't have to traverse the list
3133 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003134 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3135 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003136 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003137
3138 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003139 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003140 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3141 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003142 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003143
3144 // Pick the primary display if another display mirrors the layer.
3145 if (hintDisplay) {
3146 hintDisplay = nullptr;
3147 break;
3148 }
3149
3150 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003151 }
3152 }
Chet Haase91d25932013-04-11 15:24:55 -07003153
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003154 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003155 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3156 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003157
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003158 // could be null when this layer is using a layerStack
3159 // that is not visible on any display. Also can occur at
3160 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003161 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003162 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003163
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003164 layer->updateTransformHint(hintDisplay->getTransformHint());
Robert Carr2047fae2016-11-28 14:09:09 -08003165 });
Mathias Agopian84300952012-11-21 16:02:13 -08003166 }
3167
Robert Carr1f0a16a2016-10-24 16:27:39 -07003168 if (mLayersAdded) {
3169 mLayersAdded = false;
3170 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003171 mVisibleRegionsDirty = true;
3172 }
3173
3174 // some layers might have been removed, so
3175 // we need to update the regions they're exposing.
3176 if (mLayersRemoved) {
3177 mLayersRemoved = false;
3178 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003179 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003180 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003181 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003182 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003183 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003184 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003185 }
Robert Carr2047fae2016-11-28 14:09:09 -08003186 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003187 }
3188
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003189 doCommitTransactions();
3190 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3191 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003192}
3193
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003194void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003195 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003196 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003197 return;
3198 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003199
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003200 std::vector<WindowInfo> windowInfos;
3201 std::vector<DisplayInfo> displayInfos;
3202 bool updateWindowInfo = false;
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003203 if (mVisibleRegionsDirty || mInputInfoChanged) {
3204 mInputInfoChanged = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003205 updateWindowInfo = true;
3206 buildWindowInfos(windowInfos, displayInfos);
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003207 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003208 if (!updateWindowInfo && mInputWindowCommands.empty()) {
3209 return;
3210 }
3211 BackgroundExecutor::getInstance().execute([updateWindowInfo,
3212 windowInfos = std::move(windowInfos),
3213 displayInfos = std::move(displayInfos),
3214 inputWindowCommands =
3215 std::move(mInputWindowCommands),
3216 inputFlinger = mInputFlinger, this]() {
3217 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3218 if (updateWindowInfo) {
3219 mWindowInfosListenerInvoker->windowInfosChanged(windowInfos, displayInfos,
3220 inputWindowCommands.syncInputWindows);
3221 } else if (inputWindowCommands.syncInputWindows) {
3222 // If the caller requested to sync input windows, but there are no
3223 // changes to input windows, notify immediately.
3224 windowInfosReported();
3225 }
3226 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3227 inputFlinger->setFocusedWindow(focusRequest);
3228 }
3229 });
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003230
Arthur Hung6cbb9752019-09-05 16:38:18 +08003231 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003232}
3233
Alec Mouricdf16792021-12-10 13:16:06 -08003234void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3235 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3236 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3237 if (!supportsDisplayBrightnessCommand) {
3238 return;
3239 }
3240
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003241 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003242 if (const auto brightness = display->getStagedBrightness(); brightness) {
3243 if (!needsComposite) {
3244 const status_t error =
3245 getHwComposer()
3246 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003247 display->getCompositionDisplay()
3248 ->getState()
3249 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003250 Hwc2::Composer::DisplayBrightnessOptions{
3251 .applyImmediately = true})
3252 .get();
3253
3254 ALOGE_IF(error != NO_ERROR,
3255 "Error setting display brightness for display %s: %d (%s)",
3256 display->getDebugName().c_str(), error, strerror(error));
3257 }
3258 display->persistBrightness(needsComposite);
3259 }
3260 }
3261}
3262
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003263void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3264 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003265 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3266
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003267 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003268 const auto layerStack = display->getLayerStack();
3269 const auto info = display->getInputInfo();
3270
3271 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003272 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003273 continue;
3274 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003275
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003276 // If the layer stack is mirrored on multiple displays, the first display that is configured
3277 // to receive input takes precedence.
3278 auto& otherInfo = it->second;
3279 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003280 ALOGW_IF(display->receivesInput(),
3281 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003282 layerStack.id);
3283 } else {
3284 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003285 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003286 }
Robert Carr720e5062018-07-30 17:45:14 -07003287
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003288 static size_t sNumWindowInfos = 0;
3289 outWindowInfos.reserve(sNumWindowInfos);
3290 sNumWindowInfos = 0;
3291
Robert Carr720e5062018-07-30 17:45:14 -07003292 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003293 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003294
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003295 // Do not create WindowInfos for windows on displays that cannot receive input.
3296 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3297 const auto& info = opt->get();
3298 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003299 }
Robert Carr720e5062018-07-30 17:45:14 -07003300 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003301
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003302 sNumWindowInfos = outWindowInfos.size();
3303
3304 outDisplayInfos.reserve(displayInputInfos.size());
3305 for (const auto& [_, info] : displayInputInfos) {
3306 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003307 }
Robert Carr720e5062018-07-30 17:45:14 -07003308}
3309
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003310void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003311 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003312 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003313 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003314 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003315 }
3316 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003317
3318 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003319}
3320
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003321void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003322 // If this is called from the main thread mStateLock must be locked before
3323 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003324 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003325
3326 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003327
3328 const auto display = getDefaultDisplayDeviceLocked();
3329 if (!display || mBootStage != BootStage::FINISHED) {
3330 return;
3331 }
3332 ATRACE_CALL();
3333
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003334 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3335 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003336 return;
3337 }
3338
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003339 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003340}
3341
Ady Abraham62a0be22020-12-08 16:54:10 -08003342void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3343 PhysicalDisplayId displayId = [&]() {
3344 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3345 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3346 }();
3347
3348 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3349}
3350
Ady Abraham3efa3942021-06-24 19:01:25 -07003351void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003352 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003353 // If the scheduler is already initialized, this means that we received
3354 // a hotplug(connected) on the primary display. In that case we should
3355 // update the scheduler with the most recent display information.
3356 ALOGW("Scheduler already initialized, updating instead");
3357 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003358 return;
3359 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003360 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003361 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3362 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003363
Marin Shalamanova903d032020-12-29 20:35:13 +01003364 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003365 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003366
Dominik Laskowski068173d2021-08-11 17:22:59 -07003367 using Feature = scheduler::Feature;
3368 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003369
Dominik Laskowski068173d2021-08-11 17:22:59 -07003370 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3371 features |= Feature::kContentDetection;
3372 }
3373 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3374 features |= Feature::kTracePredictedVsync;
3375 }
3376 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003377 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003378 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003379 }
3380
Dominik Laskowski068173d2021-08-11 17:22:59 -07003381 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3382 static_cast<ISchedulerCallback&>(*this),
3383 features);
3384 {
3385 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003386 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003387 features |= Feature::kKernelIdleTimer;
3388 }
3389
3390 mScheduler->createVsyncSchedule(features);
3391 mScheduler->setRefreshRateConfigs(std::move(configs));
3392 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003393 setVsyncEnabled(false);
3394 mScheduler->startTimers();
3395
Ady Abraham9c53ee72020-07-22 21:16:18 -07003396 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003397 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003398 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003399 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003400 /*workDuration=*/configs.late.appWorkDuration,
3401 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003402 impl::EventThread::InterceptVSyncsCallback());
3403 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003404 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3405 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3406 /*readyDuration=*/configs.late.sfWorkDuration,
3407 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003408 mInterceptor->saveVSyncEvent(timestamp);
3409 });
3410
Dominik Laskowski756b7892021-08-04 12:53:59 -07003411 mScheduler->initVsync(mScheduler->getVsyncDispatch(), *mFrameTimeline->getTokenManager(),
3412 configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003413
3414 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003415 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003416 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003417 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003418 // initialization, so that the EventThreads always contain a reference to a
3419 // prior configuration.
3420 //
3421 // This is a bit hacky, but this avoids a back-pointer into the main SF
3422 // classes from EventThread, and there should be no run-time binder cost
3423 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003424 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003425}
3426
Marin Shalamanov5801c942020-12-17 17:00:13 +01003427void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3428 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003429 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003430 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003431}
3432
Ady Abraham55fa7272020-09-30 19:19:27 -07003433void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3434 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003435 mScheduler->setDuration(mAppConnectionHandle,
3436 /*workDuration=*/config.appWorkDuration,
3437 /*readyDuration=*/config.sfWorkDuration);
3438 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003439 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3440 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003441 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003442}
3443
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003444void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003445 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003446
Lloyd Pique58e24a32019-08-01 15:50:14 -07003447 if (!mLayersPendingRemoval.isEmpty()) {
3448 // Notify removed layers now that they can't be drawn from
3449 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003450 // Ensure any buffers set to display on any children are released.
3451 if (l->isRemovedFromCurrentState()) {
3452 l->latchAndReleaseBuffer();
3453 }
3454
3455 // If the layer has been removed and has no parent, then it will not be reachable
3456 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3457 // ensure we can copy its current to drawing state.
3458 if (!l->getParent()) {
3459 mOffscreenLayers.emplace(l.get());
3460 }
3461 }
3462 mLayersPendingRemoval.clear();
3463 }
3464
3465 // If this transaction is part of a window animation then the next frame
3466 // we composite should be considered an animation as well.
3467 mAnimCompositionPending = mAnimTransactionPending;
3468
3469 mDrawingState = mCurrentState;
3470 // clear the "changed" flags in current state
3471 mCurrentState.colorMatrixChanged = false;
3472
Robert Carra70e91c2021-06-11 13:59:52 -07003473 if (mVisibleRegionsDirty) {
3474 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3475 rootLayer->commitChildList();
3476 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003477 }
Robert Carra70e91c2021-06-11 13:59:52 -07003478
Lloyd Pique58e24a32019-08-01 15:50:14 -07003479 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003480 if (mNumClones > 0) {
3481 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3482 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003483}
3484
chaviw74d90ad2019-04-26 14:45:26 -07003485void SurfaceFlinger::commitOffscreenLayers() {
3486 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003487 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003488 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3489 layer->doTransaction(0);
3490 layer->commitChildList();
3491 }
chaviw74d90ad2019-04-26 14:45:26 -07003492 });
3493 }
3494}
3495
Chia-I Wuab0c3192017-08-01 11:29:00 -07003496void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003497 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003498 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003499 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003500 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003501 }
3502 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003503}
3504
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003505bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003506 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003507
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003508 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003509
Mathias Agopian4fec8732012-06-29 14:12:52 -07003510 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003511 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003512 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003513
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003514 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3515
Eric Penner51c59cd2014-07-28 19:51:58 -07003516 // Store the set of layers that need updates. This set must not change as
3517 // buffers are being latched, as this could result in a deadlock.
3518 // Example: Two producers share the same command stream and:
3519 // 1.) Layer 0 is latched
3520 // 2.) Layer 0 gets a new frame
3521 // 2.) Layer 1 gets a new frame
3522 // 3.) Layer 1 is latched.
3523 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3524 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003525 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003526 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3527 const uint32_t flags = layer->doTransaction(0);
3528 if (flags & Layer::eVisibleRegion) {
3529 mVisibleRegionsDirty = true;
3530 }
3531 }
Robert Carrb552ff52021-06-11 13:35:54 -07003532
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003533 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003534 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003535 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003536 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003537 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003538 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003539 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003540 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003541 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003542 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003543 }
Robert Carr2047fae2016-11-28 14:09:09 -08003544 });
Robert Carrb552ff52021-06-11 13:35:54 -07003545 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003546
chaviw49a108c2019-08-12 11:23:06 -07003547 // The client can continue submitting buffers for offscreen layers, but they will not
3548 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3549 // layers to ensure dequeueBuffer doesn't block indefinitely.
3550 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003551 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003552 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3553 }
3554
Lloyd Piquef2c79392018-12-20 16:23:33 -08003555 if (!mLayersWithQueuedFrames.empty()) {
3556 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3557 // writes to Layer current state. See also b/119481871
3558 Mutex::Autolock lock(mStateLock);
3559
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003560 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003561 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003562 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003563 newDataLatched = true;
3564 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003565 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003566 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003567 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003568
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003569 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003570
3571 // If we will need to wake up at some time in the future to deal with a
3572 // queued frame that shouldn't be displayed during this vsync period, wake
3573 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003574 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003575 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003576 }
3577
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003578 // enter boot animation on first buffer latch
3579 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3580 ALOGI("Enter boot animation");
3581 mBootStage = BootStage::BOOTANIMATION;
3582 }
3583
Robert Carr6a0382d2021-07-01 15:57:17 -07003584 if (mNumClones > 0) {
3585 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3586 }
chaviw74b03172019-08-19 11:09:03 -07003587
Dan Stoza6b9454d2014-11-07 16:00:59 -08003588 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003589 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590}
3591
Robert Carrc0df3122019-04-11 13:18:21 -07003592status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003593 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003594 bool addToRoot, uint32_t* outTransformHint) {
arthurhungdba591c2021-02-08 17:28:49 +08003595 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
3596 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
3597 ISurfaceComposer::MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003598 static_cast<void>(mScheduler->schedule([=] {
3599 ALOGE("Dumping random sampling of on-screen layers: ");
3600 mDrawingState.traverse([&](Layer *layer) {
3601 // Aim to dump about 200 layers to avoid totally trashing
3602 // logcat. On the other hand, if there really are 4096 layers
3603 // something has gone totally wrong its probably the most
3604 // useful information in logcat.
3605 if (rand() % 20 == 13) {
3606 ALOGE("Layer: %s", layer->getName().c_str());
3607 }
3608 });
3609 for (Layer* offscreenLayer : mOffscreenLayers) {
3610 if (rand() % 20 == 13) {
3611 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3612 }
3613 }
3614 }));
arthurhungdba591c2021-02-08 17:28:49 +08003615 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003616 }
3617
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003618 {
3619 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3620 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3621 }
arthurhungdba591c2021-02-08 17:28:49 +08003622
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003623 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003624 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003625 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003626 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003627 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003628 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003629 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003630 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003631
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003632 setTransactionFlags(eTransactionNeeded);
3633 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003634}
3635
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003636uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003637 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003638}
3639
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003640uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3641 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642}
3643
Dominik Laskowski94000c42022-03-17 12:55:14 -07003644void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003645 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003646 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003647
3648 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003649 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003650 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003651}
3652
Ady Abraham9dada822022-02-03 10:26:59 -08003653bool SurfaceFlinger::stopTransactionProcessing(
3654 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3655 applyTokensWithUnsignaledTransactions) const {
3656 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3657 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3658 // then we should have only one applyToken for processing.
3659 // so we can stop further transactions on this applyToken.
3660 return !applyTokensWithUnsignaledTransactions.empty();
3661 }
3662
3663 return false;
3664}
3665
ramindani9eff2492022-03-23 00:28:26 +00003666int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3667 std::vector<TransactionState>& transactions,
3668 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3669 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3670 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3671 applyTokensWithUnsignaledTransactions,
3672 /*tryApplyUnsignaled*/ true);
3673}
3674
Robert Carr79dc06a2022-02-22 15:28:59 -08003675int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003676 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003677 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003678 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3679 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003680 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003681 auto it = mPendingTransactionQueues.begin();
3682 while (it != mPendingTransactionQueues.end()) {
3683 auto& [applyToken, transactionQueue] = *it;
3684 while (!transactionQueue.empty()) {
3685 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3686 ATRACE_NAME("stopTransactionProcessing");
3687 break;
3688 }
3689
3690 auto& transaction = transactionQueue.front();
3691 const auto ready =
3692 transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3693 transaction.isAutoTimestamp,
3694 transaction.desiredPresentTime,
3695 transaction.originUid, transaction.states,
3696 bufferLayersReadyToPresent, transactions.size(),
3697 tryApplyUnsignaled);
3698 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3699 if (ready == TransactionReadiness::NotReady) {
3700 setTransactionFlags(eTransactionFlushNeeded);
3701 break;
3702 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003703 if (ready == TransactionReadiness::NotReadyBarrier) {
3704 transactionsPendingBarrier++;
3705 setTransactionFlags(eTransactionFlushNeeded);
3706 break;
3707 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003708 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003709 const bool frameNumberChanged = state.bufferData->flags.test(
3710 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003711 if (frameNumberChanged) {
3712 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3713 } else {
3714 // Barrier function only used for BBQ which always includes a frame number
3715 bufferLayersReadyToPresent[state.surface] =
3716 std::numeric_limits<uint64_t>::max();
3717 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003718 });
3719 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3720 if (appliedUnsignaled) {
3721 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3722 }
3723
3724 transactions.emplace_back(std::move(transaction));
3725 transactionQueue.pop();
3726 }
3727
3728 if (transactionQueue.empty()) {
3729 it = mPendingTransactionQueues.erase(it);
3730 mTransactionQueueCV.broadcast();
3731 } else {
3732 it = std::next(it, 1);
3733 }
3734 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003735 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003736}
3737
Vishnu Nair7891e962021-11-11 12:07:21 -08003738bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003739 // to prevent onHandleDestroyed from being called while the lock is held,
3740 // we must keep a copy of the transactions (specifically the composer
3741 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003742 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003743 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003744 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003745 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003746 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003747 Mutex::Autolock _l(mStateLock);
3748 {
3749 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003750
Robert Carr79dc06a2022-02-22 15:28:59 -08003751 int lastTransactionsPendingBarrier = 0;
3752 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003753 // First collect transactions from the pending transaction queues.
3754 // We are not allowing unsignaled buffers here as we want to
3755 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003756 transactionsPendingBarrier =
3757 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3758 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003759
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003760 // Second, collect transactions from the transaction queue.
3761 // Here as well we are not allowing unsignaled buffers for the same
3762 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003763 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003764 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003765 const bool pendingTransactions =
3766 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003767 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003768 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003769 if (pendingTransactions) {
3770 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003771 return TransactionReadiness::NotReady;
3772 }
3773
3774 return transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3775 transaction.isAutoTimestamp,
3776 transaction.desiredPresentTime,
3777 transaction.originUid, transaction.states,
3778 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003779 transactions.size(),
3780 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003781 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003782 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003783 if (ready != TransactionReadiness::Ready) {
3784 if (ready == TransactionReadiness::NotReadyBarrier) {
3785 transactionsPendingBarrier++;
3786 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003787 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003788 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003789 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003790 const bool frameNumberChanged = state.bufferData->flags.test(
3791 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003792 if (frameNumberChanged) {
3793 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3794 } else {
3795 // Barrier function only used for BBQ which always includes a frame number.
3796 // This value only used for barrier logic.
3797 bufferLayersReadyToPresent[state.surface] =
3798 std::numeric_limits<uint64_t>::max();
3799 }
Xiang Wang76236e12022-03-22 17:25:30 +00003800 });
Ady Abraham9dada822022-02-03 10:26:59 -08003801 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003802 }
ramindani4d48f902021-09-20 21:07:45 +00003803 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003804 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003805 }
Arthur Hung58144272021-01-16 03:43:53 +00003806
Robert Carr79dc06a2022-02-22 15:28:59 -08003807 // Transactions with a buffer pending on a barrier may be on a different applyToken
3808 // than the transaction which satisfies our barrier. In fact this is the exact use case
3809 // that the primitive is designed for. This means we may first process
3810 // the barrier dependent transaction, determine it ineligible to complete
3811 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3812 // The barrier dependent transaction was eligible to be presented in this frame
3813 // but we would have prevented it without case. To fix this we continually
3814 // loop through flushPendingTransactionQueues until we perform an iteration
3815 // where the number of transactionsPendingBarrier doesn't change. This way
3816 // we can continue to resolve dependency chains of barriers as far as possible.
3817 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3818 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3819 transactionsPendingBarrier =
3820 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3821 applyTokensWithUnsignaledTransactions,
3822 /*tryApplyUnsignaled*/ false);
3823 }
3824
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003825 // We collected all transactions that could apply without latching unsignaled buffers.
3826 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3827 // transactions that were not applied and try to apply them unsignaled.
3828 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003829 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3830 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003831 }
3832
Vishnu Nair7891e962021-11-11 12:07:21 -08003833 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003834 }
ramindani4d48f902021-09-20 21:07:45 +00003835 }
3836}
3837
Vishnu Nair7891e962021-11-11 12:07:21 -08003838bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3839 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003840 bool needsTraversal = false;
3841 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003842 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003843 needsTraversal |=
3844 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3845 transaction.displays, transaction.flags,
3846 transaction.inputWindowCommands,
3847 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3848 transaction.buffer, transaction.postTime,
3849 transaction.permissions, transaction.hasListenerCallbacks,
3850 transaction.listenerCallbacks, transaction.originPid,
3851 transaction.originUid, transaction.id);
3852 if (transaction.transactionCommittedSignal) {
3853 mTransactionCommittedSignals.emplace_back(
3854 std::move(transaction.transactionCommittedSignal));
3855 }
3856 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003857
Dominik Laskowski46471e62022-01-14 15:34:03 -08003858 if (mTransactionTracing) {
3859 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003860 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003861 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003862}
3863
3864bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003865 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003866 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003867}
3868
Ady Abraham8db10102021-03-15 17:19:23 -07003869bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3870 // The amount of time SF can delay a frame if it is considered early based
3871 // on the VsyncModulator::VsyncConfig::appWorkDuration
3872 constexpr static std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3873
3874 const auto currentVsyncPeriod = mScheduler->getDisplayStatInfo(systemTime()).vsyncPeriod;
3875 const auto earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
3876
3877 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3878 if (!prediction.has_value()) {
3879 return false;
3880 }
3881
3882 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3883 kEarlyLatchMaxThreshold.count()) {
3884 return false;
3885 }
3886
3887 return prediction->presentTime >= expectedPresentTime &&
3888 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3889}
Ady Abraham9dada822022-02-03 10:26:59 -08003890bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003891 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003892 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3893 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3894 return false;
3895 }
Ady Abraham8db10102021-03-15 17:19:23 -07003896
Ady Abraham9dada822022-02-03 10:26:59 -08003897 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3898 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3899 return true;
3900 }
3901
3902 // We only want to latch unsignaled when a single layer is updated in this
3903 // transaction (i.e. not a blast sync transaction).
3904 if (numStates != 1) {
3905 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3906 return false;
3907 }
3908
Ady Abraham2739e832022-02-14 17:42:00 -08003909 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3910 if (totalTXapplied > 0) {
3911 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3912 __func__, totalTXapplied);
3913 return false;
3914 }
3915
3916 // We don't want to latch unsignaled if are in early / client composition
3917 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3918 // or window animations being slow.
3919 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3920 if (!isDefaultVsyncConfig) {
3921 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3922 __func__);
3923 return false;
3924 }
Ady Abraham9dada822022-02-03 10:26:59 -08003925 }
3926
3927 if (!layer->simpleBufferUpdate(state)) {
3928 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3929 return false;
3930 }
3931
3932 ALOGV("%s: true", __func__);
3933 return true;
3934}
3935
3936auto SurfaceFlinger::transactionIsReadyToBeApplied(
Ady Abraham43752eb2021-03-04 16:24:25 -08003937 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003938 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003939 const std::unordered_map<
3940 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003941 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003942 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003943 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003944 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3945 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003946 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08003947 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003948 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003949 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003950 }
3951
Ady Abraham5690bda2021-03-12 15:01:18 -08003952 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
3953 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003954 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003955 }
3956
Ady Abraham8db10102021-03-15 17:19:23 -07003957 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3958 // present time of this transaction.
3959 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
3960 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08003961 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07003962 }
3963
Ady Abraham9dada822022-02-03 10:26:59 -08003964 bool fenceUnsignaled = false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003965 for (const ComposerState& state : states) {
3966 const layer_state_t& s = state.state;
Ady Abrahamf20c1922020-12-21 18:39:01 -08003967 sp<Layer> layer = nullptr;
3968 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07003969 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003970 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08003971 ALOGW("Transaction with buffer, but no Layer?");
3972 continue;
3973 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003974 if (!layer) {
3975 continue;
3976 }
Ady Abraham43752eb2021-03-04 16:24:25 -08003977
Robert Carr79dc06a2022-02-22 15:28:59 -08003978 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
3979 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
3980 const bool willApplyBarrierFrame =
3981 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
3982 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
3983 if (!willApplyBarrierFrame) {
3984 ATRACE_NAME("NotReadyBarrier");
3985 return TransactionReadiness::NotReadyBarrier;
3986 }
3987 }
3988
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003989 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08003990 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08003991 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
3992 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08003993
3994 const bool acquireFenceChanged = s.bufferData &&
3995 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
3996 s.bufferData->acquireFence;
3997 fenceUnsignaled = fenceUnsignaled ||
3998 (acquireFenceChanged &&
3999 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
4000
4001 if (fenceUnsignaled && !allowLatchUnsignaled) {
4002 ATRACE_NAME("fence unsignaled");
4003 return TransactionReadiness::NotReady;
4004 }
4005
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004006 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08004007 // If backpressure is enabled and we already have a buffer to commit, keep the
4008 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004009 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4010 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004011 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004012 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004013 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004014 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004015 }
4016 }
Ady Abraham9dada822022-02-03 10:26:59 -08004017 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004018}
4019
arthurhungf1b7c7b2021-03-03 17:42:23 +08004020void SurfaceFlinger::queueTransaction(TransactionState& state) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004021 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004022
arthurhungf1b7c7b2021-03-03 17:42:23 +08004023 // Generate a CountDownLatch pending state if this is a synchronous transaction.
4024 if ((state.flags & eSynchronous) || state.inputWindowCommands.syncInputWindows) {
4025 state.transactionCommittedSignal = std::make_shared<CountDownLatch>(
Arthur Hung2274a312021-04-28 15:13:06 +00004026 (state.inputWindowCommands.syncInputWindows
4027 ? (CountDownLatch::eSyncInputWindows | CountDownLatch::eSyncTransaction)
4028 : CountDownLatch::eSyncTransaction));
arthurhungf1b7c7b2021-03-03 17:42:23 +08004029 }
4030
ramindani4d48f902021-09-20 21:07:45 +00004031 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004032 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4033
Ady Abrahame46243a2021-02-23 19:33:49 -08004034 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004035 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4036 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004037 return TransactionSchedule::Late;
4038 }(state.flags);
4039
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004040 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4041
4042 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004043}
4044
arthurhungf1b7c7b2021-03-03 17:42:23 +08004045void SurfaceFlinger::waitForSynchronousTransaction(
4046 const CountDownLatch& transactionCommittedSignal) {
4047 // applyTransactionState is called on the main SF thread. While a given process may wish
4048 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4049 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004050 if (!transactionCommittedSignal.wait_until(
4051 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004052 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004053 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004054}
Ady Abrahame46243a2021-02-23 19:33:49 -08004055
Arthur Hung2274a312021-04-28 15:13:06 +00004056void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004057 for (auto it = mTransactionCommittedSignals.begin();
4058 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004059 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004060 it = mTransactionCommittedSignals.erase(it);
4061 } else {
4062 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004063 }
4064 }
4065}
4066
chaviw308ddba2020-08-11 16:23:51 -07004067status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004068 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004069 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4070 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004071 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004072 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004073 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004074
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004075 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004076 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4077 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004078 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4079 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004080 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004081 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004082 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004083 }
4084
Leon Scroggins9a20f722021-12-28 14:43:12 +00004085 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004086 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004087 }
4088
Robert Carrde6d7b42022-01-07 18:23:06 -08004089 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004090 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4091 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4092 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004093 }
4094
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004095 const int64_t postTime = systemTime();
4096
4097 IPCThreadState* ipc = IPCThreadState::self();
4098 const int originPid = ipc->getCallingPid();
4099 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004100 TransactionState state{frameTimelineInfo, states,
4101 displays, flags,
4102 applyToken, inputWindowCommands,
4103 desiredPresentTime, isAutoTimestamp,
4104 uncacheBuffer, postTime,
4105 permissions, hasListenerCallbacks,
4106 listenerCallbacks, originPid,
4107 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004108
4109 // Check for incoming buffer updates and increment the pending buffer count.
4110 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4111 mBufferCountTracker.increment(state.surface->localBinder());
4112 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004113
Dominik Laskowski46471e62022-01-14 15:34:03 -08004114 if (mTransactionTracing) {
4115 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004116 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004117 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004118
arthurhungf1b7c7b2021-03-03 17:42:23 +08004119 // Check the pending state to make sure the transaction is synchronous.
4120 if (state.transactionCommittedSignal) {
4121 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004122 }
4123
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004124 return NO_ERROR;
4125}
Marissa Wall713b63f2018-10-17 15:42:43 -07004126
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004127bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004128 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004129 const Vector<DisplayState>& displays, uint32_t flags,
4130 const InputWindowCommands& inputWindowCommands,
4131 const int64_t desiredPresentTime, bool isAutoTimestamp,
4132 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004133 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004134 bool hasListenerCallbacks,
4135 const std::vector<ListenerCallbacks>& listenerCallbacks,
4136 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004137 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004138 for (const DisplayState& display : displays) {
4139 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004140 }
4141
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004142 // start and end registration for listeners w/ no surface so they can get their callback. Note
4143 // that listeners with SurfaceControls will start registration during setClientStateLocked
4144 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004145 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004146 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004147 }
4148
Marissa Walle2ffb422018-10-12 11:33:52 -07004149 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004150 for (int i = 0; i < states.size(); i++) {
4151 ComposerState& state = states.editItemAt(i);
4152 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004153 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004154 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004155 if (const auto layer = fromHandle(state.state.surface).promote()) {
4156 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004157 mScheduler->recordLayerHistory(layer.get(),
4158 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004159 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004160 }
4161 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004162 }
4163
Marissa Walle2ffb422018-10-12 11:33:52 -07004164 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004165
Robert Carrde6d7b42022-01-07 18:23:06 -08004166 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004167 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4168 } else if (!inputWindowCommands.empty()) {
4169 ALOGE("Only privileged callers are allowed to send input commands.");
4170 }
chaviw273171b2018-12-26 11:46:30 -08004171
Marissa Wall947d34e2019-03-29 14:03:53 -07004172 if (uncacheBuffer.isValid()) {
4173 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004174 }
4175
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004176 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4177 // anyway. This can be used as a flush mechanism for previous async transactions.
4178 // Empty animation transaction can be used to simulate back-pressure, so also force a
4179 // transaction for empty animation transactions.
4180 if (transactionFlags == 0 &&
4181 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004182 transactionFlags = eTransactionNeeded;
4183 }
4184
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004185 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004186 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004187 if (mInterceptor->isEnabled()) {
4188 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004189 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004190 }
4191
Arthur Hung58144272021-01-16 03:43:53 +00004192 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4193 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4194 if (transactionFlags & eTraversalNeeded) {
4195 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004196 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004197 }
Arthur Hung58144272021-01-16 03:43:53 +00004198 if (transactionFlags) {
4199 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004200 }
4201
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004202 if (flags & eAnimation) {
4203 mAnimTransactionPending = true;
4204 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004205 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004206
4207 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004208}
4209
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004210uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4211 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4212 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004213
Mathias Agopiane57f2922012-08-09 16:29:12 -07004214 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004215 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4216
4217 const uint32_t what = s.what;
4218 if (what & DisplayState::eSurfaceChanged) {
4219 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4220 state.surface = s.surface;
4221 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004222 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004223 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004224 if (what & DisplayState::eLayerStackChanged) {
4225 if (state.layerStack != s.layerStack) {
4226 state.layerStack = s.layerStack;
4227 flags |= eDisplayTransactionNeeded;
4228 }
4229 }
Evan Rosky2239b372021-05-20 13:43:47 -07004230 if (what & DisplayState::eFlagsChanged) {
4231 if (state.flags != s.flags) {
4232 state.flags = s.flags;
4233 flags |= eDisplayTransactionNeeded;
4234 }
4235 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004236 if (what & DisplayState::eDisplayProjectionChanged) {
4237 if (state.orientation != s.orientation) {
4238 state.orientation = s.orientation;
4239 flags |= eDisplayTransactionNeeded;
4240 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004241 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4242 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004243 flags |= eDisplayTransactionNeeded;
4244 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004245 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4246 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004247 flags |= eDisplayTransactionNeeded;
4248 }
4249 }
4250 if (what & DisplayState::eDisplaySizeChanged) {
4251 if (state.width != s.width) {
4252 state.width = s.width;
4253 flags |= eDisplayTransactionNeeded;
4254 }
4255 if (state.height != s.height) {
4256 state.height = s.height;
4257 flags |= eDisplayTransactionNeeded;
4258 }
4259 }
4260
Mathias Agopiane57f2922012-08-09 16:29:12 -07004261 return flags;
4262}
4263
Steven Thomasd4071902020-03-24 16:02:53 -07004264bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004265 IPCThreadState* ipc = IPCThreadState::self();
4266 const int pid = ipc->getCallingPid();
4267 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004268 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004269 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4270 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004271 return false;
4272 }
4273 return true;
4274}
4275
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004276uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004277 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004278 int64_t desiredPresentTime, bool isAutoTimestamp,
4279 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004280 layer_state_t& s = composerState.state;
4281 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004282
4283 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004284 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004285 // Starts a registration but separates the callback ids according to callback type. This
4286 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004287 // note that startRegistration will not re-register if the listener has
4288 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004289
4290 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4291 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004292 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004293 }
4294
4295 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4296 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004297 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004298 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004299 }
4300
arthurhungdba591c2021-02-08 17:28:49 +08004301 const uint64_t what = s.what;
4302 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004303 sp<Layer> layer = nullptr;
4304 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004305 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004306 } else {
4307 // The client may provide us a null handle. Treat it as if the layer was removed.
4308 ALOGW("Attempt to set client state with a null layer handle");
4309 }
chaviw8b3871a2017-11-01 17:41:01 -07004310 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004311 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004312 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004313 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004314 }
chaviw8b3871a2017-11-01 17:41:01 -07004315 return 0;
4316 }
4317
Valerie Hau871d6352020-01-29 08:44:02 -08004318 // Only set by BLAST adapter layers
4319 if (what & layer_state_t::eProducerDisconnect) {
4320 layer->onDisconnect();
4321 }
4322
chaviw8b3871a2017-11-01 17:41:01 -07004323 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004324 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004325 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004326 }
chaviw8b3871a2017-11-01 17:41:01 -07004327 }
4328 if (what & layer_state_t::eLayerChanged) {
4329 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004330 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004331 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004332 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004333 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004334 mCurrentState.layersSortedByZ.removeAt(idx);
4335 mCurrentState.layersSortedByZ.add(layer);
4336 // we need traversal (state changed)
4337 // AND transaction (list changed)
4338 flags |= eTransactionNeeded|eTraversalNeeded;
4339 }
chaviw8b3871a2017-11-01 17:41:01 -07004340 } else {
4341 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004342 flags |= eTransactionNeeded|eTraversalNeeded;
4343 }
4344 }
chaviw8b3871a2017-11-01 17:41:01 -07004345 }
4346 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004347 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004348 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004349 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4350 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004351 if (p == nullptr) {
4352 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004353 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004354 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004355 mCurrentState.layersSortedByZ.removeAt(idx);
4356 mCurrentState.layersSortedByZ.add(layer);
4357 // we need traversal (state changed)
4358 // AND transaction (list changed)
4359 flags |= eTransactionNeeded|eTraversalNeeded;
4360 }
4361 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004362 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004363 flags |= eTransactionNeeded|eTraversalNeeded;
4364 }
chaviw8b3871a2017-11-01 17:41:01 -07004365 }
4366 }
4367 if (what & layer_state_t::eSizeChanged) {
4368 if (layer->setSize(s.w, s.h)) {
4369 flags |= eTraversalNeeded;
4370 }
4371 }
4372 if (what & layer_state_t::eAlphaChanged) {
4373 if (layer->setAlpha(s.alpha))
4374 flags |= eTraversalNeeded;
4375 }
4376 if (what & layer_state_t::eColorChanged) {
4377 if (layer->setColor(s.color))
4378 flags |= eTraversalNeeded;
4379 }
Peiyong Lind3788632018-09-18 16:01:31 -07004380 if (what & layer_state_t::eColorTransformChanged) {
4381 if (layer->setColorTransform(s.colorTransform)) {
4382 flags |= eTraversalNeeded;
4383 }
4384 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004385 if (what & layer_state_t::eBackgroundColorChanged) {
4386 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4387 flags |= eTraversalNeeded;
4388 }
4389 }
chaviw8b3871a2017-11-01 17:41:01 -07004390 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004391 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004392 }
4393 if (what & layer_state_t::eTransparentRegionChanged) {
4394 if (layer->setTransparentRegionHint(s.transparentRegion))
4395 flags |= eTraversalNeeded;
4396 }
4397 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004398 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004399 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004400 if (what & layer_state_t::eCornerRadiusChanged) {
4401 if (layer->setCornerRadius(s.cornerRadius))
4402 flags |= eTraversalNeeded;
4403 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004404 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004405 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4406 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004407 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004408 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4409 }
chaviw8b3871a2017-11-01 17:41:01 -07004410 if (what & layer_state_t::eLayerStackChanged) {
4411 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4412 // We only allow setting layer stacks for top level layers,
4413 // everything else inherits layer stack from its parent.
4414 if (layer->hasParent()) {
4415 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004416 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004417 } else if (idx < 0) {
4418 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004419 "that also does not appear in the top level layer list. Something"
4420 " has gone wrong.",
4421 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004422 } else if (layer->setLayerStack(s.layerStack)) {
4423 mCurrentState.layersSortedByZ.removeAt(idx);
4424 mCurrentState.layersSortedByZ.add(layer);
4425 // we need traversal (state changed)
4426 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004427 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004428 }
4429 }
Marissa Wall61c58622018-07-18 10:12:20 -07004430 if (what & layer_state_t::eTransformChanged) {
4431 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4432 }
4433 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4434 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4435 flags |= eTraversalNeeded;
4436 }
4437 if (what & layer_state_t::eCropChanged) {
4438 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4439 }
Marissa Wall61c58622018-07-18 10:12:20 -07004440 if (what & layer_state_t::eDataspaceChanged) {
4441 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4442 }
4443 if (what & layer_state_t::eHdrMetadataChanged) {
4444 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4445 }
4446 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4447 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4448 }
4449 if (what & layer_state_t::eApiChanged) {
4450 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4451 }
4452 if (what & layer_state_t::eSidebandStreamChanged) {
4453 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4454 }
Robert Carr720e5062018-07-30 17:45:14 -07004455 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004456 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4457 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004458 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004459 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004460 if (what & layer_state_t::eMetadataChanged) {
Vishnu Nairadf632b2021-01-07 14:05:08 -08004461 dequeueBufferTimestamp = s.metadata.getInt64(METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004462
4463 if (const int32_t gameMode = s.metadata.getInt32(METADATA_GAME_MODE, -1); gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004464 // The transaction will be received on the Task layer and needs to be applied to all
4465 // child layers. Child layers that are added at a later point will obtain the game mode
4466 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004467 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004468 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004469
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004470 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4471 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004472 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4473 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4474 flags |= eTraversalNeeded;
4475 }
4476 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004477 if (what & layer_state_t::eShadowRadiusChanged) {
4478 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4479 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004480 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004481 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004482 flags |= eTraversalNeeded;
4483 }
4484 }
Steven Thomas3172e202020-01-06 19:25:30 -08004485 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004486 const auto compatibility =
4487 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4488 const auto strategy =
4489 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004490
Robert Carrde6d7b42022-01-07 18:23:06 -08004491 if (layer->setFrameRate(
4492 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4493 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004494 }
Steven Thomas3172e202020-01-06 19:25:30 -08004495 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004496 if (what & layer_state_t::eFixedTransformHintChanged) {
4497 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4498 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4499 }
4500 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004501 if (what & layer_state_t::eAutoRefreshChanged) {
4502 layer->setAutoRefresh(s.autoRefresh);
4503 }
Sally Qi421ffb02022-03-21 19:41:33 -07004504 if (what & layer_state_t::eDimmingEnabledChanged) {
4505 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4506 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004507 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004508 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4509 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004510 }
4511 }
John Reckcdb4ed72021-02-04 13:39:33 -05004512 if (what & layer_state_t::eStretchChanged) {
4513 if (layer->setStretchEffect(s.stretchEffect)) {
4514 flags |= eTraversalNeeded;
4515 }
4516 }
chaviwf3f40fe2021-04-27 15:54:02 -05004517 if (what & layer_state_t::eBufferCropChanged) {
4518 if (layer->setBufferCrop(s.bufferCrop)) {
4519 flags |= eTraversalNeeded;
4520 }
4521 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004522 if (what & layer_state_t::eDestinationFrameChanged) {
4523 if (layer->setDestinationFrame(s.destinationFrame)) {
4524 flags |= eTraversalNeeded;
4525 }
4526 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004527 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004528 if (layer->setDropInputMode(s.dropInputMode)) {
4529 flags |= eTraversalNeeded;
4530 mInputInfoChanged = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004531 }
4532 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004533 // This has to happen after we reparent children because when we reparent to null we remove
4534 // child layers from current state and remove its relative z. If the children are reparented in
4535 // the same transaction, then we have to make sure we reparent the children first so we do not
4536 // lose its relative z order.
4537 if (what & layer_state_t::eReparent) {
4538 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004539 auto parentHandle = (s.parentSurfaceControlForChild)
4540 ? s.parentSurfaceControlForChild->getHandle()
4541 : nullptr;
4542 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004543 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004544 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004545 mCurrentState.layersSortedByZ.remove(layer);
4546 }
4547 flags |= eTransactionNeeded | eTraversalNeeded;
4548 }
4549 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004550 std::vector<sp<CallbackHandle>> callbackHandles;
4551 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4552 for (auto& [listener, callbackIds] : filteredListeners) {
4553 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4554 }
4555 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004556
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004557 if (what & layer_state_t::eBufferChanged) {
4558 std::shared_ptr<renderengine::ExternalTexture> buffer =
4559 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4560 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4561 dequeueBufferTimestamp, frameTimelineInfo)) {
4562 flags |= eTraversalNeeded;
4563 }
Ady Abraham8db10102021-03-15 17:19:23 -07004564 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4565 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004566 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004567
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004568 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004569 // Do not put anything that updates layer state or modifies flags after
4570 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004571 return flags;
4572}
4573
chaviw273171b2018-12-26 11:46:30 -08004574uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004575 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004576 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004577}
4578
Vishnu Nair84125ac2021-12-02 08:47:48 -08004579status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4580 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4581 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004582 if (!mirrorFromHandle) {
4583 return NAME_NOT_FOUND;
4584 }
4585
4586 sp<Layer> mirrorLayer;
4587 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004588 {
4589 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004590 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004591 if (!mirrorFrom) {
4592 return NAME_NOT_FOUND;
4593 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004594 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004595 if (result != NO_ERROR) {
4596 return result;
4597 }
4598
Robert Carr6a0382d2021-07-01 15:57:17 -07004599 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004600 }
4601
Ady Abraham9f0a4002020-10-05 15:47:26 -07004602 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004603 if (mTransactionTracing) {
4604 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4605 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004606 }
4607 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004608 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004609}
4610
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004611status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004612 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4613 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004614 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4615 "Expected only one of parentLayer or parentHandle to be non-null. "
4616 "Programmer error?");
4617
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004618 status_t result = NO_ERROR;
4619
4620 sp<Layer> layer;
4621
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004622 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004623 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004624 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004625 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004626 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4627 if (pendingBufferCounter) {
4628 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004629 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004630 pendingBufferCounter);
4631 }
4632 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004633 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004634 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004635 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004636 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004637 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004638 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004639 default:
4640 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004641 break;
4642 }
4643
Dan Stoza7d89d062015-04-30 13:29:25 -07004644 if (result != NO_ERROR) {
4645 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004646 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004647
Vishnu Nair858a3b42022-01-12 20:42:28 -08004648 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004649 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4650 if (parentHandle != nullptr && parent == nullptr) {
4651 ALOGE("Invalid parent handle %p.", parentHandle.get());
4652 addToRoot = false;
4653 }
4654 if (parentLayer != nullptr) {
4655 addToRoot = false;
4656 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004657
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004658 int parentId = -1;
4659 // We can safely promote the layer in binder thread because we have a strong reference
4660 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4661 sp<Layer> parentSp = parent.promote();
4662 if (parentSp != nullptr) {
4663 parentId = parentSp->getSequence();
4664 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004665 if (mTransactionTracing) {
4666 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4667 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004668 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004669
Vishnu Nair047fb332021-12-09 09:54:36 -08004670 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4671 if (result != NO_ERROR) {
4672 return result;
4673 }
4674
Ady Abraham9f0a4002020-10-05 15:47:26 -07004675 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004676 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004677}
4678
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004679status_t SurfaceFlinger::createBufferQueueLayer(LayerCreationArgs& args, PixelFormat& format,
Evan Roskya1f1e152019-01-24 16:17:46 -08004680 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004681 sp<IGraphicBufferProducer>* gbp,
4682 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004683 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004684 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004685 case PIXEL_FORMAT_TRANSPARENT:
4686 case PIXEL_FORMAT_TRANSLUCENT:
4687 format = PIXEL_FORMAT_RGBA_8888;
4688 break;
4689 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004690 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004691 break;
4692 }
4693
chaviwb4c6e582019-08-16 14:35:07 -07004694 sp<BufferQueueLayer> layer;
chaviwb4c6e582019-08-16 14:35:07 -07004695 args.textureName = getNewTexture();
4696 {
4697 // Grab the SF state lock during this since it's the only safe way to access
4698 // RenderEngine when creating a BufferLayerConsumer
4699 // TODO: Check if this lock is still needed here
4700 Mutex::Autolock lock(mStateLock);
4701 layer = getFactory().createBufferQueueLayer(args);
4702 }
4703
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004704 status_t err = layer->setDefaultBufferProperties(0, 0, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004705 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004706 *handle = layer->getHandle();
4707 *gbp = layer->getProducer();
4708 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004709 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004710
Marissa Wallfd668622018-05-10 10:21:13 -07004711 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004712 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004713}
4714
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004715status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004716 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004717 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004718 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004719 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004720 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004721}
4722
Vishnu Nair84125ac2021-12-02 08:47:48 -08004723status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004724 sp<Layer>* outLayer) {
4725 *outLayer = getFactory().createEffectLayer(args);
4726 *handle = (*outLayer)->getHandle();
4727 return NO_ERROR;
4728}
4729
Vishnu Nair84125ac2021-12-02 08:47:48 -08004730status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004731 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004732 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004733 *handle = (*outLayer)->getHandle();
4734 return NO_ERROR;
4735}
4736
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004737void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004738 mLayersPendingRemoval.add(layer);
4739 mLayersRemoved = true;
4740 setTransactionFlags(eTransactionNeeded);
4741}
4742
Vishnu Nairf9096652021-07-20 18:49:42 -07004743void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004744 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004745 // If a layer has a parent, we allow it to out-live it's handle
4746 // with the idea that the parent holds a reference and will eventually
4747 // be cleaned up. However no one cleans up the top-level so we do so
4748 // here.
Vishnu Nair14d218b2021-07-13 13:57:39 -07004749 if (layer->isAtRoot()) {
4750 layer->setIsAtRoot(false);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004751 mCurrentState.layersSortedByZ.remove(layer);
4752 }
4753 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004754 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004755 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004756 if (mTransactionTracing) {
4757 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004758 }
Rob Carr4bba3702018-10-08 21:53:30 +00004759}
4760
Mathias Agopianb60314a2012-04-10 22:09:54 -07004761// ---------------------------------------------------------------------------
4762
Andy McFadden13a082e2012-08-24 10:16:42 -07004763void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004764 const auto display = getDefaultDisplayDeviceLocked();
4765 if (!display) return;
4766
4767 const sp<IBinder> token = display->getDisplayToken().promote();
4768 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004769
Jesse Hall01e29052013-02-19 16:13:35 -08004770 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004771 Vector<ComposerState> state;
4772 Vector<DisplayState> displays;
4773 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004774 d.what = DisplayState::eDisplayProjectionChanged |
4775 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004776 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004777 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004778 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004779 d.orientedDisplaySpaceRect.makeInvalid();
4780 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004781 d.width = 0;
4782 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004783 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004784
Vishnu Nair9a69a042021-06-18 13:19:49 -07004785 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004786
4787 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004788 // It should be on the main thread, apply it directly.
4789 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004790 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004791 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004792
Peiyong Lin65248e02020-04-18 21:15:07 -07004793 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004794 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004795 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004796 mActiveDisplayTransformHint = display->getTransformHint();
Brian Andersond0010582017-03-07 13:20:31 -08004797 // Use phase of 0 since phase is not known.
4798 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004799 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004800 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004801}
4802
4803void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004804 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004805 static_cast<void>(
4806 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004807}
4808
Peiyong Lin65248e02020-04-18 21:15:07 -07004809void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004810 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004811 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004812 return;
4813 }
4814
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004815 const auto displayId = display->getPhysicalId();
4816 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004817
Peiyong Lin65248e02020-04-18 21:15:07 -07004818 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004819 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004820 return;
4821 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004822
Ady Abraham4f960d12021-10-13 16:59:49 -07004823 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4824 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4825 activeDisplay->isPoweredOn()) {
4826 ALOGW("Trying to change power mode on non active display while the active display is ON");
4827 }
4828
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004829 display->setPowerMode(mode);
4830
Lloyd Pique4dccc412018-01-22 17:21:36 -08004831 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004832 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004833 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004834 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004835 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004836 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004837 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004838 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004839 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004840 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4841 // We can merge the syscall later.
4842 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4843 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4844 }
Martin Liu4a322352020-03-24 21:30:38 +08004845 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4846 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4847 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004848 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004849 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004850 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004851 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004852 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004853 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004854
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004855 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004856 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004857 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004858 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004859 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004860 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4861 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004862 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004863 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4864 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4865 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004866 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004867 mScheduler->disableHardwareVsync(true);
4868 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004869 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004870
Ady Abraham27c70212019-06-11 10:52:26 -07004871 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004872 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004873
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004874 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004875 mVisibleRegionsDirty = true;
4876 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004877 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004878 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004879 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004880 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004881 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004882 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004883 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004884 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004885 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004886 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004887 mScheduler->disableHardwareVsync(true);
4888 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004889 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004890 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004891 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004892 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004893 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004894 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004895
Ady Abrahamadc914c2021-10-13 17:04:27 -07004896 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004897 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004898 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004899 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004900 }
4901
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004902 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004903}
4904
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004905void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004906 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004907 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004908 if (!display) {
4909 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4910 displayToken.get());
4911 } else if (display->isVirtual()) {
4912 ALOGW("Attempt to set power mode %d for virtual display", mode);
4913 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004914 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004915 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004916 });
4917
4918 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004919}
4920
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004921status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004922 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004923
Mathias Agopianbd115332013-04-18 16:41:04 -07004924 IPCThreadState* ipc = IPCThreadState::self();
4925 const int pid = ipc->getCallingPid();
4926 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004927
Mathias Agopianbd115332013-04-18 16:41:04 -07004928 if ((uid != AID_SHELL) &&
4929 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004930 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4931 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004932 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004933 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004934 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004935 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004936 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004937 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4938 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4939 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4940 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004941 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004942 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4943 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004944 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004945 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004946 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004947 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004948
Dominik Laskowskic2867142019-01-21 11:33:38 -08004949 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004950
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004951 bool dumpLayers = true;
4952 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004953 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004954 if (!lock.locked()) {
4955 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4956 strerror(-lock.status), lock.status);
4957 }
4958
4959 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4960 (it->second)(args, asProto, result);
4961 dumpLayers = false;
4962 } else if (!asProto) {
4963 dumpAllLocked(args, result);
4964 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004965 }
4966
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004967 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004968 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05004969 LayersTraceProto* layersTrace = traceFileProto.add_entry();
4970 LayersProto layersProto = dumpProtoFromMainThread();
4971 layersTrace->mutable_layers()->Swap(&layersProto);
4972 dumpDisplayProto(*layersTrace);
4973
Dominik Laskowski46470112019-08-02 13:13:11 -07004974 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05004975 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07004976 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004977 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05004978 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07004979 result.append(LayerProtoParser::layerTreeToString(layerTree));
4980 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004981 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004982 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004983 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004984 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004985 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004986 return NO_ERROR;
4987}
4988
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004989status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08004990 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004991 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004992 if (mTransactionTracing) {
4993 mTransactionTracing->writeToFile();
4994 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004995 }
4996
4997 return doDump(fd, DumpArgs(), asProto);
4998}
4999
Dominik Laskowskic2867142019-01-21 11:33:38 -08005000void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005001 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005002 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005003}
5004
Dominik Laskowskic2867142019-01-21 11:33:38 -08005005void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07005006 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005007
Dominik Laskowskic2867142019-01-21 11:33:38 -08005008 if (args.size() > 1) {
5009 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08005010 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005011 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005012 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005013 }
Robert Carr2047fae2016-11-28 14:09:09 -08005014 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005015 } else {
5016 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005017 }
5018}
5019
Dominik Laskowskic2867142019-01-21 11:33:38 -08005020void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005021 const bool clearAll = args.size() < 2;
5022 const auto name = clearAll ? String8() : String8(args[1]);
5023
Edgar Arriaga844fa672020-01-16 14:21:42 -08005024 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005025 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005026 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005027 }
Robert Carr2047fae2016-11-28 14:09:09 -08005028 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005029
Svetoslavd85084b2014-03-20 10:28:31 -07005030 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005031}
5032
Dominik Laskowskic2867142019-01-21 11:33:38 -08005033void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5034 mTimeStats->parseArgs(asProto, args, result);
5035}
5036
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005037void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5038 mFrameTimeline->parseArgs(args, result);
5039}
5040
Jamie Gennis6547ff42013-07-16 20:12:42 -07005041void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005042 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005043 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005044 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005045
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005046 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005047}
5048
Yiwei Zhang5434a782018-12-05 18:06:32 -08005049void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005050 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005051
Yiwei Zhang5434a782018-12-05 18:06:32 -08005052 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5053 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005054 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5055 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005056 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5057 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5058 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005059 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005060}
5061
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005062void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005063 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005064
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005065 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005066 result.append("\n");
5067
Ady Abraham8287e852020-08-12 14:44:58 -07005068 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005069 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005070 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005071 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005072
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005073 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5074 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005075
Ana Krulecc2870422019-01-29 19:00:58 -08005076 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005077 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005078 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5079 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005080}
5081
Dan Stoza269dc4d2021-01-15 15:07:43 -08005082void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5083 for (const auto& [token, display] : mDisplays) {
5084 const auto compositionDisplay = display->getCompositionDisplay();
5085 compositionDisplay->dumpPlannerInfo(args, result);
5086 }
5087}
5088
Yiwei Zhang5434a782018-12-05 18:06:32 -08005089void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5090 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005091 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5092 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005093 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005094 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005095 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005096 }
David Sodman4a36e932017-11-07 14:29:47 -08005097 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005098 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005099 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005100 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5101 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005102}
5103
Yiwei Zhang5434a782018-12-05 18:06:32 -08005104void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
5105 result.append("Layer frame timestamps:\n");
Josh Chienedaa9132020-12-04 18:30:46 +08005106 // Traverse all layers to dump frame-events for each layer
5107 mCurrentState.traverseInZOrder(
5108 [&] (Layer* layer) { layer->dumpFrameEvents(result); });
Brian Andersond6927fb2016-07-23 23:37:30 -07005109}
5110
Yiwei Zhang5434a782018-12-05 18:06:32 -08005111void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005112 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005113 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005114 if (!displayId) {
5115 continue;
5116 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005117 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005118 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005119 continue;
5120 }
5121
Yiwei Zhang5434a782018-12-05 18:06:32 -08005122 StringAppendF(&result,
5123 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5124 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005125 uint8_t port;
5126 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005127 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005128 result.append("no identification data\n");
5129 continue;
5130 }
5131
5132 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005133 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005134 continue;
5135 }
5136
5137 const auto edid = parseEdid(data);
5138 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005139 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005140 continue;
5141 }
5142
Yiwei Zhang5434a782018-12-05 18:06:32 -08005143 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005144 result.append(edid->displayName.data(), edid->displayName.length());
5145 result.append("\"\n");
5146 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005147}
5148
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005149void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5150 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005151 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005152 uint8_t port;
5153 DisplayIdentificationData data;
5154
5155 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5156 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5157 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5158 }
5159}
5160
Yiwei Zhang5434a782018-12-05 18:06:32 -08005161void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005162 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005163 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5164 StringAppendF(&result, "DisplayColorSetting: %s\n",
5165 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005166
5167 // TODO: print out if wide-color mode is active or not
5168
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005169 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005170 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005171 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005172 continue;
5173 }
5174
Yiwei Zhang5434a782018-12-05 18:06:32 -08005175 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005176 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005177 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005178 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005179 }
5180
Lloyd Pique32cbe282018-10-19 13:09:22 -07005181 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005182 StringAppendF(&result, " Current color mode: %s (%d)\n",
5183 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005184 }
5185 result.append("\n");
5186}
5187
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005188LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005189 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005190 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005191 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005192 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005193
chaviw1d044282017-09-27 12:19:28 -07005194 return layersProto;
5195}
5196
chaviw0a398992021-08-13 10:13:01 -05005197void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005198 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005199 DisplayProto* displayProto = layersTraceProto.add_displays();
5200 displayProto->set_id(display->getId().value);
5201 displayProto->set_name(display->getDisplayName());
5202 displayProto->set_layer_stack(display->getLayerStack().id);
5203 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5204 [&]() { return displayProto->mutable_size(); });
5205 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5206 return displayProto->mutable_layer_stack_space_rect();
5207 });
5208 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5209 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005210 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005211 }
5212}
5213
Alec Mouri6b9e9912020-01-21 10:50:24 -08005214void SurfaceFlinger::dumpHwc(std::string& result) const {
5215 getHwComposer().dump(result);
5216}
5217
Vishnu Nair0f085c62019-08-30 08:49:12 -07005218void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5219 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5220 // it.
5221 LayerProto* rootProto = layersProto.add_layers();
5222 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5223 rootProto->set_id(offscreenRootLayerId);
5224 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005225 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005226
5227 for (Layer* offscreenLayer : mOffscreenLayers) {
5228 // Add layer as child of the fake root
5229 rootProto->add_children(offscreenLayer->sequence);
5230
5231 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005232 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005233 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005234 }
5235}
5236
Vishnu Nair8406fd72019-07-30 11:29:31 -07005237LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005238 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005239}
5240
Vishnu Nair0f085c62019-08-30 08:49:12 -07005241void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005242 auto future = mScheduler->schedule([this] {
5243 std::string result;
5244 for (Layer* offscreenLayer : mOffscreenLayers) {
5245 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5246 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5247 }
5248 return result;
5249 });
5250
Vishnu Nair0f085c62019-08-30 08:49:12 -07005251 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005252 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005253}
5254
Dominik Laskowskic2867142019-01-21 11:33:38 -08005255void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5256 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005257 Colorizer colorizer(colorize);
5258
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005259 // figure out if we're stuck somewhere
5260 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005261 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005262 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5263
5264 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005265 * Dump library configuration.
5266 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005267
5268 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005269 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005270 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005271 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005272 result.append("\n");
5273
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005274 result.append("\nDisplay identification data:\n");
5275 dumpDisplayIdentificationData(result);
5276
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005277 result.append("\nWide-Color information:\n");
5278 dumpWideColorInfo(result);
5279
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005280 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005281 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005282 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005283 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005284 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005285
Andy McFadden41d67d72014-04-25 16:58:34 -07005286 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005287 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005288 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005289 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005290 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005291
Dan Stozab90cf072015-03-05 11:05:59 -08005292 dumpStaticScreenStats(result);
5293 result.append("\n");
5294
Alec Mouri40189b02019-03-05 15:07:54 -08005295 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5296 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5297 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005298
Andy McFadden4803b742012-09-24 19:07:20 -07005299 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005300 * Dump the visible layer list
5301 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005302 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005303 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005304 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005305
Chia-I Wu2f884132018-09-13 15:17:58 -07005306 {
Lloyd Pique207def92019-02-28 16:09:52 -08005307 StringAppendF(&result, "Composition layers\n");
5308 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005309 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005310 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005311
5312 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5313 layer->getDebugName() ? layer->getDebugName()
5314 : "<unknown>");
5315 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005316 });
5317 }
5318
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005319 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005320 * Dump Display state
5321 */
5322
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005323 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005324 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005325 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005326 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005327 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005328 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005329 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005330
5331 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005332 * Dump CompositionEngine state
5333 */
5334
5335 mCompositionEngine->dump(result);
5336
5337 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005338 * Dump SurfaceFlinger global state
5339 */
5340
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005341 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005342 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005343 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005344
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005345 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005346
Robert Carrbeba6f02021-02-10 21:06:27 -08005347 result.append("ClientCache state:\n");
5348 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005349 DebugEGLImageTracker::getInstance()->dump(result);
5350
Dominik Laskowski075d3172018-05-24 15:50:06 -07005351 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005352 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5353 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005354 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5355 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005356 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005357 StringAppendF(&result,
5358 " transaction-flags : %08x\n"
5359 " gpu_to_cpu_unsupported : %d\n",
5360 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005361
Marin Shalamanov045b7002021-01-07 16:56:24 +01005362 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005363 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005364 if (const auto activeMode = display->getActiveMode()) {
5365 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005366
5367 const auto dpi = activeMode->getDpi();
5368 xDpi = base::StringPrintf("%.2f", dpi.x);
5369 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005370 } else {
5371 fps = "unknown";
5372 xDpi = "unknown";
5373 yDpi = "unknown";
5374 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005375 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005376 " refresh-rate : %s\n"
5377 " x-dpi : %s\n"
5378 " y-dpi : %s\n",
5379 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005380 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005381
Yiwei Zhang5434a782018-12-05 18:06:32 -08005382 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005383
Dan Stozae22aec72016-08-01 13:20:59 -07005384 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005385 * Tracing state
5386 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005387 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005388
5389 result.append("\nTransaction tracing: ");
5390 if (mTransactionTracing) {
5391 result.append("enabled\n");
5392 mTransactionTracing->dump(result);
5393 } else {
5394 result.append("disabled\n");
5395 }
5396 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005397
5398 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005399 * HWC layer minidump
5400 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005401 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005402 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005403 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005404 continue;
5405 }
5406
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005407 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5408 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005409 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005410
5411 const DisplayDevice& ref = *display;
5412 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005413 result.append("\n");
5414 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005415
Ady Abraham2790e9f2021-04-28 13:14:20 -07005416 {
5417 DumpArgs plannerArgs;
5418 plannerArgs.add(); // first argument is ignored
5419 plannerArgs.add(String16("--layers"));
5420 dumpPlannerInfo(plannerArgs, result);
5421 }
5422
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005423 /*
5424 * Dump HWComposer state
5425 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005426 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005427 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005428 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005429 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005430 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005431 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005432
5433 /*
5434 * Dump gralloc state
5435 */
5436 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5437 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005438
rnleea2ecd832021-07-29 13:58:30 -07005439 /*
5440 * Dump flag/property manager state
5441 */
Robert Carr9b623c32022-03-21 15:55:22 -07005442 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005443
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005444 result.append(mTimeStats->miniDump());
5445 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005446}
5447
chaviw17ac24b2021-01-28 18:50:05 -08005448mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5449 if (saturation == 1) {
5450 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005451 }
5452
chaviw17ac24b2021-01-28 18:50:05 -08005453 float3 luminance{0.213f, 0.715f, 0.072f};
5454 luminance *= 1.0f - saturation;
5455 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5456 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5457 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5458 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5459 return saturationMatrix;
5460}
5461
5462void SurfaceFlinger::updateColorMatrixLocked() {
5463 mat4 colorMatrix =
5464 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5465
Chia-I Wu28f320b2018-05-03 11:02:56 -07005466 if (mCurrentState.colorMatrix != colorMatrix) {
5467 mCurrentState.colorMatrix = colorMatrix;
5468 mCurrentState.colorMatrixChanged = true;
5469 setTransactionFlags(eTransactionNeeded);
5470 }
5471}
5472
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005473status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005474#pragma clang diagnostic push
5475#pragma clang diagnostic error "-Wswitch-enum"
5476 switch (static_cast<ISurfaceComposerTag>(code)) {
5477 // These methods should at minimum make sure that the client requested
5478 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005479 case BOOT_FINISHED:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005480 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005481 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005482 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005483 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005484 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5485 // permission dynamically. Don't use the permission cache for this check.
5486 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005487 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005488 IPCThreadState* ipc = IPCThreadState::self();
5489 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5490 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005491 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005492 }
Robert Carr1db73f62016-12-21 12:58:51 -08005493 return OK;
5494 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005495 // Used by apps to hook Choreographer to SurfaceFlinger.
5496 case CREATE_DISPLAY_EVENT_CONNECTION:
5497 // The following calls are currently used by clients that do not
5498 // request necessary permissions. However, they do not expose any secret
5499 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005500 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005501 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005502 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005503 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005504 // Calling setTransactionState is safe, because you need to have been
5505 // granted a reference to Client* and Handle* to do anything with it.
5506 case SET_TRANSACTION_STATE:
Huihong Luo3bdef862022-03-03 11:57:19 -08005507 case CREATE_CONNECTION: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005508 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005509 return OK;
5510 }
Huihong Luo07e72362022-02-14 14:26:04 -08005511 case CREATE_DISPLAY:
5512 case DESTROY_DISPLAY:
5513 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5514 case GET_PHYSICAL_DISPLAY_IDS:
5515 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005516 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005517 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005518 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005519 case GET_DISPLAY_STATE:
5520 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005521 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005522 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005523 case GET_DISPLAY_NATIVE_PRIMARIES:
5524 case SET_ACTIVE_COLOR_MODE:
5525 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005526 case CLEAR_BOOT_DISPLAY_MODE:
5527 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5528 case SET_AUTO_LOW_LATENCY_MODE:
5529 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005530 case CAPTURE_LAYERS:
5531 case CAPTURE_DISPLAY:
5532 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005533 case CLEAR_ANIMATION_FRAME_STATS:
5534 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005535 case OVERRIDE_HDR_TYPES:
5536 case ON_PULL_ATOM:
5537 case ENABLE_VSYNC_INJECTIONS:
5538 case INJECT_VSYNC:
5539 case GET_LAYER_DEBUG_INFO:
5540 case GET_COLOR_MANAGEMENT:
5541 case GET_COMPOSITION_PREFERENCE:
5542 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5543 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005544 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005545 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005546 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005547 case ADD_REGION_SAMPLING_LISTENER:
5548 case REMOVE_REGION_SAMPLING_LISTENER:
5549 case ADD_FPS_LISTENER:
5550 case REMOVE_FPS_LISTENER:
5551 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5552 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5553 case ADD_WINDOW_INFOS_LISTENER:
5554 case REMOVE_WINDOW_INFOS_LISTENER:
5555 case SET_DESIRED_DISPLAY_MODE_SPECS:
5556 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005557 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5558 case SET_DISPLAY_BRIGHTNESS:
5559 case ADD_HDR_LAYER_INFO_LISTENER:
5560 case REMOVE_HDR_LAYER_INFO_LISTENER:
5561 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005562 case SET_GLOBAL_SHADOW_SETTINGS:
5563 case GET_DISPLAY_DECORATION_SUPPORT:
5564 case SET_FRAME_RATE:
5565 case SET_OVERRIDE_FRAME_RATE:
5566 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005567 case ADD_TRANSACTION_TRACE_LISTENER:
5568 case GET_GPU_CONTEXT_PRIORITY:
5569 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005570 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005571 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005572 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005573
5574 // These codes are used for the IBinder protocol to either interrogate the recipient
5575 // side of the transaction for its canonical interface descriptor or to dump its state.
5576 // We let them pass by default.
5577 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5578 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5579 code == IBinder::SYSPROPS_TRANSACTION) {
5580 return OK;
5581 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005582 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005583 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005584 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005585 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5586 return OK;
5587 }
5588 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5589 return PERMISSION_DENIED;
5590#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005591}
5592
Ana Krulec13be8ad2018-08-21 02:43:56 +00005593status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5594 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005595 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5596 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005597 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005598
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005599 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5600 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005601 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005602 IPCThreadState* ipc = IPCThreadState::self();
5603 const int uid = ipc->getCallingUid();
5604 if (CC_UNLIKELY(uid != AID_SYSTEM
5605 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005606 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005607 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005608 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005609 return PERMISSION_DENIED;
5610 }
5611 int n;
5612 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005613 case 1000: // Unused.
5614 case 1001:
5615 return NAME_NOT_FOUND;
5616 case 1002: // Toggle flashing on surface damage.
5617 if (const int delay = data.readInt32(); delay > 0) {
5618 mDebugFlashDelay = delay;
5619 } else {
5620 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5621 }
5622 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005623 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005624 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005625 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005626 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005627 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005628 case 1005: { // Force commit ahead of next VSYNC.
5629 Mutex::Autolock lock(mStateLock);
5630 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5631 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005632 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005633 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005634 case 1007: // Unused.
5635 return NAME_NOT_FOUND;
5636 case 1008: // Toggle forced GPU composition.
5637 mDebugDisableHWC = data.readInt32() != 0;
5638 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005639 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005640 case 1009: // Toggle use of transform hint.
5641 mDebugDisableTransformHint = data.readInt32() != 0;
5642 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005643 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005644 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005645 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005646 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005647 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005648 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005649 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005650 return NO_ERROR;
5651 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005652 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005653 if (!display) {
5654 return NAME_NOT_FOUND;
5655 }
5656
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005657 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005658 return NO_ERROR;
5659 }
5660 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005661 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005662 // daltonize
5663 n = data.readInt32();
5664 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005665 case 1:
5666 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5667 break;
5668 case 2:
5669 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5670 break;
5671 case 3:
5672 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5673 break;
5674 default:
5675 mDaltonizer.setType(ColorBlindnessType::None);
5676 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005677 }
5678 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005679 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005680 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005681 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005682 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005683
5684 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005685 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005686 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005687 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005688 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005689 // apply a color matrix
5690 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005691 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005692 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005693 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005694 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005695 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005696 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005697 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005698 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005699 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005700 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005701
5702 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5703 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005704 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005705 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5706 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5707 }
5708
Chia-I Wu28f320b2018-05-03 11:02:56 -07005709 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005710 return NO_ERROR;
5711 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005712 case 1016: { // Unused.
5713 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005714 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005715 case 1017: {
5716 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005717 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005718 return NO_ERROR;
5719 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005720 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005721 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005722 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005723 return NO_ERROR;
5724 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005725 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005726 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005727 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005728 return NO_ERROR;
5729 }
Irvel468051e2016-06-13 16:44:44 -07005730 case 1020: { // Layer updates interceptor
5731 n = data.readInt32();
5732 if (n) {
5733 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005734 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005735 }
5736 else{
5737 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005738 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005739 }
5740 return NO_ERROR;
5741 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005742 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005743 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005744 static_cast<void>(
5745 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005746 return NO_ERROR;
5747 }
Romain Guy0147a172017-06-01 13:53:56 -07005748 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005749 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005750 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005751
Chia-I Wu28f320b2018-05-03 11:02:56 -07005752 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005753 return NO_ERROR;
5754 }
Romain Guy54f154a2017-10-24 21:40:32 +01005755 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005756 int32_t colorMode;
5757
Chia-I Wu0d711262018-05-21 15:19:35 -07005758 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005759 if (data.readInt32(&colorMode) == NO_ERROR) {
5760 mForceColorMode = static_cast<ColorMode>(colorMode);
5761 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005762 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005763 return NO_ERROR;
5764 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005765 // Deprecate, use 1030 to check whether the device is color managed.
5766 case 1024: {
5767 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005768 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005769 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005770 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005771 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005772 if (n == 1) {
5773 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005774 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005775 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005776 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005777 int64_t startingTime =
5778 (fixedStartingTime) ? fixedStartingTime : systemTime();
5779 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005780 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005781 mLayerTracing.notify("start", startingTime);
5782 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005783 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005784 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005785 } else if (n == 2) {
5786 std::string filename = std::string(data.readCString());
5787 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5788 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005789 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005790 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005791 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005792 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005793 mTracingEnabledChanged = tracingEnabledChanged;
5794 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005795 return NO_ERROR;
5796 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005797 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005798 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005799 return NO_ERROR;
5800 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005801 // Is a DisplayColorSetting supported?
5802 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005803 const auto display = getDefaultDisplayDevice();
5804 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005805 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005806 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005807
5808 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5809 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005810 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005811 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005812 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005813 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005814 reply->writeBool(true);
5815 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005816 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005817 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005818 break;
5819 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005820 reply->writeBool(
5821 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005822 break;
5823 }
5824 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005825 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005826 case 1028: { // Unused.
5827 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005828 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005829 // Set buffer size for SF tracing (value in KB)
5830 case 1029: {
5831 n = data.readInt32();
5832 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5833 ALOGW("Invalid buffer size: %d KB", n);
5834 reply->writeInt32(BAD_VALUE);
5835 return BAD_VALUE;
5836 }
5837
5838 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005839 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005840 reply->writeInt32(NO_ERROR);
5841 return NO_ERROR;
5842 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005843 // Is device color managed?
5844 case 1030: {
5845 reply->writeBool(useColorManagement);
5846 return NO_ERROR;
5847 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005848 // Override default composition data space
5849 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5850 // && adb shell stop zygote && adb shell start zygote
5851 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5852 // adb shell stop zygote && adb shell start zygote
5853 case 1031: {
5854 Mutex::Autolock _l(mStateLock);
5855 n = data.readInt32();
5856 if (n) {
5857 n = data.readInt32();
5858 if (n) {
5859 Dataspace dataspace = static_cast<Dataspace>(n);
5860 if (!validateCompositionDataspace(dataspace)) {
5861 return BAD_VALUE;
5862 }
5863 mDefaultCompositionDataspace = dataspace;
5864 }
5865 n = data.readInt32();
5866 if (n) {
5867 Dataspace dataspace = static_cast<Dataspace>(n);
5868 if (!validateCompositionDataspace(dataspace)) {
5869 return BAD_VALUE;
5870 }
5871 mWideColorGamutCompositionDataspace = dataspace;
5872 }
5873 } else {
5874 // restore composition data space.
5875 mDefaultCompositionDataspace = defaultCompositionDataspace;
5876 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5877 }
5878 return NO_ERROR;
5879 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005880 // Set trace flags
5881 case 1033: {
5882 n = data.readUint32();
5883 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005884 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005885 reply->writeInt32(NO_ERROR);
5886 return NO_ERROR;
5887 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005888 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005889 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005890 switch (n = data.readInt32()) {
5891 case 0:
5892 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005893 FTL_FAKE_GUARD(mStateLock,
5894 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005895 break;
5896 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005897 reply->writeBool(
5898 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005899 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005900 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005901 });
5902
5903 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005904 return NO_ERROR;
5905 }
Ady Abraham34392f72019-04-10 11:29:27 -07005906 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005907 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005908
Dominik Laskowskif1833852021-03-23 15:06:50 -07005909 const auto display = [&]() -> sp<IBinder> {
5910 uint64_t value;
5911 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005912 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005913 }
5914
Dominik Laskowskif1833852021-03-23 15:06:50 -07005915 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5916 return getPhysicalDisplayToken(*id);
5917 }
5918
5919 ALOGE("Invalid physical display ID");
5920 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005921 }();
5922
Shiyong Li2bcece92021-08-30 20:38:50 +00005923 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005924 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005925 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5926 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005927 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005928 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5929 // manager frame rate policy a new policy which allows switching between all refresh
5930 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005931 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005932 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005933 return mScheduler
5934 ->schedule([this] {
5935 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005936 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005937
Dominik Laskowski756b7892021-08-04 12:53:59 -07005938 // This is a little racy, but not in a way that hurts anything. As
5939 // we grab the defaultMode from the display manager policy, we could
5940 // be setting a new display manager policy, leaving us using a stale
5941 // defaultMode. The defaultMode doesn't matter for the override
5942 // policy though, since we set allowGroupSwitching to true, so it's
5943 // not a problem.
5944 scheduler::RefreshRateConfigs::Policy overridePolicy;
5945 overridePolicy.defaultMode = display->refreshRateConfigs()
5946 .getDisplayManagerPolicy()
5947 .defaultMode;
5948 overridePolicy.allowGroupSwitching = true;
5949 constexpr bool kOverridePolicy = true;
5950 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5951 kOverridePolicy);
5952 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005953 .get();
5954 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07005955 return mScheduler
5956 ->schedule([this] {
5957 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005958 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07005959 constexpr bool kOverridePolicy = true;
5960 return setDesiredDisplayModeSpecsInternal(display, {},
5961 kOverridePolicy);
5962 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005963 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07005964 }
Ady Abraham07e54702020-04-16 15:05:37 -07005965 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02005966 // Inject a hotplug connected event for the primary display. This will deallocate and
5967 // reallocate the display state including framebuffers.
5968 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07005969 const hal::HWDisplayId hwcId =
5970 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
5971
5972 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02005973 return NO_ERROR;
5974 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07005975 // Modify the max number of display frames stored within FrameTimeline
5976 case 1038: {
5977 n = data.readInt32();
5978 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
5979 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
5980 return BAD_VALUE;
5981 }
5982 if (n == 0) {
5983 // restore to default
5984 mFrameTimeline->reset();
5985 return NO_ERROR;
5986 }
5987 mFrameTimeline->setMaxDisplayFrames(n);
5988 return NO_ERROR;
5989 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07005990 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07005991 PhysicalDisplayId displayId = [&]() {
5992 Mutex::Autolock lock(mStateLock);
5993 return getDefaultDisplayDeviceLocked()->getPhysicalId();
5994 }();
5995
5996 auto inUid = static_cast<uid_t>(data.readInt32());
5997 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08005998 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
5999 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07006000 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08006001 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006002 // Toggle caching feature
6003 // First argument is an int32 - nonzero enables caching and zero disables caching
6004 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6005 // caching to a particular physical display
6006 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006007 auto future = mScheduler->schedule([&] {
6008 n = data.readInt32();
6009 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6010 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6011 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6012 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6013 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6014 return NAME_NOT_FOUND;
6015 }
6016 }
6017 {
6018 Mutex::Autolock lock(mStateLock);
6019 mLayerCachingEnabled = n != 0;
6020 for (const auto& [_, display] : mDisplays) {
6021 if (!inputId || *inputId == display->getPhysicalId()) {
6022 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006023 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006024 }
6025 }
6026 return OK;
6027 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006028
Dominik Laskowski756b7892021-08-04 12:53:59 -07006029 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006030 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006031 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006032 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006033 return NO_ERROR;
6034 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006035 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006036 if (mTransactionTracing) {
6037 if (data.readInt32()) {
6038 // Transaction tracing is always running but allow the user to temporarily
6039 // increase the buffer when actively debugging.
6040 mTransactionTracing->setBufferSize(
6041 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6042 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006043 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006044 mTransactionTracing->setBufferSize(
6045 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006046 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006047 }
6048 reply->writeInt32(NO_ERROR);
6049 return NO_ERROR;
6050 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006051 case 1042: { // Write layers trace or transaction trace to file
6052 if (mTransactionTracing) {
6053 mTransactionTracing->writeToFile();
6054 }
6055 if (mLayerTracingEnabled) {
6056 mLayerTracing.writeToFile();
6057 }
6058 reply->writeInt32(NO_ERROR);
6059 return NO_ERROR;
6060 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006061 }
6062 }
6063 return err;
6064}
6065
Ady Abrahama09852a2020-02-20 14:23:42 -08006066void SurfaceFlinger::kernelTimerChanged(bool expired) {
6067 static bool updateOverlay =
6068 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006069 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006070
6071 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006072 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006073 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006074 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006075 if (!display) {
6076 ALOGW("%s: default display is null", __func__);
6077 return;
6078 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006079 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006080
6081 const auto desiredActiveMode = display->getDesiredActiveMode();
6082 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6083 ? std::make_optional(desiredActiveMode->mode->getId())
6084 : std::nullopt;
6085
6086 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6087
Ady Abraham1b11bc62021-06-03 19:51:19 -07006088 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006089 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006090 }
6091 }));
6092}
6093
ramindani32cf0602022-03-02 02:30:29 +00006094std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6095SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6096 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6097 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6098 const auto timeout = getIdleTimerTimeout(displayId);
6099 if (isKernelIdleTimerHwcSupported) {
6100 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6101 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6102 // In order to decide if we can use the HWC api for idle timer
6103 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6104 // without relying on hasDisplayCapability.
6105 // hasDisplayCapability relies on DisplayCapabilities
6106 // which are updated after we set the PowerMode::ON.
6107 // DISPLAY_IDLE_TIMER is a display driver property
6108 // and is available before the PowerMode::ON
6109 return {KernelIdleTimerController::HwcApi, timeout};
6110 }
6111 return {std::nullopt, timeout};
6112 }
6113 if (getKernelIdleTimerSyspropConfig(displayId)) {
6114 return {KernelIdleTimerController::Sysprop, timeout};
6115 }
6116
6117 return {std::nullopt, timeout};
6118}
6119
6120void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6121 KernelIdleTimerController controller,
6122 PhysicalDisplayId displayId) {
6123 switch (controller) {
6124 case KernelIdleTimerController::HwcApi: {
6125 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6126 break;
6127 }
6128 case KernelIdleTimerController::Sysprop: {
6129 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6130 break;
6131 }
6132 }
6133}
6134
Ana Krulecb9afd792020-06-11 13:16:15 -07006135void SurfaceFlinger::toggleKernelIdleTimer() {
6136 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6137
Ady Abraham3efa3942021-06-24 19:01:25 -07006138 const auto display = getDefaultDisplayDeviceLocked();
6139 if (!display) {
6140 ALOGW("%s: default display is null", __func__);
6141 return;
6142 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006143
Ady Abrahame9316b72021-09-24 17:04:36 -07006144 // If the support for kernel idle timer is disabled for the active display,
6145 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006146 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6147 display->refreshRateConfigs().kernelIdleTimerController();
6148 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006149 return;
6150 }
6151
Ady Abraham3efa3942021-06-24 19:01:25 -07006152 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006153
Ana Krulecb9afd792020-06-11 13:16:15 -07006154 switch (action) {
6155 case KernelIdleTimerAction::TurnOff:
6156 if (mKernelIdleTimerEnabled) {
6157 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006158 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6159 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6160 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006161 mKernelIdleTimerEnabled = false;
6162 }
6163 break;
6164 case KernelIdleTimerAction::TurnOn:
6165 if (!mKernelIdleTimerEnabled) {
6166 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006167 const std::chrono::milliseconds timeout =
6168 display->refreshRateConfigs().getIdleTimerTimeout();
6169 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6170 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006171 mKernelIdleTimerEnabled = true;
6172 }
6173 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006174 }
6175}
6176
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006177// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6178class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006179public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006180 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6181 ~WindowDisconnector() {
6182 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006183 }
6184
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006185private:
6186 ANativeWindow* mWindow;
6187 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006188};
6189
chaviw93df2ea2019-04-30 16:45:12 -07006190static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6191 switch (colorMode) {
6192 case ColorMode::DISPLAY_P3:
6193 case ColorMode::BT2100_PQ:
6194 case ColorMode::BT2100_HLG:
6195 case ColorMode::DISPLAY_BT2020:
6196 return Dataspace::DISPLAY_P3;
6197 default:
6198 return Dataspace::V0_SRGB;
6199 }
6200}
6201
chaviwf5bb97b2021-04-28 15:35:37 -05006202static bool hasCaptureBlackoutContentPermission() {
6203 IPCThreadState* ipc = IPCThreadState::self();
6204 const int pid = ipc->getCallingPid();
6205 const int uid = ipc->getCallingUid();
6206 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6207 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6208}
6209
chaviw4b9d5e12020-08-04 18:30:35 -07006210static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6211 IPCThreadState* ipc = IPCThreadState::self();
6212 const int pid = ipc->getCallingPid();
6213 const int uid = ipc->getCallingUid();
6214 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6215 return OK;
6216 }
6217
6218 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6219 // itself, we allow it to continue.
6220 if (captureArgs.uid == uid) {
6221 return OK;
6222 }
6223
6224 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6225 return PERMISSION_DENIED;
6226}
6227
Peiyong Lin05cc0112020-10-14 16:16:37 -07006228status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6229 static constexpr int kFifoPriority = 2;
6230 static constexpr int kOtherPriority = 0;
6231
6232 struct sched_param param = {0};
6233 int sched_policy;
6234 if (enabled) {
6235 sched_policy = SCHED_FIFO;
6236 param.sched_priority = kFifoPriority;
6237 } else {
6238 sched_policy = SCHED_OTHER;
6239 param.sched_priority = kOtherPriority;
6240 }
6241
6242 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6243 return -errno;
6244 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006245
6246 return NO_ERROR;
6247}
6248
6249status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6250 static const unsigned int kUclampMin =
6251 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6252
6253 if (!kUclampMin) {
6254 // uclamp.min set to 0 (default), skip setting
6255 return NO_ERROR;
6256 }
6257
6258 // Currently, there is no wrapper in bionic: b/183240349.
6259 struct sched_attr {
6260 uint32_t size;
6261 uint32_t sched_policy;
6262 uint64_t sched_flags;
6263 int32_t sched_nice;
6264 uint32_t sched_priority;
6265 uint64_t sched_runtime;
6266 uint64_t sched_deadline;
6267 uint64_t sched_period;
6268 uint32_t sched_util_min;
6269 uint32_t sched_util_max;
6270 };
6271
6272 sched_attr attr = {};
6273 attr.size = sizeof(attr);
6274
6275 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6276 attr.sched_util_min = enabled ? kUclampMin : 0;
6277 attr.sched_util_max = 1024;
6278
6279 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6280 return -errno;
6281 }
6282
Peiyong Lin05cc0112020-10-14 16:16:37 -07006283 return NO_ERROR;
6284}
6285
chaviwd2432892020-07-24 17:42:39 -07006286status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006287 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006288 ATRACE_CALL();
6289
chaviw4b9d5e12020-08-04 18:30:35 -07006290 status_t validate = validateScreenshotPermissions(args);
6291 if (validate != OK) {
6292 return validate;
6293 }
6294
chaviwd2432892020-07-24 17:42:39 -07006295 if (!args.displayToken) return BAD_VALUE;
6296
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006297 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006298 ui::LayerStack layerStack;
6299 ui::Size reqSize(args.width, args.height);
6300 ui::Dataspace dataspace;
6301 {
6302 Mutex::Autolock lock(mStateLock);
6303 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6304 if (!display) return NAME_NOT_FOUND;
6305 displayWeak = display;
6306 layerStack = display->getLayerStack();
6307
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006308 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006309 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006310 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006311 }
6312
arthurhung79e81aa2020-08-28 00:09:19 +08006313 // The dataspace is depended on the color mode of display, that could use non-native mode
6314 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6315 // and failed if display is not in native mode. This provide a way to force using native
6316 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006317 dataspace = args.dataspace;
6318 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006319 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6320 dataspace = pickDataspaceFromColorMode(colorMode);
6321 }
chaviwd2432892020-07-24 17:42:39 -07006322 }
6323
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006324 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006325 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006326 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006327 });
6328
chaviw4b9d5e12020-08-04 18:30:35 -07006329 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6330 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006331 };
chaviw03900772020-08-18 12:34:51 -07006332
Sally Qi59a9f502021-10-12 18:53:23 +00006333 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6334 reqSize, args.pixelFormat, args.allowProtected,
6335 args.grayscale, captureListener);
6336 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006337}
6338
Dominik Laskowskif1833852021-03-23 15:06:50 -07006339status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006340 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006341 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006342 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006343 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006344 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006345 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006346 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006347
Dominik Laskowskif1833852021-03-23 15:06:50 -07006348 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006349 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006350 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006351 }
6352
chaviw93df2ea2019-04-30 16:45:12 -07006353 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006354 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006355 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006356
chaviw426b5c02020-07-27 11:20:15 -07006357 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006358 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6359 }
6360
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006361 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006362 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006363 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006364 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006365 });
chaviw93df2ea2019-04-30 16:45:12 -07006366
Marin Shalamanov1c434292020-06-12 01:47:29 +02006367 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006368 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006369 };
6370
Sally Qi59a9f502021-10-12 18:53:23 +00006371 if (captureListener == nullptr) {
6372 ALOGE("capture screen must provide a capture listener callback");
6373 return BAD_VALUE;
6374 }
6375 auto captureResultFuture =
6376 captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6377 ui::PixelFormat::RGBA_8888, false /* allowProtected */,
6378 false /* grayscale */, captureListener);
6379 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006380}
6381
chaviw3efadb12020-07-27 10:07:15 -07006382status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006383 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006384 ATRACE_CALL();
6385
chaviw4b9d5e12020-08-04 18:30:35 -07006386 status_t validate = validateScreenshotPermissions(args);
6387 if (validate != OK) {
6388 return validate;
6389 }
6390
Marin Shalamanov1c434292020-06-12 01:47:29 +02006391 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006392 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006393 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006394 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006395 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006396
6397 // Call this before holding mStateLock to avoid any deadlocking.
6398 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6399
Robert Carrc0df3122019-04-11 13:18:21 -07006400 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006401 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006402
Vishnu Nairf9096652021-07-20 18:49:42 -07006403 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006404 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006405 ALOGE("captureLayers called with an invalid or removed parent");
6406 return NAME_NOT_FOUND;
6407 }
6408
chaviwf5bb97b2021-04-28 15:35:37 -05006409 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006410 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006411 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6412 return PERMISSION_DENIED;
6413 }
6414
Robert Carr6a160312021-05-17 12:08:20 -07006415 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006416 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006417 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006418 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006419 }
6420
chaviw3efadb12020-07-27 10:07:15 -07006421 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006422 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006423 crop.bottom = parentSourceBounds.getHeight();
6424 }
6425
chaviw17ac24b2021-01-28 18:50:05 -08006426 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006427 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6428 // crop was not specified, or an invalid frame scale was provided.
6429 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006430 }
chaviw17ac24b2021-01-28 18:50:05 -08006431 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006432
chaviw3efadb12020-07-27 10:07:15 -07006433 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006434 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006435 if (excludeLayer != nullptr) {
6436 excludeLayers.emplace(excludeLayer);
6437 } else {
6438 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6439 return NAME_NOT_FOUND;
6440 }
6441 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006442
arthurhung79e81aa2020-08-28 00:09:19 +08006443 // The dataspace is depended on the color mode of display, that could use non-native mode
6444 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6445 // and failed if display is not in native mode. This provide a way to force using native
6446 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006447 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006448 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006449
Chia-I Wu20261cb2018-08-23 12:55:44 -07006450 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006451 if (reqSize.width <= 0 || reqSize.height <= 0) {
6452 ALOGW("Failed to captureLayes: crop or scale too small");
6453 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006454 }
6455
chaviw79468ab2021-10-27 11:11:24 -05006456 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006457 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006458 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006459 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006460 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006461 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006462 });
6463
chaviw03900772020-08-18 12:34:51 -07006464 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006465 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6466 if (!layer->isVisible()) {
6467 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006468 } else if (args.childrenOnly && layer == parent.get()) {
6469 return;
6470 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006471 return;
chaviwa76b2712017-09-20 12:02:26 -07006472 }
Robert Carr866455f2019-04-02 16:28:26 -07006473
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006474 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006475 while (p != nullptr) {
6476 if (excludeLayers.count(p) != 0) {
6477 return;
6478 }
6479 p = p->getParent();
6480 }
6481
chaviwa76b2712017-09-20 12:02:26 -07006482 visitor(layer);
6483 });
6484 };
Robert Carr108b2c72019-04-02 16:32:58 -07006485
Sally Qi59a9f502021-10-12 18:53:23 +00006486 if (captureListener == nullptr) {
6487 ALOGE("capture screen must provide a capture listener callback");
6488 return BAD_VALUE;
6489 }
6490
6491 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6492 reqSize, args.pixelFormat, args.allowProtected,
6493 args.grayscale, captureListener);
6494 return captureResultFuture.get().status;
chaviwa76b2712017-09-20 12:02:26 -07006495}
6496
Sally Qi59a9f502021-10-12 18:53:23 +00006497std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
6498 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6499 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6500 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006501 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006502
Garfield Tan9c9c1912021-07-19 12:02:16 -07006503 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6504 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6505 ") that exceeds render target size limit.",
6506 bufferSize.getWidth(), bufferSize.getHeight());
Sally Qi59a9f502021-10-12 18:53:23 +00006507 return ftl::yield<renderengine::RenderEngineResult>({BAD_VALUE, base::unique_fd()}).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006508 }
6509
Peiyong Lin05cc0112020-10-14 16:16:37 -07006510 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6511 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6512 // A protected layer has no implication on whether it's secure, which is explicitly set by
6513 // application to avoid being screenshot or drawn via unsecure display.
6514 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6515 bool hasProtectedLayer = false;
6516 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006517 auto future = mScheduler->schedule([=]() {
6518 bool protectedLayerFound = false;
6519 traverseLayers([&](Layer* layer) {
6520 protectedLayerFound =
6521 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6522 });
6523 return protectedLayerFound;
6524 });
6525 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006526 }
6527
Richard Liucbcb8952020-04-08 10:51:55 +00006528 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6529 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006530 (hasProtectedLayer && allowProtected && supportsProtected
6531 ? GRALLOC_USAGE_PROTECTED
6532 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006533 sp<GraphicBuffer> buffer =
6534 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6535 static_cast<android_pixel_format>(reqPixelFormat),
6536 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006537
6538 const status_t bufferStatus = buffer->initCheck();
6539 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6540 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006541 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6542 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6543 renderengine::impl::ExternalTexture::Usage::
6544 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006545 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006546 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006547}
6548
Sally Qi59a9f502021-10-12 18:53:23 +00006549std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006550 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6551 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6552 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006553 ATRACE_CALL();
6554
chaviwf5bb97b2021-04-28 15:35:37 -05006555 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006556
Dominik Laskowski756b7892021-08-04 12:53:59 -07006557 auto scheduleResultFuture = mScheduler->schedule([=,
6558 renderAreaFuture =
6559 std::move(renderAreaFuture)]() mutable
6560 -> std::shared_future<
6561 renderengine::RenderEngineResult> {
chaviw03900772020-08-18 12:34:51 -07006562 ScreenCaptureResults captureResults;
6563 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6564 if (!renderArea) {
6565 ALOGW("Skipping screen capture because of invalid render area.");
6566 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006567 captureListener->onScreenCaptureCompleted(captureResults);
Sally Qi59a9f502021-10-12 18:53:23 +00006568 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()})
6569 .share();
chaviw03900772020-08-18 12:34:51 -07006570 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006571
Sally Qi59a9f502021-10-12 18:53:23 +00006572 std::shared_future<renderengine::RenderEngineResult> renderEngineResultFuture;
6573
chaviw03900772020-08-18 12:34:51 -07006574 renderArea->render([&] {
Sally Qi59a9f502021-10-12 18:53:23 +00006575 renderEngineResultFuture =
Robert Carr12a3b9b2022-03-10 09:55:29 -08006576 renderScreenImpl(*renderArea, traverseLayers, buffer,
Sally Qi59a9f502021-10-12 18:53:23 +00006577 canCaptureBlackoutContent, regionSampling, grayscale,
6578 captureResults);
chaviw03900772020-08-18 12:34:51 -07006579 });
Sally Qi59a9f502021-10-12 18:53:23 +00006580 // spring up a thread to unblock SF main thread and wait for
6581 // RenderEngineResult to be available
6582 if (captureListener != nullptr) {
6583 std::async([=]() mutable {
6584 ATRACE_NAME("captureListener is nonnull!");
6585 auto& [status, drawFence] = renderEngineResultFuture.get();
6586 captureResults.result = status;
6587 captureResults.fence = new Fence(dup(drawFence));
6588 captureListener->onScreenCaptureCompleted(captureResults);
6589 });
6590 }
6591 return renderEngineResultFuture;
6592 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006593
Sally Qi59a9f502021-10-12 18:53:23 +00006594 // flatten scheduleResultFuture object to single shared_future object
6595 if (captureListener == nullptr) {
6596 std::future<renderengine::RenderEngineResult> captureScreenResultFuture =
6597 ftl::chain(std::move(scheduleResultFuture))
6598 .then([=](std::shared_future<renderengine::RenderEngineResult> futureObject)
6599 -> renderengine::RenderEngineResult {
6600 auto& [status, drawFence] = futureObject.get();
6601 return {status, base::unique_fd(dup(drawFence))};
6602 });
6603 return captureScreenResultFuture.share();
6604 } else {
6605 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()}).share();
6606 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006607}
6608
Robert Carr12a3b9b2022-03-10 09:55:29 -08006609std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006610 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006611 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6612 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6613 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006614 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006615
chaviw426b5c02020-07-27 11:20:15 -07006616 traverseLayers([&](Layer* layer) {
6617 captureResults.capturedSecureLayers =
6618 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6619 });
6620
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006621 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006622
chaviw426b5c02020-07-27 11:20:15 -07006623 // We allow the system server to take screenshots of secure layers for
6624 // use in situations like the Screen-rotation animation and place
6625 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006626 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006627 ALOGW("FB is protected: PERMISSION_DENIED");
Sally Qi59a9f502021-10-12 18:53:23 +00006628 return ftl::yield<renderengine::RenderEngineResult>({PERMISSION_DENIED, base::unique_fd()})
6629 .share();
chaviw426b5c02020-07-27 11:20:15 -07006630 }
6631
Alec Mouria90a5702021-04-16 16:36:21 +00006632 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006633 auto dataspace = renderArea.getReqDataSpace();
6634 auto parent = renderArea.getParentLayer();
6635 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6636 Mutex::Autolock lock(mStateLock);
6637 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6638 return display.getLayerStack() == layerStack;
6639 });
6640 if (!display) {
6641 // If the layer is not on a display, use the dataspace for the default display.
6642 display = getDefaultDisplayDeviceLocked();
6643 }
6644
6645 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6646 dataspace = pickDataspaceFromColorMode(colorMode);
6647 }
6648 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006649
chaviwa76b2712017-09-20 12:02:26 -07006650 const auto reqWidth = renderArea.getReqWidth();
6651 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006652 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006653 const auto transform = renderArea.getTransform();
6654 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006655 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006656
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006657 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006658 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006659
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006660 // assume that bounds are never offset, and that they are the same as the
6661 // buffer bounds.
6662 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006663 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006664 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006665
Robert Carr12a3b9b2022-03-10 09:55:29 -08006666 clientCompositionDisplay.outputDataspace = dataspace;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006667 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006668
chaviw17ac24b2021-01-28 18:50:05 -08006669 const float colorSaturation = grayscale ? 0 : 1;
6670 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6671
chaviw50da5042018-04-09 13:49:37 -07006672 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006673
Vishnu Nair9b079a22020-01-21 14:36:08 -08006674 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006675 fillLayer.source.buffer.buffer = nullptr;
6676 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006677 fillLayer.geometry.boundaries =
6678 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006679 fillLayer.alpha = half(alpha);
6680 clientCompositionLayers.push_back(fillLayer);
6681
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006682 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006683 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006684 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006685 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006686 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006687
Lloyd Piquef16688f2019-02-19 17:47:57 -08006688 Region clip(renderArea.getBounds());
6689 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6690 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006691 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006692 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006693 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006694 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006695 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006696 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006697 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006698 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006699 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6700 BlurSetting::Disabled
6701 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6702 BlurSetting::Enabled,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006703 DisplayDevice::sDefaultMaxLumiance,
6704
Lloyd Piquef16688f2019-02-19 17:47:57 -08006705 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006706 std::vector<compositionengine::LayerFE::LayerSettings> results =
6707 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006708 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006709 for (auto& settings : results) {
6710 settings.geometry.positionTransform =
6711 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006712 // There's no need to process blurs when we're executing region sampling,
6713 // we're just trying to understand what we're drawing, and doing so without
6714 // blurs is already a pretty good approximation.
6715 if (regionSampling) {
6716 settings.backgroundBlurRadius = 0;
6717 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07006718 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006719
Yichi Chen40773d92020-04-01 10:10:18 +08006720 clientCompositionLayers.insert(clientCompositionLayers.end(),
6721 std::make_move_iterator(results.begin()),
6722 std::make_move_iterator(results.end()));
6723 renderedLayers.push_back(layer);
6724 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006725
chaviwa76b2712017-09-20 12:02:26 -07006726 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006727
Sally Qi59a9f502021-10-12 18:53:23 +00006728 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6729 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006730 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006731 std::back_inserter(clientRenderEngineLayers),
6732 [](compositionengine::LayerFE::LayerSettings& settings)
6733 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006734
Alec Mouri6338c9d2019-02-07 16:57:51 -08006735 // Use an empty fence for the buffer fence, since we just created the buffer so
6736 // there is no need for synchronization with the GPU.
6737 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006738 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006739
Alec Mouria90a5702021-04-16 16:36:21 +00006740 const constexpr bool kUseFramebufferCache = false;
Sally Qi59a9f502021-10-12 18:53:23 +00006741 std::future<renderengine::RenderEngineResult> drawLayersResult =
6742 getRenderEngine().drawLayers(clientCompositionDisplay, clientRenderEngineLayers, buffer,
6743 kUseFramebufferCache, std::move(bufferFence));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006744
Sally Qi59a9f502021-10-12 18:53:23 +00006745 std::shared_future<renderengine::RenderEngineResult> drawLayersResultFuture =
6746 drawLayersResult.share(); // drawLayersResult will be moved to shared one
6747
6748 for (auto* layer : renderedLayers) {
6749 // make a copy of shared_future object for each layer
6750 layer->onLayerDisplayed(drawLayersResultFuture);
Yichi Chen40773d92020-04-01 10:10:18 +08006751 }
Ady Abraham99599942021-01-27 20:27:23 -08006752
Peiyong Lin05cc0112020-10-14 16:16:37 -07006753 // Always switch back to unprotected context.
6754 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006755
Sally Qi59a9f502021-10-12 18:53:23 +00006756 return drawLayersResultFuture;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006757}
6758
chaviwbf023a62021-06-07 16:00:06 -05006759void SurfaceFlinger::windowInfosReported() {
chaviw95ef3c42019-02-14 10:55:09 -08006760 Mutex::Autolock _l(mStateLock);
Arthur Hung2274a312021-04-28 15:13:06 +00006761 signalSynchronousTransactions(CountDownLatch::eSyncInputWindows);
chaviw95ef3c42019-02-14 10:55:09 -08006762}
chaviw5f21a5e2019-02-14 10:00:34 -08006763
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006764// ---------------------------------------------------------------------------
6765
Edgar Arriaga844fa672020-01-16 14:21:42 -08006766void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6767 layersSortedByZ.traverse(visitor);
6768}
6769
Dan Stoza412903f2017-04-27 13:42:17 -07006770void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6771 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006772}
6773
Dan Stoza412903f2017-04-27 13:42:17 -07006774void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6775 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006776}
6777
chaviw4b9d5e12020-08-04 18:30:35 -07006778void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006779 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006780 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006781 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006782 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006783 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006784 continue;
6785 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006786 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006787 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006788 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006789 return;
6790 }
chaviwa76b2712017-09-20 12:02:26 -07006791 if (!layer->isVisible()) {
6792 return;
6793 }
chaviw4b9d5e12020-08-04 18:30:35 -07006794 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6795 return;
6796 }
chaviwa76b2712017-09-20 12:02:26 -07006797 visitor(layer);
6798 });
6799 }
6800}
6801
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006802status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006803 const sp<DisplayDevice>& display,
6804 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006805 Mutex::Autolock lock(mStateLock);
6806
Ady Abrahamfb853662021-04-09 11:46:40 -07006807 if (mDebugDisplayModeSetByBackdoor) {
6808 // ignore this request as mode is overridden by backdoor
6809 return NO_ERROR;
6810 }
6811
Ady Abraham3efa3942021-06-24 19:01:25 -07006812 status_t setPolicyResult = overridePolicy
6813 ? display->refreshRateConfigs().setOverridePolicy(policy)
6814 : display->refreshRateConfigs().setDisplayManagerPolicy(*policy);
6815 if (setPolicyResult < 0) {
6816 return BAD_VALUE;
6817 }
6818 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6819 return NO_ERROR;
6820 }
6821
Ady Abraham3efa3942021-06-24 19:01:25 -07006822 scheduler::RefreshRateConfigs::Policy currentPolicy =
6823 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006824
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006825 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006826
Ana Krulecb9afd792020-06-11 13:16:15 -07006827 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6828 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006829 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006830 if (isDisplayActiveLocked(display)) {
6831 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6832 toggleKernelIdleTimer();
6833 } else {
6834 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6835 }
Ady Abraham838de062019-02-04 10:24:03 -08006836
Ady Abraham690f4612021-07-01 23:24:03 -07006837 const DisplayModePtr preferredDisplayMode = [&] {
6838 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6839 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6840 return schedulerMode;
6841 }
6842
6843 return display->getMode(currentPolicy.defaultMode);
6844 }();
6845
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006846 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006847 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006848
Ady Abraham690f4612021-07-01 23:24:03 -07006849 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006850 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006851 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006852 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006853 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006854 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006855 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006856 }
6857
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006858 return NO_ERROR;
6859}
6860
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006861status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6862 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6863 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6864 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006865 ATRACE_CALL();
6866
6867 if (!displayToken) {
6868 return BAD_VALUE;
6869 }
6870
Dominik Laskowski756b7892021-08-04 12:53:59 -07006871 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006872 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006873 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006874 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006875 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006876 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006877 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006878 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006879 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006880 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006881 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006882 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006883 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006884 {Fps::fromValue(primaryRefreshRateMin),
6885 Fps::fromValue(primaryRefreshRateMax)},
6886 {Fps::fromValue(appRequestRefreshRateMin),
6887 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006888 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006889
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006890 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006891 }
6892 });
6893
6894 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006895}
6896
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006897status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6898 ui::DisplayModeId* outDefaultMode,
6899 bool* outAllowGroupSwitching,
6900 float* outPrimaryRefreshRateMin,
6901 float* outPrimaryRefreshRateMax,
6902 float* outAppRequestRefreshRateMin,
6903 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006904 ATRACE_CALL();
6905
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006906 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006907 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006908 return BAD_VALUE;
6909 }
6910
6911 Mutex::Autolock lock(mStateLock);
6912 const auto display = getDisplayDeviceLocked(displayToken);
6913 if (!display) {
6914 return NAME_NOT_FOUND;
6915 }
6916
Ady Abraham3efa3942021-06-24 19:01:25 -07006917 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006918 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006919 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006920
6921 scheduler::RefreshRateConfigs::Policy policy =
6922 display->refreshRateConfigs().getDisplayManagerPolicy();
6923 *outDefaultMode = policy.defaultMode.value();
6924 *outAllowGroupSwitching = policy.allowGroupSwitching;
6925 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6926 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6927 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6928 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6929 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006930}
6931
Vishnu Nairf9096652021-07-20 18:49:42 -07006932wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6933 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006934}
6935
Dominik Laskowski75848362019-11-11 17:57:20 -08006936void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006937 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006938 if (!layer->isRemovedFromCurrentState()) {
6939 mScheduler->registerLayer(layer);
6940 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006941}
6942
6943void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6944 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006945 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006946 if (!layer->isRemovedFromCurrentState()) {
6947 mScheduler->deregisterLayer(layer);
6948 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08006949 if (mTransactionTracing) {
6950 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08006951 }
Valerie Hauc5686802019-11-22 14:18:09 -08006952}
6953
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006954void SurfaceFlinger::onLayerUpdate() {
6955 scheduleCommit(FrameHint::kActive);
6956}
6957
Valerie Hauc5686802019-11-22 14:18:09 -08006958// WARNING: ONLY CALL THIS FROM LAYER DTOR
6959// Here we add children in the current state to offscreen layers and remove the
6960// layer itself from the offscreen layer list. Since
6961// this is the dtor, it is safe to access the current state. This keeps us
6962// from dangling children layers such that they are not reachable from the
6963// Drawing state nor the offscreen layer list
6964// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07006965void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08006966 for (auto& child : layer->getCurrentChildren()) {
6967 mOffscreenLayers.emplace(child.get());
6968 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006969 mOffscreenLayers.erase(layer);
6970}
6971
Robert Carr867be372021-06-29 17:36:02 -07006972void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6973 mOffscreenLayers.erase(layer);
6974}
6975
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006976status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6977 float lightPosY, float lightPosZ,
6978 float lightRadius) {
6979 Mutex::Autolock _l(mStateLock);
6980 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6981 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6982 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6983 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6984 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6985
6986 // these values are overridden when calculating the shadow settings for a layer.
6987 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6988 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006989 return NO_ERROR;
6990}
6991
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006992const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6993 const {
6994 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6995 // on the work to remove the table in that bug rather than adding more to
6996 // it.
6997 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006998 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6999 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
7000 };
7001 return genericLayerMetadataKeyMap;
7002}
7003
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007004status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7005 PhysicalDisplayId displayId = [&]() {
7006 Mutex::Autolock lock(mStateLock);
7007 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7008 }();
7009
7010 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7011 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7012 return NO_ERROR;
7013}
7014
Dominik Laskowski20134642020-04-20 22:36:44 -07007015void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007016 for (const auto& [ignored, display] : mDisplays) {
7017 if (display->isInternal()) {
7018 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007019 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007020 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007021}
7022
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007023status_t SurfaceFlinger::addTransactionTraceListener(
7024 const sp<gui::ITransactionTraceListener>& listener) {
7025 if (!listener) {
7026 return BAD_VALUE;
7027 }
7028
7029 mInterceptor->addTransactionTraceListener(listener);
7030
7031 return NO_ERROR;
7032}
7033
Huihong Luo02186fb2022-02-23 14:21:54 -08007034int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007035 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007036}
7037
Ady Abraham899dcdb2021-06-15 16:56:21 -07007038int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7039 std::chrono::nanoseconds presentLatency) {
7040 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7041 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007042 pipelineDepth++;
7043 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007044 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007045}
7046
Ady Abraham899dcdb2021-06-15 16:56:21 -07007047status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007048 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007049
7050 if (!getHwComposer().isHeadless()) {
7051 if (const auto display = getDefaultDisplayDevice()) {
7052 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007053 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007054 }
7055
7056 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007057 return NO_ERROR;
7058}
7059
rnleeed20fa42021-08-10 18:00:03 -07007060uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007061 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007062
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007063 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7064 refreshRate = *frameRateOverride;
7065 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007066 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007067 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007068 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007069 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007070
Ady Abraham899dcdb2021-06-15 16:56:21 -07007071 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7072}
7073
7074int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7075 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7076 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7077 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7078}
7079
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007080void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state) {
7081 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007082 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007083 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7084 return;
arthurhungdba591c2021-02-08 17:28:49 +08007085 }
7086
7087 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007088 bool addToRoot = state.addToRoot;
7089 if (state.initialParent != nullptr) {
7090 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007091 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007092 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007093 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007094 }
arthurhungdba591c2021-02-08 17:28:49 +08007095 }
7096
Garfield Tand712ad32021-10-27 13:44:22 -07007097 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007098 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007099 mCurrentState.layersSortedByZ.add(layer);
7100 } else if (parent == nullptr) {
7101 layer->onRemovedFromCurrentState();
7102 } else if (parent->isRemovedFromCurrentState()) {
7103 parent->addChild(layer);
7104 layer->onRemovedFromCurrentState();
7105 } else {
7106 parent->addChild(layer);
7107 }
7108
Ady Abraham1273ac12021-08-26 17:31:53 -07007109 layer->updateTransformHint(mActiveDisplayTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +08007110
Arthur Hung23e07502021-10-15 11:58:19 +00007111 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007112}
Ady Abraham562c2712021-05-07 15:10:42 -07007113
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007114void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007115 if (!mLumaSampling || !mRegionSamplingThread) {
7116 return;
7117 }
7118
Dominik Laskowski756b7892021-08-04 12:53:59 -07007119 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007120}
7121
Ady Abrahamed3290f2021-05-17 15:12:14 -07007122void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7123 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7124 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7125}
7126
7127void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7128 ATRACE_CALL();
7129
Ady Abrahamdb036a82021-07-16 14:18:34 -07007130 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7131 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7132 }
7133
Ady Abrahamed3290f2021-05-17 15:12:14 -07007134 if (!activeDisplay) {
7135 ALOGE("%s: activeDisplay is null", __func__);
7136 return;
7137 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007138 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007139 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007140 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007141 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007142 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007143 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007144 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007145
7146 // Update the kernel timer for the current active display, since the policy
7147 // for this display might have changed when it was not the active display.
7148 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007149}
7150
chaviw60c9d3e2021-06-04 12:52:17 -05007151status_t SurfaceFlinger::addWindowInfosListener(
7152 const sp<IWindowInfosListener>& windowInfosListener) const {
7153 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7154 return NO_ERROR;
7155}
7156
7157status_t SurfaceFlinger::removeWindowInfosListener(
7158 const sp<IWindowInfosListener>& windowInfosListener) const {
7159 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7160 return NO_ERROR;
7161}
7162
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007163std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7164 const BufferData& bufferData, const char* layerName) const {
7165 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7166 bool bufferSizeExceedsLimit = false;
7167 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7168 if (cacheIdChanged && bufferData.buffer != nullptr) {
7169 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7170 bufferData.buffer->getHeight());
7171 if (!bufferSizeExceedsLimit) {
7172 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7173 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7174 }
7175 } else if (cacheIdChanged) {
7176 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7177 } else if (bufferData.buffer != nullptr) {
7178 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7179 bufferData.buffer->getHeight());
7180 if (!bufferSizeExceedsLimit) {
7181 buffer = std::make_shared<
7182 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7183 renderengine::impl::ExternalTexture::
7184 Usage::READABLE);
7185 }
7186 }
7187 ALOGE_IF(bufferSizeExceedsLimit,
7188 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7189 "limit.",
7190 layerName);
7191 return buffer;
7192}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007193
7194bool SurfaceFlinger::commitCreatedLayers() {
7195 std::vector<LayerCreatedState> createdLayers;
7196 {
7197 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7198 createdLayers = std::move(mCreatedLayers);
7199 mCreatedLayers.clear();
7200 if (createdLayers.size() == 0) {
7201 return false;
7202 }
7203 }
7204
7205 Mutex::Autolock _l(mStateLock);
7206 for (const auto& createdLayer : createdLayers) {
7207 handleLayerCreatedLocked(createdLayer);
7208 }
7209 createdLayers.clear();
7210 mLayersAdded = true;
7211 return true;
7212}
Huihong Luof5029222021-12-16 14:33:46 -08007213
7214// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007215
7216binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7217 sp<IBinder>* outDisplay) {
7218 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007219 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007220 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007221 }
Huihong Luo37396db2022-02-15 10:43:00 -08007222 String8 displayName8 = String8::format("%s", displayName.c_str());
7223 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7224 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007225}
7226
7227binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7228 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007229 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007230 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007231 }
Huihong Luo37396db2022-02-15 10:43:00 -08007232 mFlinger->destroyDisplay(display);
7233 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007234}
7235
7236binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7237 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7238 std::vector<int64_t> displayIds;
7239 displayIds.reserve(physicalDisplayIds.size());
7240 for (auto item : physicalDisplayIds) {
7241 displayIds.push_back(static_cast<int64_t>(item.value));
7242 }
7243 *outDisplayIds = displayIds;
7244 return binder::Status::ok();
7245}
7246
7247binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7248 status_t status = checkAccessPermission();
7249 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007250 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007251 }
7252
7253 PhysicalDisplayId id;
7254 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7255 if (status == NO_ERROR) {
7256 *outDisplayId = id.value;
7257 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007258 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007259}
7260
7261binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7262 sp<IBinder>* outDisplay) {
7263 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7264 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7265 return binder::Status::ok();
7266}
7267
Huihong Luo37396db2022-02-15 10:43:00 -08007268binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7269 status_t status = checkAccessPermission();
7270 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007271 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007272 }
7273 mFlinger->setPowerMode(display, mode);
7274 return binder::Status::ok();
7275}
7276
Huihong Luo0a81aa32022-02-22 16:02:36 -08007277binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7278 std::vector<FrameEvent>* outSupported) {
7279 status_t status;
7280 if (!outSupported) {
7281 status = UNEXPECTED_NULL;
7282 } else {
7283 outSupported->clear();
7284 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7285 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007286 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007287}
7288
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007289binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7290 gui::DisplayStatInfo* outStatInfo) {
7291 DisplayStatInfo statInfo;
7292 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7293 if (status == NO_ERROR) {
7294 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7295 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7296 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007297 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007298}
7299
7300binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7301 gui::DisplayState* outState) {
7302 ui::DisplayState state;
7303 status_t status = mFlinger->getDisplayState(display, &state);
7304 if (status == NO_ERROR) {
7305 outState->layerStack = state.layerStack.id;
7306 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7307 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7308 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7309 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007310 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007311}
7312
Huihong Luoa79ddf42022-02-17 00:01:38 -08007313binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7314 gui::StaticDisplayInfo* outInfo) {
7315 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7316 ui::StaticDisplayInfo info;
7317 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7318 if (status == NO_ERROR) {
7319 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7320 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7321 outInfo->density = info.density;
7322 outInfo->secure = info.secure;
7323 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7324
7325 gui::DeviceProductInfo dinfo;
7326 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7327 dinfo.name = std::move(dpi->name);
7328 dinfo.manufacturerPnpId =
7329 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7330 dinfo.productId = dpi->productId;
7331 if (const auto* model =
7332 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7333 gui::DeviceProductInfo::ModelYear modelYear;
7334 modelYear.year = model->year;
7335 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7336 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7337 &dpi->manufactureOrModelDate)) {
7338 gui::DeviceProductInfo::ManufactureYear date;
7339 date.modelYear.year = manufacture->year;
7340 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7341 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7342 &dpi->manufactureOrModelDate)) {
7343 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7344 date.manufactureYear.modelYear.year = manufacture->year;
7345 date.week = manufacture->week;
7346 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7347 }
7348
7349 outInfo->deviceProductInfo = dinfo;
7350 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007351 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007352}
7353
Huihong Luo38603fd2022-02-21 14:32:54 -08007354binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7355 gui::DynamicDisplayInfo* outInfo) {
7356 ui::DynamicDisplayInfo info;
7357 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7358 if (status == NO_ERROR) {
7359 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7360 outInfo->supportedDisplayModes.clear();
7361 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7362 for (const auto& mode : info.supportedDisplayModes) {
7363 gui::DisplayMode outMode;
7364 outMode.id = mode.id;
7365 outMode.resolution.width = mode.resolution.width;
7366 outMode.resolution.height = mode.resolution.height;
7367 outMode.xDpi = mode.xDpi;
7368 outMode.yDpi = mode.yDpi;
7369 outMode.refreshRate = mode.refreshRate;
7370 outMode.appVsyncOffset = mode.appVsyncOffset;
7371 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7372 outMode.presentationDeadline = mode.presentationDeadline;
7373 outMode.group = mode.group;
7374 outInfo->supportedDisplayModes.push_back(outMode);
7375 }
7376
7377 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7378
7379 outInfo->supportedColorModes.clear();
7380 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7381 for (const auto& cmode : info.supportedColorModes) {
7382 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7383 }
7384
7385 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7386
7387 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7388 hdrCapabilities.supportedHdrTypes.clear();
7389 hdrCapabilities.supportedHdrTypes.reserve(
7390 info.hdrCapabilities.getSupportedHdrTypes().size());
7391 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7392 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7393 }
7394 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7395 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7396 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7397
7398 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7399 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7400 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7401 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007402 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007403}
7404
Huihong Luoca3d9a42022-02-22 11:07:34 -08007405binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7406 gui::DisplayPrimaries* outPrimaries) {
7407 ui::DisplayPrimaries primaries;
7408 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7409 if (status == NO_ERROR) {
7410 outPrimaries->red.X = primaries.red.X;
7411 outPrimaries->red.Y = primaries.red.Y;
7412 outPrimaries->red.Z = primaries.red.Z;
7413
7414 outPrimaries->green.X = primaries.green.X;
7415 outPrimaries->green.Y = primaries.green.Y;
7416 outPrimaries->green.Z = primaries.green.Z;
7417
7418 outPrimaries->blue.X = primaries.blue.X;
7419 outPrimaries->blue.Y = primaries.blue.Y;
7420 outPrimaries->blue.Z = primaries.blue.Z;
7421
7422 outPrimaries->white.X = primaries.white.X;
7423 outPrimaries->white.Y = primaries.white.Y;
7424 outPrimaries->white.Z = primaries.white.Z;
7425 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007426 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007427}
7428
7429binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7430 status_t status = checkAccessPermission();
7431 if (status == OK) {
7432 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7433 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007434 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007435}
7436
7437binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7438 int displayModeId) {
7439 status_t status = checkAccessPermission();
7440 if (status == OK) {
7441 status = mFlinger->setBootDisplayMode(display,
7442 static_cast<ui::DisplayModeId>(displayModeId));
7443 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007444 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007445}
7446
Huihong Luo37396db2022-02-15 10:43:00 -08007447binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7448 status_t status = checkAccessPermission();
7449 if (status == OK) {
7450 status = mFlinger->clearBootDisplayMode(display);
7451 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007452 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007453}
7454
7455binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7456 status_t status = checkAccessPermission();
7457 if (status == OK) {
7458 status = mFlinger->getBootDisplayModeSupport(outMode);
7459 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007460 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007461}
7462
7463binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7464 status_t status = checkAccessPermission();
7465 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007466 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007467 }
7468 mFlinger->setAutoLowLatencyMode(display, on);
7469 return binder::Status::ok();
7470}
7471
7472binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7473 status_t status = checkAccessPermission();
7474 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007475 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007476 }
7477 mFlinger->setGameContentType(display, on);
7478 return binder::Status::ok();
7479}
7480
Huihong Luof5029222021-12-16 14:33:46 -08007481binder::Status SurfaceComposerAIDL::captureDisplay(
7482 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7483 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007484 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007485}
7486
7487binder::Status SurfaceComposerAIDL::captureDisplayById(
7488 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7489 status_t status;
7490 IPCThreadState* ipc = IPCThreadState::self();
7491 const int uid = ipc->getCallingUid();
7492 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7493 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7494 status = mFlinger->captureDisplay(*id, captureListener);
7495 } else {
7496 status = PERMISSION_DENIED;
7497 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007498 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007499}
7500
7501binder::Status SurfaceComposerAIDL::captureLayers(
7502 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7503 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007504 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007505}
7506
Huihong Luo4ed1c912022-02-22 14:30:01 -08007507binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7508 status_t status = checkAccessPermission();
7509 if (status == OK) {
7510 status = mFlinger->clearAnimationFrameStats();
7511 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007512 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007513}
7514
7515binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7516 status_t status = checkAccessPermission();
7517 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007518 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007519 }
7520
7521 FrameStats stats;
7522 status = mFlinger->getAnimationFrameStats(&stats);
7523 if (status == NO_ERROR) {
7524 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7525 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7526 for (const auto& t : stats.desiredPresentTimesNano) {
7527 outStats->desiredPresentTimesNano.push_back(t);
7528 }
7529 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7530 for (const auto& t : stats.actualPresentTimesNano) {
7531 outStats->actualPresentTimesNano.push_back(t);
7532 }
7533 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7534 for (const auto& t : stats.frameReadyTimesNano) {
7535 outStats->frameReadyTimesNano.push_back(t);
7536 }
7537 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007538 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007539}
7540
Huihong Luo05539a12022-02-23 10:29:40 -08007541binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7542 const std::vector<int32_t>& hdrTypes) {
7543 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7544 // permission dynamically. Don't use the permission cache for this check.
7545 status_t status = checkAccessPermission(false);
7546 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007547 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007548 }
7549
7550 std::vector<ui::Hdr> hdrTypesVector;
7551 for (int32_t i : hdrTypes) {
7552 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7553 }
7554 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007555 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007556}
7557
7558binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7559 status_t status;
7560 const int uid = IPCThreadState::self()->getCallingUid();
7561 if (uid != AID_SYSTEM) {
7562 status = PERMISSION_DENIED;
7563 } else {
7564 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7565 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007566 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007567}
7568
7569binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7570 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007571 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007572 }
7573
7574 status_t status = checkAccessPermission();
7575 if (status == OK) {
7576 status = mFlinger->enableVSyncInjections(enable);
7577 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007578 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007579}
7580
7581binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7582 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007583 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007584 }
7585
7586 status_t status = checkAccessPermission();
7587 if (status == OK) {
7588 status = mFlinger->injectVSync(when);
7589 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007590 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007591}
7592
7593binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7594 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007595 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007596 }
7597
7598 IPCThreadState* ipc = IPCThreadState::self();
7599 const int pid = ipc->getCallingPid();
7600 const int uid = ipc->getCallingUid();
7601 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7602 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007603 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007604 }
7605 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007606 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007607}
7608
7609binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7610 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007611 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007612}
7613
7614binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7615 ui::Dataspace dataspace;
7616 ui::PixelFormat pixelFormat;
7617 ui::Dataspace wideColorGamutDataspace;
7618 ui::PixelFormat wideColorGamutPixelFormat;
7619 status_t status =
7620 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7621 &wideColorGamutPixelFormat);
7622 if (status == NO_ERROR) {
7623 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7624 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7625 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7626 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7627 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007628 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007629}
7630
7631binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7632 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7633 status_t status = checkAccessPermission();
7634 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007635 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007636 }
7637
7638 ui::PixelFormat format;
7639 ui::Dataspace dataspace;
7640 uint8_t componentMask;
7641 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7642 &componentMask);
7643 if (status == NO_ERROR) {
7644 outAttrs->format = static_cast<int32_t>(format);
7645 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7646 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7647 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007648 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007649}
7650
7651binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7652 bool enable,
7653 int8_t componentMask,
7654 int64_t maxFrames) {
7655 status_t status = checkAccessPermission();
7656 if (status == OK) {
7657 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7658 static_cast<uint8_t>(componentMask),
7659 static_cast<uint64_t>(maxFrames));
7660 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007661 return binderStatusFromStatusT(status);
7662}
7663
7664binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7665 int64_t maxFrames, int64_t timestamp,
7666 gui::DisplayedFrameStats* outStats) {
7667 if (!outStats) {
7668 return binderStatusFromStatusT(BAD_VALUE);
7669 }
7670
7671 status_t status = checkAccessPermission();
7672 if (status != OK) {
7673 return binderStatusFromStatusT(status);
7674 }
7675
7676 DisplayedFrameStats stats;
7677 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7678 static_cast<uint64_t>(timestamp), &stats);
7679 if (status == NO_ERROR) {
7680 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7681 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7682 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7683 for (const auto& s : stats.component_0_sample) {
7684 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7685 }
7686 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7687 for (const auto& s : stats.component_1_sample) {
7688 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7689 }
7690 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7691 for (const auto& s : stats.component_2_sample) {
7692 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7693 }
7694 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7695 for (const auto& s : stats.component_3_sample) {
7696 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7697 }
7698 }
7699 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007700}
7701
7702binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7703 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007704 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007705}
7706
Huihong Luo37396db2022-02-15 10:43:00 -08007707binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7708 bool* outIsWideColorDisplay) {
7709 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007710 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007711}
7712
Huihong Luo02186fb2022-02-23 14:21:54 -08007713binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7714 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7715 const sp<gui::IRegionSamplingListener>& listener) {
7716 status_t status = checkReadFrameBufferPermission();
7717 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007718 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007719 }
7720 android::Rect rect;
7721 rect.left = samplingArea.left;
7722 rect.top = samplingArea.top;
7723 rect.right = samplingArea.right;
7724 rect.bottom = samplingArea.bottom;
7725 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007726 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007727}
7728
7729binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7730 const sp<gui::IRegionSamplingListener>& listener) {
7731 status_t status = checkReadFrameBufferPermission();
7732 if (status == OK) {
7733 status = mFlinger->removeRegionSamplingListener(listener);
7734 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007735 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007736}
7737
7738binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7739 const sp<gui::IFpsListener>& listener) {
7740 status_t status = checkReadFrameBufferPermission();
7741 if (status == OK) {
7742 status = mFlinger->addFpsListener(taskId, listener);
7743 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007744 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007745}
7746
7747binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7748 status_t status = checkReadFrameBufferPermission();
7749 if (status == OK) {
7750 status = mFlinger->removeFpsListener(listener);
7751 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007752 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007753}
7754
7755binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7756 const sp<gui::ITunnelModeEnabledListener>& listener) {
7757 status_t status = checkAccessPermission();
7758 if (status == OK) {
7759 status = mFlinger->addTunnelModeEnabledListener(listener);
7760 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007761 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007762}
7763
7764binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7765 const sp<gui::ITunnelModeEnabledListener>& listener) {
7766 status_t status = checkAccessPermission();
7767 if (status == OK) {
7768 status = mFlinger->removeTunnelModeEnabledListener(listener);
7769 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007770 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007771}
7772
7773binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7774 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7775 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7776 float appRequestRefreshRateMax) {
7777 status_t status = checkAccessPermission();
7778 if (status == OK) {
7779 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7780 static_cast<ui::DisplayModeId>(defaultMode),
7781 allowGroupSwitching, primaryRefreshRateMin,
7782 primaryRefreshRateMax,
7783 appRequestRefreshRateMin,
7784 appRequestRefreshRateMax);
7785 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007786 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007787}
7788
7789binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7790 gui::DisplayModeSpecs* outSpecs) {
7791 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007792 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007793 }
7794
7795 status_t status = checkAccessPermission();
7796 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007797 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007798 }
7799
7800 ui::DisplayModeId displayModeId;
7801 bool allowGroupSwitching;
7802 float primaryRefreshRateMin;
7803 float primaryRefreshRateMax;
7804 float appRequestRefreshRateMin;
7805 float appRequestRefreshRateMax;
7806 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7807 &allowGroupSwitching, &primaryRefreshRateMin,
7808 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7809 &appRequestRefreshRateMax);
7810 if (status == NO_ERROR) {
7811 outSpecs->defaultMode = displayModeId;
7812 outSpecs->allowGroupSwitching = allowGroupSwitching;
7813 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7814 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7815 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7816 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7817 }
7818
Huihong Luo3bdef862022-03-03 11:57:19 -08007819 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007820}
7821
Huihong Luo37396db2022-02-15 10:43:00 -08007822binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7823 bool* outSupport) {
7824 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007825 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007826}
7827
7828binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7829 const gui::DisplayBrightness& brightness) {
7830 status_t status = checkControlDisplayBrightnessPermission();
7831 if (status == OK) {
7832 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7833 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007834 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007835}
7836
7837binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7838 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7839 status_t status = checkControlDisplayBrightnessPermission();
7840 if (status == OK) {
7841 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7842 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007843 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007844}
7845
7846binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7847 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7848 status_t status = checkControlDisplayBrightnessPermission();
7849 if (status == OK) {
7850 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7851 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007852 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007853}
7854
7855binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7856 status_t status = checkAccessPermission();
7857 if (status == OK) {
7858 status = mFlinger->notifyPowerBoost(boostId);
7859 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007860 return binderStatusFromStatusT(status);
7861}
7862
7863binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7864 const gui::Color& spotColor,
7865 float lightPosY, float lightPosZ,
7866 float lightRadius) {
7867 status_t status = checkAccessPermission();
7868 if (status != OK) {
7869 return binderStatusFromStatusT(status);
7870 }
7871
7872 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7873 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7874 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7875 lightPosZ, lightRadius);
7876 return binderStatusFromStatusT(status);
7877}
7878
7879binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7880 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7881 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7882 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7883 if (status != NO_ERROR) {
7884 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7885 return binderStatusFromStatusT(status);
7886 }
7887
7888 if (!support || !support.has_value()) {
7889 outSupport->reset();
7890 } else {
7891 outSupport->emplace();
7892 outSupport->value().format = static_cast<int32_t>(support->format);
7893 outSupport->value().alphaInterpretation =
7894 static_cast<int32_t>(support->alphaInterpretation);
7895 }
7896
7897 return binder::Status::ok();
7898}
7899
7900binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
7901 status_t status;
7902 const int c_uid = IPCThreadState::self()->getCallingUid();
7903 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
7904 status = mFlinger->setOverrideFrameRate(uid, frameRate);
7905 } else {
7906 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
7907 status = PERMISSION_DENIED;
7908 }
7909 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007910}
7911
Huihong Luo02186fb2022-02-23 14:21:54 -08007912binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
7913 const sp<gui::ITransactionTraceListener>& listener) {
7914 status_t status;
7915 IPCThreadState* ipc = IPCThreadState::self();
7916 const int uid = ipc->getCallingUid();
7917 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7918 status = mFlinger->addTransactionTraceListener(listener);
7919 } else {
7920 status = PERMISSION_DENIED;
7921 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007922 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007923}
7924
7925binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
7926 *outPriority = mFlinger->getGpuContextPriority();
7927 return binder::Status::ok();
7928}
7929
7930binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
7931 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007932 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007933}
7934
7935binder::Status SurfaceComposerAIDL::addWindowInfosListener(
7936 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7937 status_t status;
7938 const int uid = IPCThreadState::self()->getCallingUid();
7939 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7940 status = mFlinger->addWindowInfosListener(windowInfosListener);
7941 } else {
7942 status = PERMISSION_DENIED;
7943 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007944 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007945}
7946
7947binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
7948 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7949 status_t status;
7950 const int uid = IPCThreadState::self()->getCallingUid();
7951 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7952 status = mFlinger->removeWindowInfosListener(windowInfosListener);
7953 } else {
7954 status = PERMISSION_DENIED;
7955 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007956 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007957}
7958
Huihong Luo07e72362022-02-14 14:26:04 -08007959status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
7960 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
7961 IPCThreadState* ipc = IPCThreadState::self();
7962 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
7963 ipc->getCallingUid());
7964 return PERMISSION_DENIED;
7965 }
7966 return OK;
7967}
7968
Huihong Luo37396db2022-02-15 10:43:00 -08007969status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
7970 IPCThreadState* ipc = IPCThreadState::self();
7971 const int pid = ipc->getCallingPid();
7972 const int uid = ipc->getCallingUid();
7973 if ((uid != AID_GRAPHICS) &&
7974 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
7975 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
7976 return PERMISSION_DENIED;
7977 }
7978 return OK;
7979}
7980
Huihong Luo02186fb2022-02-23 14:21:54 -08007981status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
7982 IPCThreadState* ipc = IPCThreadState::self();
7983 const int pid = ipc->getCallingPid();
7984 const int uid = ipc->getCallingUid();
7985 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
7986 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
7987 return PERMISSION_DENIED;
7988 }
7989 return OK;
7990}
7991
Dominik Laskowski9dab3432019-03-27 13:21:10 -07007992} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07007993
Mathias Agopian3f844832013-08-07 21:24:32 -07007994#if defined(__gl_h_)
7995#error "don't include gl/gl.h in this file"
7996#endif
7997
7998#if defined(__gl2_h_)
7999#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008000#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008001
8002// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008003#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"