blob: 64fd45ef51363a9583077f6aa2abae6cabca2005 [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 Wall61c58622018-07-18 10:12:20 -0700109#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200110#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200111#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800112#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800113#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700114#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700115#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700116#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100117#include "DisplayHardware/Hal.h"
Xiang Wang839fe5b2022-04-04 17:39:38 +0000118#include "DisplayHardware/PowerAdvisor.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700119#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200120#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800121#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700122#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700123#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800124#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700125#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700126#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400127#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800128#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500129#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200130#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800131#include "LayerVector.h"
132#include "MonitoredProducer.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800133#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800134#include "NativeWindowSurface.h"
135#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700136#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700137#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700138#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700139#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700140#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700141#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700142#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800143#include "StartPropertySetThread.h"
144#include "SurfaceFlingerProperties.h"
145#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800146#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200147#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500148#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800149
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500150#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500151#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
Alec Mourifcedb9c2022-04-11 20:02:17 +0000152#include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500153
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
Tianhao Yao67dd7122022-02-22 17:48:33 +0000158// To enable layer borders in the system, change the below flag to true.
159#undef DOES_CONTAIN_BORDER
160#define DOES_CONTAIN_BORDER false
161
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700163
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700164using namespace std::string_literals;
165
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800166using namespace hardware::configstore;
167using namespace hardware::configstore::V1_0;
168using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800169
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800170using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
171using aidl::android::hardware::graphics::composer3::Capability;
172using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800173using CompositionStrategyPredictionState = android::compositionengine::impl::
174 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800175
Yiwei Zhang5434a782018-12-05 18:06:32 -0800176using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700177using gui::DisplayInfo;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800178using gui::GameMode;
Huihong Luo6fac5232021-11-22 16:05:23 -0800179using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500180using gui::IWindowInfosListener;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800181using gui::LayerMetadata;
chaviw98318de2021-05-19 16:45:23 -0500182using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800183using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700184using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700185using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800186using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700187using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900188
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800189using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
190
Peiyong Line9d809e2020-04-14 13:10:48 -0700191namespace hal = android::hardware::graphics::composer::hal;
192
Steven Thomasb02664d2017-07-26 18:48:28 -0700193namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700194
195#pragma clang diagnostic push
196#pragma clang diagnostic error "-Wswitch-enum"
197
198bool isWideColorMode(const ColorMode colorMode) {
199 switch (colorMode) {
200 case ColorMode::DISPLAY_P3:
201 case ColorMode::ADOBE_RGB:
202 case ColorMode::DCI_P3:
203 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700204 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700205 case ColorMode::BT2100_PQ:
206 case ColorMode::BT2100_HLG:
207 return true;
208 case ColorMode::NATIVE:
209 case ColorMode::STANDARD_BT601_625:
210 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
211 case ColorMode::STANDARD_BT601_525:
212 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
213 case ColorMode::STANDARD_BT709:
214 case ColorMode::SRGB:
215 return false;
216 }
217 return false;
218}
219
220#pragma clang diagnostic pop
221
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100222// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700223constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800224
225float getDensityFromProperty(const char* property, bool required) {
226 char value[PROPERTY_VALUE_MAX];
227 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
228 if (!density && required) {
229 ALOGE("%s must be defined as a build property", property);
230 return FALLBACK_DENSITY;
231 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700232 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800233}
234
Peiyong Lin9d846a52018-11-05 13:18:20 -0800235// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
236bool validateCompositionDataspace(Dataspace dataspace) {
237 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
238}
239
ramindani32cf0602022-03-02 02:30:29 +0000240std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700241 const auto displayIdleTimerMsKey = [displayId] {
242 std::stringstream ss;
243 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
244 return ss.str();
245 }();
246
ramindani32cf0602022-03-02 02:30:29 +0000247 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
248 if (displayIdleTimerMs > 0) {
249 return std::chrono::milliseconds(displayIdleTimerMs);
250 }
251
252 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
253 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
254 return std::chrono::milliseconds(millis);
255}
256
257bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700258 const auto displaySupportKernelIdleTimerKey = [displayId] {
259 std::stringstream ss;
260 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
261 return ss.str();
262 }();
263
Ady Abraham6d885932021-09-03 18:05:48 -0700264 const auto displaySupportKernelIdleTimer =
265 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000266 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700267}
268
Steven Thomasb02664d2017-07-26 18:48:28 -0700269} // namespace anonymous
270
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800271// ---------------------------------------------------------------------------
272
Mathias Agopian99b49842011-06-27 16:05:52 -0700273const String16 sHardwareTest("android.permission.HARDWARE_TEST");
274const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800275const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700276const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400277const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700278const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500279const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000280const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500281
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800282const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700283
Vishnu Nair4fb00ed2022-06-03 10:25:09 -0700284static const int MAX_TRACING_MEMORY = 1024 * 1024 * 1024; // 1GB
285
Mathias Agopian99b49842011-06-27 16:05:52 -0700286// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700288bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800289bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800290int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100291uint32_t SurfaceFlinger::maxGraphicsWidth;
292uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600293bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700294bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700295Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
296ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
297Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
298ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000299LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700300
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800301std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
302 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800303 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700304 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800305 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700306 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800307 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700308 return std::string("Enhanced");
309 default:
310 return std::string("Unknown ") +
311 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800312 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800313}
314
Hongwei Wang46213ea2020-12-04 17:17:31 -0800315bool callingThreadHasRotateSurfaceFlingerAccess() {
316 IPCThreadState* ipc = IPCThreadState::self();
317 const int pid = ipc->getCallingPid();
318 const int uid = ipc->getCallingUid();
319 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
320 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
321}
322
Leon Scroggins9a20f722021-12-28 14:43:12 +0000323bool callingThreadHasInternalSystemWindowAccess() {
324 IPCThreadState* ipc = IPCThreadState::self();
325 const int pid = ipc->getCallingPid();
326 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500327 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
328 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000329}
330
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700331SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
332 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800333 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000334 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700335 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800336 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800337 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700338 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700339 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700340 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800341 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700342 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000343 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Patrick Williams641f7f22022-06-22 19:25:35 +0000344 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make()) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700345 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700346}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800347
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700348SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800349 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800350
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900351 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900353 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700354
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900355 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700356
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900357 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800358
Brian Lindahla13f2d52020-03-05 11:54:17 +0100359 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
360 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
361
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900362 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900363 mDefaultCompositionDataspace =
364 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700365 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
366 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900367 defaultCompositionDataspace = mDefaultCompositionDataspace;
368 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
369 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
370 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
371 wideColorGamutCompositionPixelFormat =
372 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700373
Yichi Chenda901bf2019-06-28 14:58:27 +0800374 mColorSpaceAgnosticDataspace =
375 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
376
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700377 mLayerCachingEnabled = [] {
378 const bool enable =
379 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
380 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
381 }();
382
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900383 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800384
Sundong Ahn85131bd2019-02-18 15:51:53 +0900385 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800386
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800387 // debugging stuff...
388 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700389
Mathias Agopianb4b17302013-03-20 18:36:41 -0700390 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700391 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700392
Alec Mouri5f487d42020-02-06 09:26:19 -0800393 property_get("ro.build.type", value, "user");
394 mIsUserBuild = strcmp(value, "user") == 0;
395
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700396 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000397
398 // DDMS debugging deprecated (b/120782499)
399 property_get("debug.sf.ddms", value, "0");
400 int debugDdms = atoi(value);
401 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700402
Ady Abrahamadb9a992019-09-19 21:21:55 +0000403 property_get("debug.sf.enable_gl_backpressure", value, "0");
404 mPropagateBackpressureClientComposition = atoi(value);
405 ALOGI_IF(mPropagateBackpressureClientComposition,
406 "Enabling backpressure propagation for Client Composition");
407
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800408 property_get("ro.surface_flinger.supports_background_blur", value, "0");
409 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700410 mSupportsBlur = supportsBlurs;
411 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800412 property_get("ro.sf.blurs_are_expensive", value, "0");
413 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800414
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700415 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700416 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
417 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800418 mGraphicBufferProducerListSizeLogThreshold =
419 std::max(static_cast<int>(0.95 *
420 static_cast<double>(mMaxGraphicBufferProducerListSize)),
421 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700422
Dan Stozaec460082018-12-17 15:35:09 -0800423 property_get("debug.sf.luma_sampling", value, "1");
424 mLumaSampling = atoi(value);
425
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800426 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800427 mDisableClientCompositionCache = atoi(value);
428
Vishnu Nair3539d812022-02-26 09:20:17 -0800429 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800430 mPredictCompositionStrategy = atoi(value);
431
Alec Mouridda07d92022-04-25 22:39:25 +0000432 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
433 mTreat170mAsSrgb = atoi(value);
434
Romain Guy11d63f42017-07-20 12:47:14 -0700435 // We should be reading 'persist.sys.sf.color_saturation' here
436 // but since /data may be encrypted, we need to wait until after vold
437 // comes online to attempt to read the property. The property is
438 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800439
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700440 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800441 // Without the override SurfaceFlinger cannot connect to HIDL
442 // services that are not listed in the manifests. Considered
443 // deriving the setting from the set service name, but it
444 // would be brittle if the name that's not 'default' is used
445 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700446 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000447 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800448 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800449
Ady Abraham29d0da32020-07-16 18:39:33 -0700450 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400451
Dominik Laskowski46471e62022-01-14 15:34:03 -0800452 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
453 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800454 }
John Reck49d9ad32022-02-23 19:03:31 -0500455
456 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
Matt Buckley50c44062022-01-17 20:48:10 +0000457
458 // Power hint session mode, representing which hint(s) to send: early, late, or both)
459 mPowerHintSessionMode =
460 {.late = base::GetBoolProperty("debug.sf.send_late_power_session_hint"s, true),
461 .early = base::GetBoolProperty("debug.sf.send_early_power_session_hint"s, true)};
ramindani4d48f902021-09-20 21:07:45 +0000462}
463
464LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
465 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
466 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000467 }
Ady Abraham9dada822022-02-03 10:26:59 -0800468
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000469 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800470 return LatchUnsignaledConfig::AutoSingleLayer;
471 }
472
473 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800474}
475
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700476SurfaceFlinger::~SurfaceFlinger() = default;
477
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700478void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800479 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700480 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800481
Dominik Laskowski756b7892021-08-04 12:53:59 -0700482 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000483 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800484
Andy McFadden13a082e2012-08-24 10:16:42 -0700485 // restore initial conditions (default device unblank, etc)
486 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800487
488 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700489 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800490}
491
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700492void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700493 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800494}
495
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700496sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700497 // onTransact already checks for some permissions, but adding an additional check here.
498 // This is to ensure that only system and graphics can request to create a secure
499 // display. Secure displays can show secure content so we add an additional restriction on it.
500 const int uid = IPCThreadState::self()->getCallingUid();
501 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
502 ALOGE("Only privileged processes can create a secure display");
503 return nullptr;
504 }
505
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506 class DisplayToken : public BBinder {
507 sp<SurfaceFlinger> flinger;
508 virtual ~DisplayToken() {
509 // no more references, this display must be terminated
510 Mutex::Autolock _l(flinger->mStateLock);
511 flinger->mCurrentState.displays.removeItem(this);
512 flinger->setTransactionFlags(eDisplayTransactionNeeded);
513 }
514 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700515 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516 : flinger(flinger) {
517 }
518 };
519
520 sp<BBinder> token = new DisplayToken(this);
521
522 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700523 // Display ID is assigned when virtual display is allocated by HWC.
524 DisplayDeviceState state;
525 state.isSecure = secure;
526 state.displayName = displayName;
527 mCurrentState.displays.add(token, state);
528 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700529 return token;
530}
531
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700532void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700533 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700534
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700535 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700536 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800537 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700538 return;
539 }
540
Dominik Laskowski075d3172018-05-24 15:50:06 -0700541 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700542 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800543 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700544 return;
545 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700546 mInterceptor->saveDisplayDeletion(state.sequenceId);
547 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700548 setTransactionFlags(eDisplayTransactionNeeded);
549}
550
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800551void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
552 auto& generator = mVirtualDisplayIdGenerators.hal;
553 if (!generator && enable) {
554 ALOGI("Enabling HAL virtual displays");
555 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
556 } else if (generator && !enable) {
557 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
558 generator.reset();
559 }
560}
561
Dominik Laskowski263eec42021-07-21 23:13:24 -0700562VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
563 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800564 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
565 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700566 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800567 return *id;
568 }
569
570 generator->releaseId(*id);
571 } else {
572 ALOGW("%s: Exhausted HAL virtual displays", __func__);
573 }
574
575 ALOGW("%s: Falling back to GPU virtual display", __func__);
576 }
577
578 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
579 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
580 return *id;
581}
582
583void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
584 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
585 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
586 generator->releaseId(*id);
587 }
588 return;
589 }
590
591 const auto id = GpuVirtualDisplayId::tryCast(displayId);
592 LOG_ALWAYS_FATAL_IF(!id);
593 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
594}
595
Ady Abrahamed3290f2021-05-17 15:12:14 -0700596std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800597 std::vector<PhysicalDisplayId> displayIds;
598 displayIds.reserve(mPhysicalDisplayTokens.size());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700599
Dominik Laskowski3c363242022-04-07 10:44:12 -0700600 const auto defaultDisplayId = getDefaultDisplayDeviceLocked()->getPhysicalId();
Ady Abraham2a0066d2021-07-15 20:16:58 -0700601 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800602
603 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700604 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200605 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800606 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700607 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700608
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800609 return displayIds;
610}
611
Vishnu Nair8c8db542021-09-17 19:51:45 -0700612status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
613 Mutex::Autolock lock(mStateLock);
Dominik Laskowski3c363242022-04-07 10:44:12 -0700614 *id = getPrimaryDisplayIdLocked();
Vishnu Nair8c8db542021-09-17 19:51:45 -0700615 return NO_ERROR;
616}
617
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800618sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
619 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200620 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700621}
622
Ady Abraham37965d42018-11-01 13:43:32 -0700623status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
624 if (!outGetColorManagement) {
625 return BAD_VALUE;
626 }
627 *outGetColorManagement = useColorManagement;
628 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700629}
630
Lloyd Pique441d5042018-10-18 16:49:51 -0700631HWComposer& SurfaceFlinger::getHwComposer() const {
632 return mCompositionEngine->getHwComposer();
633}
634
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700635renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
636 return mCompositionEngine->getRenderEngine();
637}
638
Lloyd Pique70d91362018-10-18 16:02:55 -0700639compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
640 return *mCompositionEngine.get();
641}
642
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100643void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700644 if (mBootFinished == true) {
645 ALOGE("Extra call to bootFinished");
646 return;
647 }
648 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700649 if (mStartPropertySetThread->join() != NO_ERROR) {
650 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800651 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700652
653 if (mRenderEnginePrimeCacheFuture.valid()) {
654 mRenderEnginePrimeCacheFuture.get();
655 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800656 const nsecs_t now = systemTime();
657 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000658 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700659
Mikael Pessa90092f42019-08-26 17:22:04 -0700660 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700661 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700662 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700663
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700664 // wait patiently for the window manager death
665 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700666 mWindowManager = defaultServiceManager()->getService(name);
667 if (mWindowManager != 0) {
668 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700669 }
670
671 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700672 // formerly we would just kill the process, but we now ask it to exit so it
673 // can choose where to stop the animation.
674 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700675
676 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
677 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
678 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700679
Denis Hsue70cc6c2020-06-17 10:17:30 +0800680 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
681
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000682 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800683 if (input == nullptr) {
684 ALOGE("Failed to link to input service");
685 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700686 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800687 }
688
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800689 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000690 mPowerAdvisor->onBootFinished();
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000691 const bool powerHintEnabled = mFlagManager.use_adpf_cpu_hint();
692 mPowerAdvisor->enablePowerHint(powerHintEnabled);
693 const bool powerHintUsed = mPowerAdvisor->usePowerHintSession();
694 ALOGD("Power hint is %s",
695 powerHintUsed ? "supported" : (powerHintEnabled ? "unsupported" : "disabled"));
696 if (powerHintUsed) {
Xiang Wang76236e12022-03-22 17:25:30 +0000697 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
698 std::vector<int32_t> tidList;
699 tidList.emplace_back(gettid());
700 if (renderEngineTid.has_value()) {
701 tidList.emplace_back(*renderEngineTid);
702 }
Xiang Wang839fe5b2022-04-04 17:39:38 +0000703 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000704 ALOGW("Cannot start power hint session");
705 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000706 }
707
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800708 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800709
Ady Abraham8a82ba62020-01-17 12:43:17 -0800710 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800711 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800712 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800713 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800714}
715
Dan Stoza436ccf32018-06-21 12:10:12 -0700716uint32_t SurfaceFlinger::getNewTexture() {
717 {
718 std::lock_guard lock(mTexturePoolMutex);
719 if (!mTexturePool.empty()) {
720 uint32_t name = mTexturePool.back();
721 mTexturePool.pop_back();
722 ATRACE_INT("TexturePoolSize", mTexturePool.size());
723 return name;
724 }
725
726 // The pool was too small, so increase it for the future
727 ++mTexturePoolSize;
728 }
729
730 // The pool was empty, so we need to get a new texture name directly using a
731 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700732 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700733 uint32_t name = 0;
734 getRenderEngine().genTextures(1, &name);
735 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700736 };
737 if (std::this_thread::get_id() == mMainThreadId) {
738 return genTextures();
739 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700740 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700741 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700742}
743
Mathias Agopian3f844832013-08-07 21:24:32 -0700744void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700745 std::lock_guard lock(mTexturePoolMutex);
746 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
747 // to actually delete this or not based on mTexturePoolSize
748 mTexturePool.push_back(texture);
749 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700750}
751
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500752static std::optional<renderengine::RenderEngine::RenderEngineType>
753chooseRenderEngineTypeViaSysProp() {
754 char prop[PROPERTY_VALUE_MAX];
755 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
756
757 if (strcmp(prop, "gles") == 0) {
758 return renderengine::RenderEngine::RenderEngineType::GLES;
759 } else if (strcmp(prop, "threaded") == 0) {
760 return renderengine::RenderEngine::RenderEngineType::THREADED;
761 } else if (strcmp(prop, "skiagl") == 0) {
762 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
763 } else if (strcmp(prop, "skiaglthreaded") == 0) {
764 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
765 } else {
766 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
767 return {};
768 }
769}
770
Wei Wangf9b05ee2017-07-19 20:59:39 -0700771// Do not call property_set on main thread which will be blocked by init
772// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700773void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700774 ALOGI( "SurfaceFlinger's main thread ready to run. "
775 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700776 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800777
Steven Thomasb02664d2017-07-26 18:48:28 -0700778 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700779 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800780 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500781 auto builder = renderengine::RenderEngineCreationArgs::Builder()
782 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
783 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
784 .setUseColorManagerment(useColorManagement)
785 .setEnableProtectedContext(enable_protected_contents(false))
786 .setPrecacheToneMapperShaderOnly(false)
787 .setSupportsBackgroundBlur(mSupportsBlur)
788 .setContextPriority(
789 useContextPriority
790 ? renderengine::RenderEngine::ContextPriority::REALTIME
791 : renderengine::RenderEngine::ContextPriority::MEDIUM);
792 if (auto type = chooseRenderEngineTypeViaSysProp()) {
793 builder.setRenderEngineType(type.value());
794 }
795 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700796 mMaxRenderTargetSize =
797 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700798
799 // Set SF main policy after initializing RenderEngine which has its own policy.
800 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
801 ALOGW("Failed to set main task profile");
802 }
803
Alec Mourie4034bb2019-11-19 12:45:54 -0800804 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700805 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800806 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000807 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800808
Ady Abraham9dada822022-02-03 10:26:59 -0800809 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
810
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800811 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
812 enableHalVirtualDisplays(true);
813 }
814
Lloyd Piqueba04e622017-12-14 17:11:26 -0800815 // Process any initial hotplug and resulting display changes.
816 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700817 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700818 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200819 const auto displayId = display->getPhysicalId();
820 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700821 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800822
Mathias Agopian92a979a2012-08-02 18:32:23 -0700823 // initialize our drawing state
824 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700825
Andy McFadden13a082e2012-08-24 10:16:42 -0700826 // set initial conditions (e.g. unblank default device)
827 initializeDisplays();
828
Xiang Wang839fe5b2022-04-04 17:39:38 +0000829 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700830
Steven Thomas137d4bc2019-07-25 16:55:14 -0700831 char primeShaderCache[PROPERTY_VALUE_MAX];
832 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
833 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700834 if (setSchedFifo(false) != NO_ERROR) {
835 ALOGW("Can't set SCHED_OTHER for primeCache");
836 }
837
838 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
839
840 if (setSchedFifo(true) != NO_ERROR) {
841 ALOGW("Can't set SCHED_OTHER for primeCache");
842 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700843 }
Dan Stoza4e637772016-07-28 13:31:51 -0700844
Ady Abrahamed3290f2021-05-17 15:12:14 -0700845 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400846
Wei Wangf9b05ee2017-07-19 20:59:39 -0700847 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700848
849 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800850 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700851 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700852
853 if (mStartPropertySetThread->Start() != NO_ERROR) {
854 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800855 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800856
Dan Stoza9e56aa02015-11-02 13:00:03 -0800857 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700858}
859
Romain Guy11d63f42017-07-20 12:47:14 -0700860void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700861 Mutex::Autolock _l(mStateLock);
862
Romain Guy11d63f42017-07-20 12:47:14 -0700863 char value[PROPERTY_VALUE_MAX];
864
865 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800866 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700867 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800868 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100869
870 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700871 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800872
873 property_get("persist.sys.sf.color_mode", value, "0");
874 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700875}
876
Mathias Agopiana67e4182012-06-19 17:26:12 -0700877void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800878 // Start boot animation service by setting a property mailbox
879 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700880 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800881 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700882 if (mStartPropertySetThread->join() != NO_ERROR) {
883 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800884 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700885}
886
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800887// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800888
Brian Anderson6b376712017-04-04 10:51:39 -0700889status_t SurfaceFlinger::getSupportedFrameTimestamps(
890 std::vector<FrameEvent>* outSupported) const {
891 *outSupported = {
892 FrameEvent::REQUESTED_PRESENT,
893 FrameEvent::ACQUIRE,
894 FrameEvent::LATCH,
895 FrameEvent::FIRST_REFRESH_START,
896 FrameEvent::LAST_REFRESH_START,
897 FrameEvent::GPU_COMPOSITION_DONE,
898 FrameEvent::DEQUEUE_READY,
899 FrameEvent::RELEASE,
900 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800901
902 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
903
Ady Abrahamde549d42022-01-26 19:19:17 -0800904 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700905 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
906 }
907 return NO_ERROR;
908}
909
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800910status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
911 if (!displayToken || !state) {
912 return BAD_VALUE;
913 }
914
915 Mutex::Autolock lock(mStateLock);
916
917 const auto display = getDisplayDeviceLocked(displayToken);
918 if (!display) {
919 return NAME_NOT_FOUND;
920 }
921
922 state->layerStack = display->getLayerStack();
923 state->orientation = display->getOrientation();
924
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200925 const Rect layerStackRect = display->getLayerStackSpaceRect();
926 state->layerStackSpaceRect =
927 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800928
929 return NO_ERROR;
930}
931
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100932status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
933 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800934 if (!displayToken || !info) {
935 return BAD_VALUE;
936 }
937
938 Mutex::Autolock lock(mStateLock);
939
940 const auto display = getDisplayDeviceLocked(displayToken);
941 if (!display) {
942 return NAME_NOT_FOUND;
943 }
944
Dominik Laskowski55c85402020-01-21 16:25:47 -0800945 if (const auto connectionType = display->getConnectionType())
946 info->connectionType = *connectionType;
947 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800948 return INVALID_OPERATION;
949 }
950
951 if (mEmulatedDisplayDensity) {
952 info->density = mEmulatedDisplayDensity;
953 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100954 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800955 ? mInternalDisplayDensity
956 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800957 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700958 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800959
960 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200961 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000962 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800963
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800964 return NO_ERROR;
965}
966
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100967status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
968 ui::DynamicDisplayInfo* info) {
969 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700970 return BAD_VALUE;
971 }
972
Dominik Laskowski22488f62019-03-28 09:53:04 -0700973 Mutex::Autolock lock(mStateLock);
974
Marin Shalamanov5801c942020-12-17 17:00:13 +0100975 const auto display = getDisplayDeviceLocked(displayToken);
976 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700977 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700978 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700979
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700980 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
981 if (!displayId) {
982 return INVALID_OPERATION;
983 }
984
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800985 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700986
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100987 const auto& supportedModes = display->getSupportedModes();
988 info->supportedDisplayModes.clear();
989 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800990
991 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100992 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800993 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700994
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800995 auto [width, height] = mode->getResolution();
996 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700997
ramindani06e518e2022-03-14 18:47:53 +0000998 if (const auto physicalOrientation = display->getPhysicalOrientation();
999 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001000 std::swap(width, height);
1001 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -07001002 }
1003
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001004 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -08001005
Huan Songf7eeb102022-03-28 11:02:38 -07001006 outMode.xDpi = xDpi;
1007 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001008
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001009 const nsecs_t period = mode->getVsyncPeriod();
1010 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001011
Ady Abraham8287e852020-08-12 14:44:58 -07001012 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001013 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001014 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1015 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1016 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001017
Andy McFadden91b2ca82014-06-13 14:04:23 -07001018 // This is how far in advance a buffer must be queued for
1019 // presentation at a given time. If you want a buffer to appear
1020 // on the screen at time N, you must submit the buffer before
1021 // (N - presentationDeadline).
1022 //
1023 // Normally it's one full refresh period (to give SF a chance to
1024 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001025 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001026 // composer or panel must be accounted for here.
1027 //
1028 // We add an additional 1ms to allow for processing time and
1029 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001030 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001031
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001032 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001033 }
1034
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001035 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001036 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001037 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001038
Marin Shalamanovb173f752021-02-16 19:38:36 +01001039 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001040 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001041 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001042 info->gameContentTypeSupported =
1043 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001044
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001045 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001046
1047 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001048 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1049 if (const auto modeId = display->translateModeId(*hwcId)) {
1050 info->preferredBootDisplayMode = modeId->value();
1051 }
1052 }
1053 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001054
Dan Stoza7f7da322014-05-02 15:26:25 -07001055 return NO_ERROR;
1056}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001057
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001058status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* outStats) {
1059 if (!outStats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001060 return BAD_VALUE;
1061 }
1062
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001063 const auto& schedule = mScheduler->getVsyncSchedule();
1064 outStats->vsyncTime = schedule.vsyncDeadlineAfter(scheduler::SchedulerClock::now()).ns();
1065 outStats->vsyncPeriod = schedule.period().ns();
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001066 return NO_ERROR;
1067}
1068
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001069void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001070 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001071
1072 if (!info.mode) {
1073 ALOGW("requested display mode is null");
1074 return;
1075 }
1076 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001077 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001078 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001079 return;
1080 }
1081
Ady Abraham690f4612021-07-01 23:24:03 -07001082 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001083 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001084
Alec Mouri754c98a2019-03-18 18:53:42 -07001085 // Start receiving vsync samples now, so that we can detect a period
1086 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001087 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001088 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001089 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001090 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001091
Ady Abraham690f4612021-07-01 23:24:03 -07001092 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001093 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001094 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001095}
1096
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001097status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001098 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001099
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001100 if (!displayToken) {
1101 return BAD_VALUE;
1102 }
Ady Abraham838de062019-02-04 10:24:03 -08001103
Dominik Laskowski756b7892021-08-04 12:53:59 -07001104 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001105 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001106 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001107 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001108 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001109 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001110 }
1111
1112 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001113 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001114 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001115 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001116
1117 const auto mode = display->getMode(DisplayModeId{modeId});
1118 if (!mode) {
1119 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1120 return BAD_VALUE;
1121 }
1122
1123 const auto fps = mode->getFps();
1124 // Keep the old switching type.
1125 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001126 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001127 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1128 allowGroupSwitching,
1129 {fps, fps}};
1130 constexpr bool kOverridePolicy = false;
1131
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001132 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001133 });
1134
1135 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001136}
1137
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001138void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001139 ATRACE_CALL();
1140
Dominik Laskowski22488f62019-03-28 09:53:04 -07001141 const auto display = getDefaultDisplayDeviceLocked();
1142 if (!display) {
1143 return;
1144 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001145
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001146 const auto upcomingModeInfo =
1147 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1148
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001149 if (!upcomingModeInfo.mode) {
1150 // There is no pending mode change. This can happen if the active
1151 // display changed and the mode change happened on a different display.
1152 return;
1153 }
1154
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001155 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001156 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1157 // We need to generate new sequenceId in order to recreate the display (and this
1158 // way the framebuffer).
1159 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001160 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001161 processDisplayChangesLocked();
1162
1163 // processDisplayChangesLocked will update all necessary components so we're done here.
1164 return;
1165 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001166
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001167 // We just created this display so we can call even if we are not on the main thread.
1168 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001169 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001170
Ady Abraham690f4612021-07-01 23:24:03 -07001171 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001172 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001173 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001174
Dominik Laskowski068173d2021-08-11 17:22:59 -07001175 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001176 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001177 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001178}
1179
Ady Abraham690f4612021-07-01 23:24:03 -07001180void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1181 display->clearDesiredActiveModeState();
1182 if (isDisplayActiveLocked(display)) {
1183 mScheduler->setModeChangePending(false);
1184 }
Ady Abraham53852a52019-05-28 18:07:44 -07001185}
1186
Ady Abraham690f4612021-07-01 23:24:03 -07001187void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1188 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1189 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001190 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001191 updatePhaseConfiguration(refreshRate);
1192}
1193
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001194void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001195 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001196
Marin Shalamanovdd594312021-11-09 16:37:37 +01001197 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1198
Ady Abraham690f4612021-07-01 23:24:03 -07001199 for (const auto& iter : mDisplays) {
1200 const auto& display = iter.second;
1201 if (!display || !display->isInternal()) {
1202 continue;
1203 }
1204
1205 // Store the local variable to release the lock.
1206 const auto desiredActiveMode = display->getDesiredActiveMode();
1207 if (!desiredActiveMode) {
1208 // No desired active mode pending to be applied
1209 continue;
1210 }
1211
1212 if (!isDisplayActiveLocked(display)) {
1213 // display is no longer the active display, so abort the mode change
1214 clearDesiredActiveModeState(display);
1215 continue;
1216 }
1217
1218 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1219 if (!desiredMode) {
1220 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1221 desiredActiveMode->mode->getId().value());
1222 clearDesiredActiveModeState(display);
1223 continue;
1224 }
1225
1226 const auto refreshRate = desiredMode->getFps();
1227 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1228 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1229 to_string(display->getId()).c_str());
1230
1231 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001232 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001233 desiredActiveModeChangeDone(display);
1234 continue;
1235 }
1236
1237 // Desired active mode was set, it is different than the mode currently in use, however
1238 // allowed modes might have changed by the time we process the refresh.
1239 // Make sure the desired mode is still allowed
1240 const auto displayModeAllowed =
1241 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1242 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001243 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001244 continue;
1245 }
1246
1247 // TODO(b/142753666) use constrains
1248 hal::VsyncPeriodChangeConstraints constraints;
1249 constraints.desiredTimeNanos = systemTime();
1250 constraints.seamlessRequired = false;
1251 hal::VsyncPeriodChangeTimeline outTimeline;
1252
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001253 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1254 display->initiateModeChange(*desiredActiveMode,
1255 constraints, &outTimeline));
1256
Ady Abraham690f4612021-07-01 23:24:03 -07001257 if (status != NO_ERROR) {
1258 // initiateModeChange may fail if a hotplug event is just about
1259 // to be sent. We just log the error in this case.
1260 ALOGW("initiateModeChange failed: %d", status);
1261 continue;
1262 }
1263 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1264
Marin Shalamanovdd594312021-11-09 16:37:37 +01001265 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001266 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001267 mSetActiveModePending = true;
1268 } else {
1269 // Updating the internal state should be done outside the loop,
1270 // because it can recreate a DisplayDevice and modify mDisplays
1271 // which will invalidate the iterator.
1272 displayToUpdateImmediately = display->getPhysicalId();
1273 }
1274 }
1275
1276 if (displayToUpdateImmediately) {
1277 updateInternalStateWithChangedMode();
1278
1279 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1280 const auto desiredActiveMode = display->getDesiredActiveMode();
1281 if (desiredActiveMode &&
1282 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1283 desiredActiveModeChangeDone(display);
1284 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001285 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001286}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001287
Alec Mouridea1ac52021-06-23 18:12:18 -07001288void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001289 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001290 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001291 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001292 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001293 for (const auto& [_, display] : mDisplays) {
1294 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001295 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001296 }
1297 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001298 });
1299
1300 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001301}
1302
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001303std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1304 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001305
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001306 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001307 // filter out all wide color modes. The typical reason why this happens is that the
1308 // hardware is not good enough to support GPU composition of wide color, and thus the
1309 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001310 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1311 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001312 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1313 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001314 }
Michael Wright28f24d02016-07-12 13:30:53 -07001315
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001316 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001317}
1318
Daniel Solomon42d04562019-01-20 21:03:19 -08001319status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001320 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001321 if (!displayToken) {
1322 return BAD_VALUE;
1323 }
1324
Dominik Laskowski3c363242022-04-07 10:44:12 -07001325 Mutex::Autolock lock(mStateLock);
1326
1327 const auto display = getDisplayDeviceLocked(displayToken);
1328 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001329 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001330 }
1331
Dominik Laskowski3c363242022-04-07 10:44:12 -07001332 const auto connectionType = display->getConnectionType();
1333 if (connectionType != ui::DisplayConnectionType::Internal) {
1334 return INVALID_OPERATION;
1335 }
1336
1337 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1338 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001339 return NO_ERROR;
1340}
1341
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001342status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001343 if (!displayToken) {
1344 return BAD_VALUE;
1345 }
1346
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001347 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001348 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001349 if (!display) {
1350 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1351 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001352 return NAME_NOT_FOUND;
1353 }
1354
1355 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001356 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1357 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001358 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001359 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001360
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001361 const auto modes = getDisplayColorModes(*display);
1362 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1363
1364 if (mode < ColorMode::NATIVE || !exists) {
1365 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1366 decodeColorMode(mode).c_str(), mode, displayToken.get());
1367 return BAD_VALUE;
1368 }
1369
1370 display->getCompositionDisplay()->setColorProfile(
1371 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1372
1373 return NO_ERROR;
1374 });
1375
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001376 // TODO(b/195698395): Propagate error.
1377 future.wait();
1378 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001379}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001380
Kriti Dang7defaf32021-11-15 11:55:43 +01001381status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001382 auto future = mScheduler->schedule(
1383 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1384
1385 *outSupport = future.get();
1386 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001387}
1388
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001389status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1390 ui::DisplayModeId modeId) {
1391 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001392 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001393 const auto display = getDisplayDeviceLocked(displayToken);
1394 if (!display) {
1395 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1396 return NAME_NOT_FOUND;
1397 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001398
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001399 if (display->isVirtual()) {
1400 ALOGE("%s: Invalid operation on virtual display", whence);
1401 return INVALID_OPERATION;
1402 }
1403
1404 const auto displayId = display->getPhysicalId();
1405 const auto mode = display->getMode(DisplayModeId{modeId});
1406 if (!mode) {
1407 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1408 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001409 return BAD_VALUE;
1410 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001411
1412 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001413 });
1414 return future.get();
1415}
1416
1417status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001418 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001419 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001420 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1421 return getHwComposer().clearBootDisplayMode(*displayId);
1422 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001423 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001424 return BAD_VALUE;
1425 }
1426 });
1427 return future.get();
1428}
1429
Galia Peycheva5492cb52019-10-30 14:13:16 +01001430void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001431 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001432 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001433 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1434 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1435 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001436 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001437 }
1438 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001439}
1440
Galia Peycheva5492cb52019-10-30 14:13:16 +01001441void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001442 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001443 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001444 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001445 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001446 getHwComposer().setContentType(*displayId, type);
1447 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001448 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001449 }
1450 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001451}
1452
Svetoslavd85084b2014-03-20 10:28:31 -07001453status_t SurfaceFlinger::clearAnimationFrameStats() {
1454 Mutex::Autolock _l(mStateLock);
1455 mAnimFrameTracker.clearStats();
1456 return NO_ERROR;
1457}
1458
1459status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1460 Mutex::Autolock _l(mStateLock);
1461 mAnimFrameTracker.getStats(outStats);
1462 return NO_ERROR;
1463}
1464
Kriti Dang49ad4132021-01-08 11:49:56 +01001465status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1466 const std::vector<ui::Hdr>& hdrTypes) {
1467 Mutex::Autolock lock(mStateLock);
1468
1469 auto display = getDisplayDeviceLocked(displayToken);
1470 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001471 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001472 return NAME_NOT_FOUND;
1473 }
1474
1475 display->overrideHdrTypes(hdrTypes);
1476 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1477 return NO_ERROR;
1478}
1479
Tej Singhe2751772021-04-06 22:05:29 -07001480status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1481 *success = mTimeStats->onPullAtom(atomId, pulledData);
1482 return NO_ERROR;
1483}
1484
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001485status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1486 ui::PixelFormat* outFormat,
1487 ui::Dataspace* outDataspace,
1488 uint8_t* outComponentMask) const {
1489 if (!outFormat || !outDataspace || !outComponentMask) {
1490 return BAD_VALUE;
1491 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001492
1493 Mutex::Autolock lock(mStateLock);
1494
1495 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1496 if (!displayId) {
1497 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001498 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001499
1500 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001501 outDataspace, outComponentMask);
1502}
1503
Kevin DuBois74e53772018-11-19 10:52:38 -08001504status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1505 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001506 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001507 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001508 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001509 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1510 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1511 componentMask, maxFrames);
1512 } else {
1513 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1514 return NAME_NOT_FOUND;
1515 }
1516 });
1517
1518 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001519}
1520
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001521status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1522 uint64_t maxFrames, uint64_t timestamp,
1523 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001524 Mutex::Autolock lock(mStateLock);
1525
1526 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1527 if (!displayId) {
1528 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001529 }
1530
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001531 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001532}
1533
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001534status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1535 if (!outSupported) {
1536 return BAD_VALUE;
1537 }
1538 *outSupported = getRenderEngine().supportsProtectedContent();
1539 return NO_ERROR;
1540}
1541
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001542status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1543 bool* outIsWideColorDisplay) const {
1544 if (!displayToken || !outIsWideColorDisplay) {
1545 return BAD_VALUE;
1546 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001547
1548 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001549 const auto display = getDisplayDeviceLocked(displayToken);
1550 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001551 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001552 }
Peiyong Linff84a152019-05-17 18:36:19 -07001553
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001554 *outIsWideColorDisplay =
1555 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001556 return NO_ERROR;
1557}
1558
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001559status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001560 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001561 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001562
Dominik Laskowski6505f792019-09-18 11:10:05 -07001563 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001564 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001565 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001566 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001567
Dominik Laskowski756b7892021-08-04 12:53:59 -07001568 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001569 return NO_ERROR;
1570}
1571
1572status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001573 Mutex::Autolock lock(mStateLock);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001574 const nsecs_t expectedPresentTime = calculateExpectedPresentTime(when).ns();
1575 const nsecs_t deadlineTimestamp = expectedPresentTime;
1576 return mScheduler->injectVSync(when, expectedPresentTime, deadlineTimestamp) ? NO_ERROR
1577 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001578}
1579
Huihong Luo05539a12022-02-23 10:29:40 -08001580status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001581 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001582 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001583 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001584 mDrawingState.traverseInZOrder([&](Layer* layer) {
1585 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1586 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001587 });
1588
1589 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001590 return NO_ERROR;
1591}
1592
Peiyong Linc6780972018-10-28 15:24:08 -07001593status_t SurfaceFlinger::getCompositionPreference(
1594 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1595 Dataspace* outWideColorGamutDataspace,
1596 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001597 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001598 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001599 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001600 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001601 return NO_ERROR;
1602}
1603
Dan Stozaec460082018-12-17 15:35:09 -08001604status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1605 const sp<IBinder>& stopLayerHandle,
1606 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001607 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001608 return BAD_VALUE;
1609 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001610
1611 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1612 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001613 return NO_ERROR;
1614}
1615
Dan Stozaec460082018-12-17 15:35:09 -08001616status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001617 if (!listener) {
1618 return BAD_VALUE;
1619 }
Dan Stozaec460082018-12-17 15:35:09 -08001620 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001621 return NO_ERROR;
1622}
Dan Gittik57e63c52019-01-18 16:37:54 +00001623
Alec Mouria9a68a62021-03-04 19:14:50 -08001624status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001625 if (!listener) {
1626 return BAD_VALUE;
1627 }
1628
Alec Mouria9a68a62021-03-04 19:14:50 -08001629 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001630 return NO_ERROR;
1631}
1632
1633status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1634 if (!listener) {
1635 return BAD_VALUE;
1636 }
1637 mFpsReporter->removeListener(listener);
1638 return NO_ERROR;
1639}
1640
Galia Peycheva8f04b302021-04-27 13:25:38 +02001641status_t SurfaceFlinger::addTunnelModeEnabledListener(
1642 const sp<gui::ITunnelModeEnabledListener>& listener) {
1643 if (!listener) {
1644 return BAD_VALUE;
1645 }
1646
1647 mTunnelModeEnabledReporter->addListener(listener);
1648 return NO_ERROR;
1649}
1650
1651status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1652 const sp<gui::ITunnelModeEnabledListener>& listener) {
1653 if (!listener) {
1654 return BAD_VALUE;
1655 }
1656
1657 mTunnelModeEnabledReporter->removeListener(listener);
1658 return NO_ERROR;
1659}
1660
Dan Gittik57e63c52019-01-18 16:37:54 +00001661status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1662 bool* outSupport) const {
1663 if (!displayToken || !outSupport) {
1664 return BAD_VALUE;
1665 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001666
1667 Mutex::Autolock lock(mStateLock);
1668
Dan Gittik57e63c52019-01-18 16:37:54 +00001669 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1670 if (!displayId) {
1671 return NAME_NOT_FOUND;
1672 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001673 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001674 return NO_ERROR;
1675}
1676
Alec Mouricdf16792021-12-10 13:16:06 -08001677bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1678 bool hasHdrLayers = false;
1679 mDrawingState.traverse([&,
1680 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1681 hasHdrLayers |= (layer->isVisible() &&
1682 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1683 isHdrDataspace(layer->getDataSpace()));
1684 });
1685 return hasHdrLayers;
1686}
1687
John Reck22be6962021-03-10 12:59:54 -05001688status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1689 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001690 if (!displayToken) {
1691 return BAD_VALUE;
1692 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001693
Dominik Laskowski756b7892021-08-04 12:53:59 -07001694 const char* const whence = __func__;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001695 return ftl::Future(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001696 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001697 const bool supportsDisplayBrightnessCommand =
1698 getHwComposer().getComposer()->isSupported(
1699 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1700 // If we support applying display brightness as a command, then we also support
1701 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001702 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001703 auto compositionDisplay = display->getCompositionDisplay();
1704 float currentDimmingRatio =
1705 compositionDisplay->editState().sdrWhitePointNits /
1706 compositionDisplay->editState().displayBrightnessNits;
1707 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1708 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001709 FTL_FAKE_GUARD(kMainThreadContext,
1710 display->stageBrightness(brightness.displayBrightness));
1711
Alec Mouri6da0e272022-02-07 12:45:57 -08001712 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1713 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001714 scheduleComposite(FrameHint::kNone);
1715 } else {
1716 scheduleCommit(FrameHint::kNone);
1717 }
1718 return ftl::yield<status_t>(OK);
1719 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001720 return getHwComposer()
1721 .setDisplayBrightness(display->getPhysicalId(),
1722 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001723 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001724 Hwc2::Composer::DisplayBrightnessOptions{
1725 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001726 }
Alec Mouricdf16792021-12-10 13:16:06 -08001727
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001728 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001729 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001730 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001731 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001732 }))
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001733 .then([](ftl::Future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001734 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001735}
1736
John Reck88270902021-03-18 11:27:35 -04001737status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1738 const sp<gui::IHdrLayerInfoListener>& listener) {
1739 if (!displayToken) {
1740 return BAD_VALUE;
1741 }
1742
1743 Mutex::Autolock lock(mStateLock);
1744
1745 const auto display = getDisplayDeviceLocked(displayToken);
1746 if (!display) {
1747 return NAME_NOT_FOUND;
1748 }
1749 const auto displayId = display->getId();
1750 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1751 if (!hdrInfoReporter) {
1752 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1753 }
1754 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001755
1756
1757 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001758 return OK;
1759}
1760
1761status_t SurfaceFlinger::removeHdrLayerInfoListener(
1762 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1763 if (!displayToken) {
1764 return BAD_VALUE;
1765 }
1766
1767 Mutex::Autolock lock(mStateLock);
1768
1769 const auto display = getDisplayDeviceLocked(displayToken);
1770 if (!display) {
1771 return NAME_NOT_FOUND;
1772 }
1773 const auto displayId = display->getId();
1774 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1775 if (hdrInfoReporter) {
1776 hdrInfoReporter->removeListener(listener);
1777 }
1778 return OK;
1779}
1780
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001781status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001782 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001783 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001784
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001785 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001786 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001787 }
1788
1789 return NO_ERROR;
1790}
1791
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001792status_t SurfaceFlinger::getDisplayDecorationSupport(
1793 const sp<IBinder>& displayToken,
1794 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001795 if (!displayToken || !outSupport) {
1796 return BAD_VALUE;
1797 }
1798
1799 Mutex::Autolock lock(mStateLock);
1800
1801 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1802 if (!displayId) {
1803 return NAME_NOT_FOUND;
1804 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001805 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001806 return NO_ERROR;
1807}
1808
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001809// ----------------------------------------------------------------------------
1810
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001811sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001812 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001813 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001814 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1815 ? mSfConnectionHandle
1816 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001817
Ady Abraham62f216c2020-10-13 19:07:23 -07001818 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001819}
1820
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001821void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001822 if (hint == FrameHint::kActive) {
1823 mScheduler->resetIdleTimer();
1824 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001825 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001826 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001827}
1828
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001829void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1830 mMustComposite = true;
1831 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001832}
1833
1834void SurfaceFlinger::scheduleRepaint() {
1835 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001836 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001837}
1838
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001839void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001840 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001841}
1842
Ady Abraham2492a022020-07-24 11:09:55 -07001843nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001844 if (const auto display = getDefaultDisplayDeviceLocked()) {
1845 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001846 }
1847
Marin Shalamanov045b7002021-01-07 16:56:24 +01001848 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001849}
1850
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001851void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1852 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001853 const std::string tracePeriod = [vsyncPeriod]() {
1854 if (ATRACE_ENABLED() && vsyncPeriod) {
1855 std::stringstream ss;
1856 ss << "(" << *vsyncPeriod << ")";
1857 return ss.str();
1858 }
1859 return std::string();
1860 }();
1861 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001862
Steven Thomas3cfac282017-02-06 12:29:30 -08001863 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001864 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1865 if (displayId) {
1866 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1867 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001868 display->onVsync(timestamp);
1869 }
1870
Dominik Laskowski075d3172018-05-24 15:50:06 -07001871 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001872 return;
1873 }
1874
Ady Abrahame1166472021-07-15 10:56:06 -07001875 const bool isActiveDisplay =
1876 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1877 if (!isActiveDisplay) {
1878 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001879 return;
1880 }
1881
Alec Mourif8e689c2019-05-20 18:32:22 -07001882 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001883 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001884 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001885 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001886 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001887}
1888
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001889void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1890 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001891 const bool connected = connection == hal::Connection::CONNECTED;
1892 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001893
Steven Thomasb02664d2017-07-26 18:48:28 -07001894 // Only lock if we're not on the main thread. This function is normally
1895 // called on a hwbinder thread, but for the primary display it's called on
1896 // the main thread with the state lock already held, so don't attempt to
1897 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001898 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001899
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001900 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001901
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001902 if (std::this_thread::get_id() == mMainThreadId) {
1903 // Process all pending hot plug events immediately if we are on the main thread.
1904 processDisplayHotplugEventsLocked();
1905 }
1906
Lloyd Piqueba04e622017-12-14 17:11:26 -08001907 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001908}
1909
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001910void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1911 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001912 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001913 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001914
1915 if (timeline.refreshRequired) {
1916 scheduleComposite(FrameHint::kNone);
1917 }
Ady Abraham7159f572019-10-11 11:10:18 -07001918}
1919
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001920void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001921 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001922 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1923}
1924
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001925void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001926 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001927 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001928}
1929
Yichi Chen3401b562022-01-17 15:42:35 +08001930void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001931 ATRACE_CALL();
1932 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001933}
1934
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001935void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001936 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001937
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001938 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001939 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001940 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001941
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001942 if (const auto display = getDefaultDisplayDeviceLocked();
1943 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001944 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001945 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001946 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001947}
1948
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001949auto SurfaceFlinger::getPreviousPresentFence(nsecs_t frameTime, Period vsyncPeriod)
1950 -> const FenceTimePtr& {
1951 const bool isTwoVsyncsAhead = mExpectedPresentTime - frameTime > vsyncPeriod.ns();
1952 const size_t i = static_cast<size_t>(isTwoVsyncsAhead);
1953 return mPreviousPresentFences[i].fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001954}
1955
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001956bool SurfaceFlinger::isFencePending(const FenceTimePtr& fence, int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001957 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001958 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001959 return false;
1960 }
1961
Dan Stoza59083052020-04-28 10:13:20 -07001962 const status_t status = fence->wait(graceTimeMs);
1963 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1964 // which calls wait(0) again internally
1965 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001966}
1967
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001968TimePoint SurfaceFlinger::calculateExpectedPresentTime(nsecs_t frameTime) const {
1969 const auto& schedule = mScheduler->getVsyncSchedule();
Alec Mouri6d414b52020-03-17 11:18:05 -07001970
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001971 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(TimePoint::fromNs(frameTime));
1972 if (mVsyncModulator->getVsyncConfig().sfOffset > 0) {
1973 return vsyncDeadline;
Alec Mouri6d414b52020-03-17 11:18:05 -07001974 }
1975
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001976 // Inflate the expected present time if we're targeting the next vsync.
1977 return vsyncDeadline + schedule.period();
Alec Mouriaa614192019-06-06 13:28:34 -07001978}
1979
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001980bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1981 FTL_FAKE_GUARD(kMainThreadContext) {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001982 // The expectedVsyncTime, which was predicted when this frame was scheduled, is normally in the
1983 // future relative to frameTime, but may not be for delayed frames. Adjust mExpectedPresentTime
1984 // accordingly, but not mScheduledPresentTime.
Snild Dolkow819636c2021-01-22 14:42:08 +01001985 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001986 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07001987
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001988 // Calculate the expected present time once and use the cached value throughout this frame to
1989 // make sure all layers are seeing this same value.
1990 mExpectedPresentTime = expectedVsyncTime >= frameTime
1991 ? expectedVsyncTime
1992 : calculateExpectedPresentTime(frameTime).ns();
1993
Ady Abraham893c99d2021-04-30 16:00:23 -07001994 const auto vsyncIn = [&] {
1995 if (!ATRACE_ENABLED()) return 0.f;
1996 return (mExpectedPresentTime - systemTime()) / 1e6f;
1997 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001998 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
1999 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002000
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002001 const Period vsyncPeriod = mScheduler->getVsyncSchedule().period();
2002 const FenceTimePtr& previousPresentFence = getPreviousPresentFence(frameTime, vsyncPeriod);
2003
Dan Stoza28d46a52020-04-28 09:54:54 -07002004 // When Backpressure propagation is enabled we want to give a small grace period
2005 // for the present fence to fire instead of just giving up on this frame to handle cases
2006 // where present fence is just about to get signaled.
2007 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002008 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002009
2010 // Pending frames may trigger backpressure propagation.
2011 const TracedOrdinal<bool> framePending = {"PrevFramePending",
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002012 isFencePending(previousPresentFence,
2013 graceTimeForPresentFenceMs)};
Dan Stoza28d46a52020-04-28 09:54:54 -07002014
2015 // Frame missed counts for metrics tracking.
2016 // A frame is missed if the prior frame is still pending. If no longer pending,
2017 // then we still count the frame as missed if the predicted present time
2018 // was further in the past than when the fence actually fired.
2019
2020 // Add some slop to correct for drift. This should generally be
2021 // smaller than a typical frame duration, but should not be so small
2022 // that it reports reasonable drift as a missed frame.
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002023 const nsecs_t frameMissedSlop = vsyncPeriod.ns() / 2;
2024 const nsecs_t previousPresentTime = previousPresentFence->getSignalTime();
Dan Stoza28d46a52020-04-28 09:54:54 -07002025 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2026 framePending ||
2027 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002028 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002029 previousPresentTime - frameMissedSlop))};
2030 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2031 mHadDeviceComposition && frameMissed};
2032 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2033 mHadClientComposition && frameMissed};
2034
2035 if (frameMissed) {
2036 mFrameMissedCount++;
2037 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002038 }
2039
2040 if (hwcFrameMissed) {
2041 mHwcFrameMissedCount++;
2042 }
2043
2044 if (gpuFrameMissed) {
2045 mGpuFrameMissedCount++;
2046 }
2047
Vishnu Nair286f4f92022-06-08 16:37:39 -07002048 if (mTracingEnabledChanged) {
2049 mLayerTracingEnabled = mLayerTracing.isEnabled();
2050 mTracingEnabledChanged = false;
2051 }
2052
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002053 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002054 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002055 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002056 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002057 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002058 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002059 }
2060
2061 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002062 // the mode, hence we update SF.
2063 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002064 {
2065 Mutex::Autolock lock(mStateLock);
2066 updateInternalStateWithChangedMode();
2067 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002068 }
2069
John Reck2ec53912020-07-07 16:53:55 -07002070 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002071 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002072 scheduleCommit(FrameHint::kNone);
2073 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002074 }
2075 }
2076
Matt Buckley50c44062022-01-17 20:48:10 +00002077 // Save this once per commit + composite to ensure consistency
2078 mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession();
2079 if (mPowerHintSessionEnabled) {
2080 nsecs_t vsyncPeriod;
2081 {
2082 Mutex::Autolock lock(mStateLock);
2083 vsyncPeriod = getVsyncPeriodFromHWC();
2084 }
2085 mPowerAdvisor->setCommitStart(frameTime);
2086 mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime);
2087 const nsecs_t idealSfWorkDuration =
2088 mVsyncModulator->getVsyncConfig().sfWorkDuration.count();
2089 // Frame delay is how long we should have minus how long we actually have
2090 mPowerAdvisor->setFrameDelay(idealSfWorkDuration - (mExpectedPresentTime - frameTime));
2091 mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration);
2092 mPowerAdvisor->setTargetWorkDuration(vsyncPeriod);
2093
2094 // Send early hint here to make sure there's not another frame pending
2095 if (mPowerHintSessionMode.early) {
2096 // Send a rough prediction for this frame based on last frame's timing info
2097 mPowerAdvisor->sendPredictedWorkDuration();
2098 }
2099 }
2100
Ady Abraham29d0da32020-07-16 18:39:33 -07002101 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002102 Mutex::Autolock lock(mStateLock);
2103 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002104 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002105 }
2106 }
2107
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002108 // Composite if transactions were committed, or if requested by HWC.
2109 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002110 {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002111 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(vsyncPeriod.ns()));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002112
chaviw6b9ffea2021-11-08 09:25:48 -06002113 bool needsTraversal = false;
2114 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07002115 needsTraversal |= commitCreatedLayers(vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002116 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002117 }
2118
2119 const bool shouldCommit =
2120 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2121 if (shouldCommit) {
2122 commitTransactions();
2123 }
2124
2125 if (transactionFlushNeeded()) {
2126 setTransactionFlags(eTransactionFlushNeeded);
2127 }
2128
2129 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002130 mustComposite |= latchBuffers();
2131
chaviw6b9ffea2021-11-08 09:25:48 -06002132 // This has to be called after latchBuffers because we want to include the layers that have
2133 // been latched in the commit callback
2134 if (!needsTraversal) {
2135 // Invoke empty transaction callbacks early.
2136 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2137 } else {
2138 // Invoke OnCommit callbacks.
2139 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2140 }
2141
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002142 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002143 }
2144
2145 // Layers need to get updated (in the previous line) before we can use them for
2146 // choosing the refresh rate.
2147 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2148 // and may eventually call to ~Layer() if it holds the last reference
2149 {
2150 Mutex::Autolock _l(mStateLock);
2151 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002152 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002153 }
2154
Dan Stoza28d46a52020-04-28 09:54:54 -07002155 updateCursorAsync();
2156 updateInputFlinger();
2157
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002158 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2159 // This will block and tracing should only be enabled for debugging.
Pablo Gamitob8775792022-06-10 15:02:42 +00002160 mLayerTracing.notify(mVisibleRegionsDirty, frameTime, vsyncId);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002161 }
Pablo Gamito6be82442022-06-13 11:04:34 +00002162 mLastCommittedVsyncId = vsyncId;
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002163
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002164 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002165
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002166 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002167}
2168
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002169void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2170 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002171 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002172
Lloyd Piqueab039b52019-02-13 14:22:42 -08002173 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002174 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002175 refreshArgs.outputs.reserve(displays.size());
Matt Buckley50c44062022-01-17 20:48:10 +00002176 std::vector<DisplayId> displayIds;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002177 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002178 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Matt Buckley50c44062022-01-17 20:48:10 +00002179 displayIds.push_back(display->getId());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002180 }
Matt Buckley50c44062022-01-17 20:48:10 +00002181 mPowerAdvisor->setDisplays(displayIds);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002182 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002183 if (auto layerFE = layer->getCompositionEngineLayerFE())
2184 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002185 });
Tianhao Yao67dd7122022-02-22 17:48:33 +00002186
2187 if (DOES_CONTAIN_BORDER) {
2188 refreshArgs.borderInfoList.clear();
2189 mDrawingState.traverse([&refreshArgs](Layer* layer) {
2190 if (layer->isBorderEnabled()) {
2191 compositionengine::BorderRenderInfo info;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00002192 info.width = layer->getBorderWidth();
2193 info.color = layer->getBorderColor();
Tianhao Yao67dd7122022-02-22 17:48:33 +00002194 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2195 info.layerIds.push_back(ilayer->getSequence());
2196 });
2197 refreshArgs.borderInfoList.emplace_back(std::move(info));
2198 }
2199 });
2200 }
2201
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002202 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002203 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002204 if (auto layerFE = layer->getCompositionEngineLayerFE())
2205 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002206 }
2207
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002208 refreshArgs.outputColorSetting = useColorManagement
2209 ? mDisplayColorSetting
2210 : compositionengine::OutputColorSetting::kUnmanaged;
2211 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2212 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002213
2214 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002215 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002216 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002217 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002218
2219 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2220 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2221 mDrawingState.colorMatrixChanged = false;
2222 }
2223
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002224 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002225
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002226 if (mDebugFlashDelay != 0) {
2227 refreshArgs.devOptForceClientComposition = true;
2228 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002229 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002230
Ady Abraham43065bd2021-12-10 17:22:15 -08002231 const auto expectedPresentTime = mExpectedPresentTime.load();
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002232 const auto prevVsyncTime =
2233 TimePoint::fromNs(expectedPresentTime) - mScheduler->getVsyncSchedule().period();
2234
Ady Abrahamcaba2982021-06-16 16:45:04 -07002235 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2236 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002237 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002238 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002239 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002240
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002241 // Store the present time just before calling to the composition engine so we could notify
2242 // the scheduler.
2243 const auto presentTime = systemTime();
2244
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002245 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002246
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002247 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002248
Matt Buckley50c44062022-01-17 20:48:10 +00002249 // Send a power hint hint after presentation is finished
2250 if (mPowerHintSessionEnabled) {
Matt Buckleyc6b9d382022-06-17 15:28:07 -07002251 mPowerAdvisor->setPresentFenceTime(mPreviousPresentFences[0].fenceTime->getSignalTime());
Matt Buckley50c44062022-01-17 20:48:10 +00002252 if (mPowerHintSessionMode.late) {
2253 mPowerAdvisor->sendActualWorkDuration();
2254 }
2255 }
2256
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002257 if (mScheduler->onPostComposition(presentTime)) {
2258 scheduleComposite(FrameHint::kNone);
2259 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002260
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002261 postFrame();
2262 postComposition();
2263
Midas Chien50f52e22020-09-26 17:57:42 +08002264 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002265
Vishnu Nair9cf89262022-02-26 09:17:49 -08002266 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2267 TimeStats::ClientCompositionRecord clientCompositionRecord;
2268 for (const auto& [_, display] : displays) {
2269 const auto& state = display->getCompositionDisplay()->getState();
2270 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2271 mHadDeviceComposition |= state.usesDeviceComposition;
2272 mReusedClientComposition |= state.reusedClientComposition;
2273 clientCompositionRecord.predicted |=
2274 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2275 clientCompositionRecord.predictionSucceeded |=
2276 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002277 }
2278
Vishnu Nair9cf89262022-02-26 09:17:49 -08002279 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2280 clientCompositionRecord.reused = mReusedClientComposition;
2281 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2282 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2283
Yichi Chen28dee2c2020-07-06 21:24:14 +08002284 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002285 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2286 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002287
David Sodman7e4ae112018-02-09 15:02:28 -08002288 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002289 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002290 // This will block and should only be used for debugging.
Pablo Gamitob8775792022-06-10 15:02:42 +00002291 mLayerTracing.notify(mVisibleRegionsDirty, frameTime, vsyncId);
Vishnu Nairdf529052019-06-07 14:53:14 -07002292 }
Robert Carr167bdde2021-07-28 11:26:51 -07002293
2294 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002295 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002296
2297 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002298 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002299 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002300
Matt Buckley50c44062022-01-17 20:48:10 +00002301 if (mPowerHintSessionEnabled) {
2302 mPowerAdvisor->setCompositeEnd(systemTime());
Matt Buckleyef51fba2021-10-12 19:30:12 +00002303 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002304}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002305
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002306void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002307 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002308
Vishnu Nair4351ad52019-02-11 14:13:02 -08002309 if (mVisibleRegionsDirty) {
2310 computeLayerBounds();
2311 }
2312
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002313 for (auto& layer : mLayersPendingRefresh) {
2314 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002315 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002316 invalidateLayerStack(layer, visibleReg);
2317 }
2318 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002319}
2320
John Reck49d9ad32022-02-23 19:03:31 -05002321bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002322 // Treat all layers as non-HDR if:
2323 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2324 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2325 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2326 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2327 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002328 return false;
2329 }
2330 if (mIgnoreHdrCameraLayers) {
2331 auto buffer = layer->getBuffer();
2332 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2333 return false;
2334 }
2335 }
2336 return true;
2337}
2338
ramindani06e518e2022-03-14 18:47:53 +00002339ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2340 bool isPrimary) const {
2341 const auto id = PhysicalDisplayId::tryCast(displayId);
2342 if (!id) {
2343 return ui::ROTATION_0;
2344 }
2345 if (getHwComposer().getComposer()->isSupported(
2346 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2347 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2348 case Hwc2::AidlTransform::ROT_90:
2349 return ui::ROTATION_90;
2350 case Hwc2::AidlTransform::ROT_180:
2351 return ui::ROTATION_180;
2352 case Hwc2::AidlTransform::ROT_270:
2353 return ui::ROTATION_270;
2354 default:
2355 return ui::ROTATION_0;
2356 }
2357 }
2358
2359 if (isPrimary) {
2360 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2361 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2362 case Values::ORIENTATION_90:
2363 return ui::ROTATION_90;
2364 case Values::ORIENTATION_180:
2365 return ui::ROTATION_180;
2366 case Values::ORIENTATION_270:
2367 return ui::ROTATION_270;
2368 default:
2369 break;
2370 }
2371 }
2372 return ui::ROTATION_0;
2373}
2374
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002375void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002376 ATRACE_CALL();
2377 ALOGV("postComposition");
2378
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002379 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002380
2381 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002382 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002383 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002384 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002385 ->getRenderSurface()
2386 ->getClientTargetAcquireFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002387 } else {
2388 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2389 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002390
Ady Abrahambe0f9482019-04-24 15:41:53 -07002391 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002392 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002393 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002394 mPreviousPresentFences[0].fenceTime =
2395 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2396
Vishnu Nair9a69a042021-06-18 13:19:49 -07002397 nsecs_t now = systemTime();
2398
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002399 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2400 // information from previous' frame classification is already available when sending jank info
2401 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002402 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002403 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002404
Lloyd Piqueab039b52019-02-13 14:22:42 -08002405 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2406 // be sampled a little later than when we started doing work for this frame,
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002407 // but that should be okay since CompositorTiming has snapping logic.
Dominik Laskowski80c77272022-07-08 12:47:29 -07002408 const TimePoint compositeTime =
2409 TimePoint::fromNs(mCompositionEngine->getLastFrameRefreshTimestamp());
2410 const Duration presentLatency =
2411 mPresentLatencyTracker.trackPendingFrame(compositeTime,
2412 mPreviousPresentFences[0].fenceTime);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002413
2414 const auto& schedule = mScheduler->getVsyncSchedule();
2415 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(TimePoint::fromNs(now));
2416 const Period vsyncPeriod = schedule.period();
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002417 const nsecs_t vsyncPhase = mVsyncConfiguration->getCurrentConfigs().late.sfOffset;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002418
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002419 const CompositorTiming compositorTiming(vsyncDeadline.ns(), vsyncPeriod.ns(), vsyncPhase,
Dominik Laskowski80c77272022-07-08 12:47:29 -07002420 presentLatency.ns());
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002421
Robert Carrc747ad02021-06-11 14:01:24 -07002422 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002423 layer->onPostComposition(display, glCompositionDoneFenceTime,
2424 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002425 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002426 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002427
John Reck88270902021-03-18 11:27:35 -04002428 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2429 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002430 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002431 {
2432 Mutex::Autolock lock(mStateLock);
2433 if (mFpsReporter) {
2434 mFpsReporter->dispatchLayerFps();
2435 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002436
2437 if (mTunnelModeEnabledReporter) {
2438 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2439 }
John Reck88270902021-03-18 11:27:35 -04002440 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002441 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2442 if (reporter && reporter->hasListeners()) {
2443 if (const auto display = getDisplayDeviceLocked(displayId)) {
2444 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002445 }
2446 }
2447 }
Robert Carr167bdde2021-07-28 11:26:51 -07002448 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2449 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002450 }
2451
Robert Carr167bdde2021-07-28 11:26:51 -07002452 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2453 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2454 HdrLayerInfoReporter::HdrLayerInfo info;
2455 int32_t maxArea = 0;
2456 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2457 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002458 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002459 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002460 const auto* outputLayer =
2461 compositionDisplay->getOutputLayerForLayer(layerFe);
2462 if (outputLayer) {
2463 info.numberOfHdrLayers++;
2464 const auto displayFrame = outputLayer->getState().displayFrame;
2465 const int32_t area = displayFrame.width() * displayFrame.height();
2466 if (area > maxArea) {
2467 maxArea = area;
2468 info.maxW = displayFrame.width();
2469 info.maxH = displayFrame.height();
2470 }
John Reckdb1a16b2021-07-09 13:05:52 -04002471 }
John Reck88270902021-03-18 11:27:35 -04002472 }
2473 }
Robert Carr167bdde2021-07-28 11:26:51 -07002474 });
2475 listener->dispatchHdrLayerInfo(info);
2476 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002477 }
2478
Robert Carr167bdde2021-07-28 11:26:51 -07002479 mSomeDataspaceChanged = false;
2480 mVisibleRegionsWereDirtyThisFrame = false;
2481
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002482 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002483 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002484 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002485
Ady Abrahamed3290f2021-05-17 15:12:14 -07002486 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002487 mPreviousPresentFences[0].fenceTime->isValid()) {
2488 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002489 }
2490
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002491 const bool isDisplayConnected =
2492 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002493
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002494 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002495 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002496 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002497 }
2498 }
2499
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002500 if (mAnimCompositionPending) {
2501 mAnimCompositionPending = false;
2502
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002503 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2504 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002505 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002506 // The HWC doesn't support present fences, so use the refresh
2507 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002508 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002509 mAnimFrameTracker.setActualPresentTime(presentTime);
2510 }
2511 mAnimFrameTracker.advanceFrame();
2512 }
Dan Stozab90cf072015-03-05 11:05:59 -08002513
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002514 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002515
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002516 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002517
Alec Mouri717bcb62020-02-10 17:07:19 -08002518 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2519 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2520 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2521
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002522 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002523 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002524 return;
2525 }
2526
2527 nsecs_t currentTime = systemTime();
2528 if (mHasPoweredOff) {
2529 mHasPoweredOff = false;
2530 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002531 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002532 const size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncPeriod.ns());
David Sodman4a36e932017-11-07 14:29:47 -08002533 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2534 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002535 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002536 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002537 }
David Sodman4a36e932017-11-07 14:29:47 -08002538 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002539 }
David Sodman4a36e932017-11-07 14:29:47 -08002540 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002541
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002542 // Cleanup any outstanding resources due to rendering a prior frame.
2543 getRenderEngine().cleanupPostRender();
2544
Dan Stoza436ccf32018-06-21 12:10:12 -07002545 {
2546 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002547 if (mTexturePool.size() < mTexturePoolSize) {
2548 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002549 const size_t offset = mTexturePool.size();
2550 mTexturePool.resize(mTexturePoolSize);
2551 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2552 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002553 } else if (mTexturePool.size() > mTexturePoolSize) {
2554 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2555 const size_t offset = mTexturePoolSize;
2556 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2557 mTexturePool.resize(mTexturePoolSize);
2558 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002559 }
2560 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002561
Dan Stoza45de5ba2019-04-25 14:12:09 -07002562 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2563 // side-effect of getTotalSize(), so we check that again here
2564 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002565 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002566 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2567 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002568}
2569
chaviw79468ab2021-10-27 11:11:24 -05002570FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002571 const ui::Size maxSize = [this] {
2572 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002573
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002574 // The LayerTraceGenerator tool runs without displays.
2575 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002576
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002577 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2578 [](ui::Size size, const auto& pair) -> ui::Size {
2579 const auto& display = pair.second;
2580 return {std::max(size.getWidth(), display->getWidth()),
2581 std::max(size.getHeight(), display->getHeight())};
2582 });
2583 }();
chaviwb09c6552021-08-12 17:20:43 -05002584
2585 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2586 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002587 const float xMax = maxSize.getWidth() * 10.f;
2588 const float yMax = maxSize.getHeight() * 10.f;
2589
2590 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002591}
2592
2593void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002594 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002595 for (const auto& layer : mDrawingState.layersSortedByZ) {
2596 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002597 }
2598}
2599
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002600void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002601 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002602 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002603 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002604 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2605 logFrameStats();
2606 }
2607 }
2608}
2609
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002610void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002611 ATRACE_CALL();
2612
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002613 // Keep a copy of the drawing state (that is going to be overwritten
2614 // by commitTransactionsLocked) outside of mStateLock so that the side
2615 // effects of the State assignment don't happen with mStateLock held,
2616 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002617 State drawingState(mDrawingState);
2618
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002619 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002620 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621
Mathias Agopianca4d3602011-05-19 15:38:14 -07002622 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002623 // so we can call commitTransactionsLocked unconditionally.
2624 // We clear the flags with mStateLock held to guarantee that
2625 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002626 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002627 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002628
Mathias Agopianca4d3602011-05-19 15:38:14 -07002629 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002630}
2631
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002632std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2633 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002634 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2635 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002636
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002637 int attempt = 0;
2638 constexpr int kMaxAttempts = 3;
2639 do {
2640 hwcModes = getHwComposer().getModes(displayId);
2641 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2642 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2643
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002644 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2645 return mode.hwcId == *activeModeHwcId;
2646 };
2647
2648 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2649 break;
2650 }
2651 } while (++attempt < kMaxAttempts);
2652
2653 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002654 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002655 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002656 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002657
2658 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002659 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2660 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002661 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002662
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002663 ui::DisplayModeId nextModeId = 1 +
2664 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2665 [](ui::DisplayModeId max, const auto& pair) {
2666 return std::max(max, pair.first.value());
2667 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002668
2669 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002670 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002671 const DisplayModeId id{nextModeId++};
2672 newModes.try_emplace(id,
2673 DisplayMode::Builder(hwcMode.hwcId)
2674 .setId(id)
2675 .setPhysicalDisplayId(displayId)
2676 .setResolution({hwcMode.width, hwcMode.height})
2677 .setVsyncPeriod(hwcMode.vsyncPeriod)
2678 .setDpiX(hwcMode.dpiX)
2679 .setDpiY(hwcMode.dpiY)
2680 .setGroup(hwcMode.configGroup)
2681 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002682 }
2683
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002684 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002685 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002686 [](const auto& lhs, const auto& rhs) {
2687 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002688 });
2689
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002690 // Keep IDs if modes have not changed.
2691 const auto& modes = sameModes ? oldModes : newModes;
2692 const DisplayModePtr activeMode =
2693 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2694 return pair.second->getHwcId() == activeModeHwcId;
2695 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002696
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002697 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002698}
2699
Lloyd Piqueba04e622017-12-14 17:11:26 -08002700void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2701 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002702 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002703 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002704
Dominik Laskowski075d3172018-05-24 15:50:06 -07002705 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002706 continue;
2707 }
2708
Marin Shalamanova524a092020-07-27 21:39:55 +02002709 const auto displayId = info->id;
Dominik Laskowskieb627312022-04-07 09:13:16 -07002710 const auto token = mPhysicalDisplayTokens.get(displayId);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002711
Peiyong Line9d809e2020-04-14 13:10:48 -07002712 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002713 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002714
Dominik Laskowskieb627312022-04-07 09:13:16 -07002715 if (!token) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002716 ALOGV("Creating display %s", to_string(displayId).c_str());
2717
Dominik Laskowski075d3172018-05-24 15:50:06 -07002718 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002719 state.physical = {.id = displayId,
2720 .type = getHwComposer().getDisplayConnectionType(displayId),
2721 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002722 .deviceProductInfo = std::move(info->deviceProductInfo),
2723 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002724 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002725 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002726 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002727
2728 sp<IBinder> token = new BBinder();
2729 mCurrentState.displays.add(token, state);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002730 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002731 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002732 } else {
2733 ALOGV("Recreating display %s", to_string(displayId).c_str());
2734
Dominik Laskowskieb627312022-04-07 09:13:16 -07002735 auto& state = mCurrentState.displays.editValueFor(token->get());
2736 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
Marin Shalamanova903d032020-12-29 20:35:13 +01002737 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002738 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002739 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2740 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2741 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002742 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002743 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002744 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002745
Dominik Laskowskieb627312022-04-07 09:13:16 -07002746 if (const ssize_t index = mCurrentState.displays.indexOfKey(token->get()); index >= 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002747 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2748 mInterceptor->saveDisplayDeletion(state.sequenceId);
2749 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002750 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002751
2752 mPhysicalDisplayTokens.erase(displayId);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002753 }
2754
2755 processDisplayChangesLocked();
2756 }
2757
2758 mPendingHotplugEvents.clear();
2759}
2760
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002761void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002762 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2763 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002764 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2765 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002766}
2767
Lloyd Pique99d3da52018-01-22 17:48:03 -08002768sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002769 const wp<IBinder>& displayToken,
2770 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002771 const DisplayDeviceState& state,
2772 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002773 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002774 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002775 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002776 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002777 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002778 creationArgs.hasWideColorGamut = false;
2779 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002780
Dominik Laskowski55c85402020-01-21 16:25:47 -08002781 if (const auto& physical = state.physical) {
2782 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002783 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002784 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002785 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2786 getKernelIdleTimerProperties(compositionDisplay->getId());
2787
Ady Abraham3efa3942021-06-24 19:01:25 -07002788 scheduler::RefreshRateConfigs::Config config =
2789 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2790 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002791 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002792 .idleTimerTimeout = idleTimerTimeoutMs,
2793 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002794 creationArgs.refreshRateConfigs =
2795 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2796 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002797 }
2798
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002799 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002800 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002801
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002802 if (useColorManagement) {
2803 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2804 for (ColorMode colorMode : modes) {
2805 if (isWideColorMode(colorMode)) {
2806 creationArgs.hasWideColorGamut = true;
2807 }
2808
2809 std::vector<RenderIntent> renderIntents =
2810 getHwComposer().getRenderIntents(*id, colorMode);
2811 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002812 }
2813 }
tangrobin6753a022018-08-10 10:58:54 +08002814 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002815
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002816 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2817 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2818 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002819 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002820
Lloyd Pique90c115d2018-09-18 21:39:42 -07002821 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002822 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002823 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002824
Lloyd Pique99d3da52018-01-22 17:48:03 -08002825 // Make sure that composition can never be stalled by a virtual display
2826 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002827 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002828 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002829 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2830 }
2831
Dominik Laskowski718f9602019-11-09 20:01:35 -08002832 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002833 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2834 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002835
Lloyd Pique99d3da52018-01-22 17:48:03 -08002836 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002837 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002838
Lloyd Pique9370a482019-10-03 17:58:30 -07002839 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002840
Ady Abraham8565ad22021-06-22 17:45:44 -07002841 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002842
2843 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002844 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002845 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002846 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002847 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002848 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002849 display->getCompositionDisplay()->setColorProfile(
2850 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2851 RenderIntent::COLORIMETRIC,
2852 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002853 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002854 FTL_FAKE_GUARD(kMainThreadContext,
2855 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002856 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002857 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002858
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002859 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002860 display->setProjection(state.orientation, state.layerStackSpaceRect,
2861 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002862 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002863 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002864
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002865 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002866}
2867
Marin Shalamanovae685592020-02-12 17:12:22 +01002868void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2869 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002870 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002871 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2872 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002873 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002874 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2875 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002876 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002877 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002878 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002879 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002880 int format;
2881 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002882 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002883 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002884 } else {
2885 // Virtual displays without a surface are dormant:
2886 // they have external state (layer stack, projection,
2887 // etc.) but no internal state (i.e. a DisplayDevice).
2888 return;
2889 }
2890
2891 compositionengine::DisplayCreationArgsBuilder builder;
2892 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002893 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002894 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002895 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002896 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002897
Marin Shalamanov045b7002021-01-07 16:56:24 +01002898 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002899 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002900 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002901 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002902 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002903 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002904
2905 sp<compositionengine::DisplaySurface> displaySurface;
2906 sp<IGraphicBufferProducer> producer;
2907 sp<IGraphicBufferProducer> bqProducer;
2908 sp<IGraphicBufferConsumer> bqConsumer;
2909 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2910
Marin Shalamanovae685592020-02-12 17:12:22 +01002911 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002912 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2913 LOG_FATAL_IF(!displayId);
2914 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2915 bqProducer, bqConsumer, state.displayName);
2916 displaySurface = surface;
2917 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002918 } else {
2919 ALOGE_IF(state.surface != nullptr,
2920 "adding a supported display, but rendering "
2921 "surface is provided (%p), ignoring it",
2922 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002923 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2924 LOG_FATAL_IF(!displayId);
2925 displaySurface =
2926 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002927 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002928 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002929 producer = bqProducer;
2930 }
2931
Marin Shalamanov700e6392020-02-12 20:22:26 +01002932 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002933 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2934 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002935 if (display->isPrimary()) {
2936 initScheduler(display);
2937 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002938 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002939 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002940 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002941
2942 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01002943}
2944
2945void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002946 auto display = getDisplayDeviceLocked(displayToken);
2947 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002948 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002949
2950 if (display->isVirtual()) {
2951 releaseVirtualDisplay(display->getVirtualId());
2952 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002953 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01002954 }
2955 }
2956
2957 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08002958
2959 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002960 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002961 // Destroy the display without holding the mStateLock.
2962 // This is a temporary solution until we can manage transaction queues without
2963 // holding the mStateLock.
2964 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
2965 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
2966 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
2967 // ends up running on the main thread causing a deadlock since setTransactionstate
2968 // will try to acquire the mStateLock. Instead we extend the lifetime of
2969 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
2970 // The display will be disconnected and removed from the mDisplays list so it will
2971 // not be accessible.
2972 }));
2973 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002974}
2975
2976void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2977 const DisplayDeviceState& currentState,
2978 const DisplayDeviceState& drawingState) {
2979 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2980 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002981
2982 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01002983 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02002984 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002985
Marin Shalamanovae685592020-02-12 17:12:22 +01002986 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2987 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002988 if (display->isVirtual()) {
2989 releaseVirtualDisplay(display->getVirtualId());
2990 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002991 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002992
Marin Shalamanovae685592020-02-12 17:12:22 +01002993 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002994
Marin Shalamanov700e6392020-02-12 20:22:26 +01002995 if (const auto& physical = currentState.physical) {
2996 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2997 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002998
Marin Shalamanovae685592020-02-12 17:12:22 +01002999 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003000
Marin Shalamanov700e6392020-02-12 20:22:26 +01003001 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003002 const auto display = getDisplayDeviceLocked(displayToken);
3003 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003004
3005 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003006 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003007 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003008 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003009 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003010 return;
3011 }
3012
3013 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3014 if (currentState.layerStack != drawingState.layerStack) {
3015 display->setLayerStack(currentState.layerStack);
3016 }
Evan Rosky2239b372021-05-20 13:43:47 -07003017 if (currentState.flags != drawingState.flags) {
3018 display->setFlags(currentState.flags);
3019 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003020 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003021 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3022 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3023 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3024 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003025 if (isDisplayActiveLocked(display)) {
3026 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003027 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003028 }
3029 if (currentState.width != drawingState.width ||
3030 currentState.height != drawingState.height) {
3031 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003032
Ady Abrahamed3290f2021-05-17 15:12:14 -07003033 if (isDisplayActiveLocked(display)) {
3034 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003035 }
3036 }
3037 }
3038}
Ady Abraham3efa3942021-06-24 19:01:25 -07003039void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003040 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003041 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003042 updatePhaseConfiguration(refreshRate);
3043 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003044}
Marin Shalamanovae685592020-02-12 17:12:22 +01003045
Lloyd Pique347200f2017-12-14 17:00:15 -08003046void SurfaceFlinger::processDisplayChangesLocked() {
3047 // here we take advantage of Vector's copy-on-write semantics to
3048 // improve performance by skipping the transaction entirely when
3049 // know that the lists are identical
3050 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3051 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3052 if (!curr.isIdenticalTo(draw)) {
3053 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003054 mUpdateInputInfo = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003055
3056 // find the displays that were removed
3057 // (ie: in drawing state but not in current state)
3058 // also handle displays that changed
3059 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003060 for (size_t i = 0; i < draw.size(); i++) {
3061 const wp<IBinder>& displayToken = draw.keyAt(i);
3062 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003063 if (j < 0) {
3064 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003065 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003066 } else {
3067 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003068 const DisplayDeviceState& currentState = curr[j];
3069 const DisplayDeviceState& drawingState = draw[i];
3070 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003071 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003072 }
3073
3074 // find displays that were added
3075 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003076 for (size_t i = 0; i < curr.size(); i++) {
3077 const wp<IBinder>& displayToken = curr.keyAt(i);
3078 if (draw.indexOfKey(displayToken) < 0) {
3079 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003080 }
3081 }
3082 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003083
3084 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003085}
3086
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003087void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3088 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003089 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3090 if (displayTransactionNeeded) {
3091 processDisplayChangesLocked();
3092 processDisplayHotplugEventsLocked();
3093 }
Robert Carrb552ff52021-06-11 13:35:54 -07003094 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003095
Robert Carre450fb52021-06-11 13:21:09 -07003096 if (mSomeChildrenChanged) {
3097 mVisibleRegionsDirty = true;
3098 mSomeChildrenChanged = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003099 mUpdateInputInfo = true;
Robert Carre450fb52021-06-11 13:21:09 -07003100 }
3101
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003102 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003103 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003104 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003105 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003106 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003107 // the hint is set before we acquire a buffer from the surface texture.
3108 //
3109 // NOTE: layer transactions have taken place already, so we use their
3110 // drawing state. However, SurfaceFlinger's own transaction has not
3111 // happened yet, so we must use the current state layer list
3112 // (soon to become the drawing state list).
3113 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003114 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003115 ui::LayerStack layerStack;
3116
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003117 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003118 // NOTE: we rely on the fact that layers are sorted by
3119 // layerStack first (so we don't have to traverse the list
3120 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003121 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3122 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003123 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003124
3125 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003126 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003127 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3128 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003129 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003130
3131 // Pick the primary display if another display mirrors the layer.
3132 if (hintDisplay) {
3133 hintDisplay = nullptr;
3134 break;
3135 }
3136
3137 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003138 }
3139 }
Chet Haase91d25932013-04-11 15:24:55 -07003140
Vishnu Naire3066de2022-06-08 12:16:25 -07003141 if (!hintDisplay && mDisplays.size() > 0) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003142 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3143 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003144
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003145 // could be null when this layer is using a layerStack
3146 // that is not visible on any display. Also can occur at
3147 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003148 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003149 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003150
Vishnu Naire3066de2022-06-08 12:16:25 -07003151 if (hintDisplay) {
3152 layer->updateTransformHint(hintDisplay->getTransformHint());
3153 } else {
3154 ALOGW("Ignoring transform hint update for %s", layer->getDebugName());
3155 }
Robert Carr2047fae2016-11-28 14:09:09 -08003156 });
Mathias Agopian84300952012-11-21 16:02:13 -08003157 }
3158
Robert Carr1f0a16a2016-10-24 16:27:39 -07003159 if (mLayersAdded) {
3160 mLayersAdded = false;
3161 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003162 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003163 mUpdateInputInfo = true;
Mathias Agopian3559b072012-08-15 13:46:03 -07003164 }
3165
3166 // some layers might have been removed, so
3167 // we need to update the regions they're exposing.
3168 if (mLayersRemoved) {
3169 mLayersRemoved = false;
3170 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003171 mUpdateInputInfo = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003172 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003173 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003174 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003175 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003176 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003177 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003178 }
Robert Carr2047fae2016-11-28 14:09:09 -08003179 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180 }
3181
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003182 doCommitTransactions();
3183 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3184 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003185}
3186
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003187void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003188 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003189 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003190 return;
3191 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003192
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003193 std::vector<WindowInfo> windowInfos;
3194 std::vector<DisplayInfo> displayInfos;
3195 bool updateWindowInfo = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003196 if (mUpdateInputInfo) {
3197 mUpdateInputInfo = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003198 updateWindowInfo = true;
3199 buildWindowInfos(windowInfos, displayInfos);
Arthur Hung9ed43392022-05-27 06:31:57 +00003200 } else if (mInputWindowCommands.empty()) {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003201 return;
3202 }
Arthur Hung9ed43392022-05-27 06:31:57 +00003203
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003204 BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
3205 windowInfos = std::move(windowInfos),
3206 displayInfos = std::move(displayInfos),
3207 inputWindowCommands =
3208 std::move(mInputWindowCommands),
3209 inputFlinger = mInputFlinger, this]() {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003210 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3211 if (updateWindowInfo) {
Patrick Williams641f7f22022-06-22 19:25:35 +00003212 mWindowInfosListenerInvoker
3213 ->windowInfosChanged(windowInfos, displayInfos,
3214 inputWindowCommands.windowInfosReportedListeners);
3215 } else {
3216 // If there are listeners but no changes to input windows, call the listeners
3217 // immediately.
3218 for (const auto& listener : inputWindowCommands.windowInfosReportedListeners) {
3219 if (IInterface::asBinder(listener)->isBinderAlive()) {
3220 listener->onWindowInfosReported();
3221 }
3222 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003223 }
3224 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3225 inputFlinger->setFocusedWindow(focusRequest);
3226 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003227 }});
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003228
Arthur Hung6cbb9752019-09-05 16:38:18 +08003229 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003230}
3231
Alec Mouricdf16792021-12-10 13:16:06 -08003232void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3233 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3234 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3235 if (!supportsDisplayBrightnessCommand) {
3236 return;
3237 }
3238
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003239 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003240 if (const auto brightness = display->getStagedBrightness(); brightness) {
3241 if (!needsComposite) {
3242 const status_t error =
3243 getHwComposer()
3244 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003245 display->getCompositionDisplay()
3246 ->getState()
3247 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003248 Hwc2::Composer::DisplayBrightnessOptions{
3249 .applyImmediately = true})
3250 .get();
3251
3252 ALOGE_IF(error != NO_ERROR,
3253 "Error setting display brightness for display %s: %d (%s)",
3254 display->getDebugName().c_str(), error, strerror(error));
3255 }
3256 display->persistBrightness(needsComposite);
3257 }
3258 }
3259}
3260
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003261void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3262 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003263 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3264
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003265 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003266 const auto layerStack = display->getLayerStack();
3267 const auto info = display->getInputInfo();
3268
3269 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003270 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003271 continue;
3272 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003273
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003274 // If the layer stack is mirrored on multiple displays, the first display that is configured
3275 // to receive input takes precedence.
3276 auto& otherInfo = it->second;
3277 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003278 ALOGW_IF(display->receivesInput(),
3279 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003280 layerStack.id);
3281 } else {
3282 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003283 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003284 }
Robert Carr720e5062018-07-30 17:45:14 -07003285
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003286 static size_t sNumWindowInfos = 0;
3287 outWindowInfos.reserve(sNumWindowInfos);
3288 sNumWindowInfos = 0;
3289
Robert Carr720e5062018-07-30 17:45:14 -07003290 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003291 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003292
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003293 // Do not create WindowInfos for windows on displays that cannot receive input.
3294 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3295 const auto& info = opt->get();
3296 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003297 }
Robert Carr720e5062018-07-30 17:45:14 -07003298 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003299
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003300 sNumWindowInfos = outWindowInfos.size();
3301
3302 outDisplayInfos.reserve(displayInputInfos.size());
3303 for (const auto& [_, info] : displayInputInfos) {
3304 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003305 }
Robert Carr720e5062018-07-30 17:45:14 -07003306}
3307
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003308void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003309 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003310 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003311 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003312 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003313 }
3314 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003315
3316 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003317}
3318
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003319void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003320 // If this is called from the main thread mStateLock must be locked before
3321 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003322 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003323
3324 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003325
3326 const auto display = getDefaultDisplayDeviceLocked();
3327 if (!display || mBootStage != BootStage::FINISHED) {
3328 return;
3329 }
3330 ATRACE_CALL();
3331
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003332 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3333 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003334 return;
3335 }
3336
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003337 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003338}
3339
Ady Abraham62a0be22020-12-08 16:54:10 -08003340void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3341 PhysicalDisplayId displayId = [&]() {
3342 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3343 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3344 }();
3345
3346 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3347}
3348
Ady Abraham3efa3942021-06-24 19:01:25 -07003349void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003350 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003351 // If the scheduler is already initialized, this means that we received
3352 // a hotplug(connected) on the primary display. In that case we should
3353 // update the scheduler with the most recent display information.
3354 ALOGW("Scheduler already initialized, updating instead");
3355 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003356 return;
3357 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003358 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003359 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3360 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003361
Marin Shalamanova903d032020-12-29 20:35:13 +01003362 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003363 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003364
Dominik Laskowski068173d2021-08-11 17:22:59 -07003365 using Feature = scheduler::Feature;
3366 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003367
Dominik Laskowski068173d2021-08-11 17:22:59 -07003368 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3369 features |= Feature::kContentDetection;
3370 }
3371 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3372 features |= Feature::kTracePredictedVsync;
3373 }
3374 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003375 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003376 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003377 }
3378
Dominik Laskowski068173d2021-08-11 17:22:59 -07003379 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3380 static_cast<ISchedulerCallback&>(*this),
3381 features);
3382 {
3383 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003384 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003385 features |= Feature::kKernelIdleTimer;
3386 }
3387
3388 mScheduler->createVsyncSchedule(features);
3389 mScheduler->setRefreshRateConfigs(std::move(configs));
3390 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003391 setVsyncEnabled(false);
3392 mScheduler->startTimers();
3393
Ady Abraham9c53ee72020-07-22 21:16:18 -07003394 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003395 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003396 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003397 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003398 /*workDuration=*/configs.late.appWorkDuration,
3399 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003400 impl::EventThread::InterceptVSyncsCallback());
3401 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003402 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3403 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3404 /*readyDuration=*/configs.late.sfWorkDuration,
3405 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003406 mInterceptor->saveVSyncEvent(timestamp);
3407 });
3408
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003409 mScheduler->initVsync(mScheduler->getVsyncSchedule().getDispatch(),
3410 *mFrameTimeline->getTokenManager(), configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003411
3412 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003413 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003414 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003415 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003416 // initialization, so that the EventThreads always contain a reference to a
3417 // prior configuration.
3418 //
3419 // This is a bit hacky, but this avoids a back-pointer into the main SF
3420 // classes from EventThread, and there should be no run-time binder cost
3421 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003422 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003423}
3424
Marin Shalamanov5801c942020-12-17 17:00:13 +01003425void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3426 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003427 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003428 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003429}
3430
Ady Abraham55fa7272020-09-30 19:19:27 -07003431void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3432 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003433 mScheduler->setDuration(mAppConnectionHandle,
3434 /*workDuration=*/config.appWorkDuration,
3435 /*readyDuration=*/config.sfWorkDuration);
3436 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003437 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3438 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003439 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003440}
3441
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003442void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003443 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003444
Lloyd Pique58e24a32019-08-01 15:50:14 -07003445 if (!mLayersPendingRemoval.isEmpty()) {
3446 // Notify removed layers now that they can't be drawn from
3447 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003448 // Ensure any buffers set to display on any children are released.
3449 if (l->isRemovedFromCurrentState()) {
3450 l->latchAndReleaseBuffer();
3451 }
3452
chaviw6852bff2022-04-19 17:35:11 -05003453 // If a layer has a parent, we allow it to out-live it's handle
3454 // with the idea that the parent holds a reference and will eventually
3455 // be cleaned up. However no one cleans up the top-level so we do so
3456 // here.
3457 if (l->isAtRoot()) {
3458 l->setIsAtRoot(false);
3459 mCurrentState.layersSortedByZ.remove(l);
3460 }
3461
Lloyd Pique58e24a32019-08-01 15:50:14 -07003462 // If the layer has been removed and has no parent, then it will not be reachable
3463 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3464 // ensure we can copy its current to drawing state.
3465 if (!l->getParent()) {
3466 mOffscreenLayers.emplace(l.get());
3467 }
3468 }
3469 mLayersPendingRemoval.clear();
3470 }
3471
3472 // If this transaction is part of a window animation then the next frame
3473 // we composite should be considered an animation as well.
3474 mAnimCompositionPending = mAnimTransactionPending;
3475
3476 mDrawingState = mCurrentState;
3477 // clear the "changed" flags in current state
3478 mCurrentState.colorMatrixChanged = false;
3479
Robert Carra70e91c2021-06-11 13:59:52 -07003480 if (mVisibleRegionsDirty) {
3481 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3482 rootLayer->commitChildList();
3483 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003484 }
Robert Carra70e91c2021-06-11 13:59:52 -07003485
Lloyd Pique58e24a32019-08-01 15:50:14 -07003486 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003487 if (mNumClones > 0) {
3488 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3489 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003490}
3491
chaviw74d90ad2019-04-26 14:45:26 -07003492void SurfaceFlinger::commitOffscreenLayers() {
3493 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003494 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003495 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3496 layer->doTransaction(0);
3497 layer->commitChildList();
3498 }
chaviw74d90ad2019-04-26 14:45:26 -07003499 });
3500 }
3501}
3502
Chia-I Wuab0c3192017-08-01 11:29:00 -07003503void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003504 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003505 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003506 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003507 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003508 }
3509 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003510}
3511
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003512bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003513 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003514
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003515 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516
Mathias Agopian4fec8732012-06-29 14:12:52 -07003517 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003518 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003519 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003520
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003521 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3522
Eric Penner51c59cd2014-07-28 19:51:58 -07003523 // Store the set of layers that need updates. This set must not change as
3524 // buffers are being latched, as this could result in a deadlock.
3525 // Example: Two producers share the same command stream and:
3526 // 1.) Layer 0 is latched
3527 // 2.) Layer 0 gets a new frame
3528 // 2.) Layer 1 gets a new frame
3529 // 3.) Layer 1 is latched.
3530 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3531 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003532 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003533 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3534 const uint32_t flags = layer->doTransaction(0);
3535 if (flags & Layer::eVisibleRegion) {
3536 mVisibleRegionsDirty = true;
3537 }
3538 }
Robert Carrb552ff52021-06-11 13:35:54 -07003539
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003540 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003541 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003542 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003543 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003544 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003545 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003546 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003547 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003548 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003549 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003550 }
Robert Carr2047fae2016-11-28 14:09:09 -08003551 });
Robert Carrb552ff52021-06-11 13:35:54 -07003552 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003553
chaviw49a108c2019-08-12 11:23:06 -07003554 // The client can continue submitting buffers for offscreen layers, but they will not
3555 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3556 // layers to ensure dequeueBuffer doesn't block indefinitely.
3557 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003558 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003559 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3560 }
3561
Lloyd Piquef2c79392018-12-20 16:23:33 -08003562 if (!mLayersWithQueuedFrames.empty()) {
3563 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3564 // writes to Layer current state. See also b/119481871
3565 Mutex::Autolock lock(mStateLock);
3566
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003567 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003568 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003569 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003570 newDataLatched = true;
3571 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003572 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003573 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003574 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003575
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003576 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003577
3578 // If we will need to wake up at some time in the future to deal with a
3579 // queued frame that shouldn't be displayed during this vsync period, wake
3580 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003581 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003582 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003583 }
3584
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003585 // enter boot animation on first buffer latch
3586 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3587 ALOGI("Enter boot animation");
3588 mBootStage = BootStage::BOOTANIMATION;
3589 }
3590
Robert Carr6a0382d2021-07-01 15:57:17 -07003591 if (mNumClones > 0) {
3592 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3593 }
chaviw74b03172019-08-19 11:09:03 -07003594
Dan Stoza6b9454d2014-11-07 16:00:59 -08003595 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003596 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003597}
3598
Robert Carrc0df3122019-04-11 13:18:21 -07003599status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003600 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003601 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003602 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003603 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003604 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003605 static_cast<void>(mScheduler->schedule([=] {
3606 ALOGE("Dumping random sampling of on-screen layers: ");
3607 mDrawingState.traverse([&](Layer *layer) {
3608 // Aim to dump about 200 layers to avoid totally trashing
3609 // logcat. On the other hand, if there really are 4096 layers
3610 // something has gone totally wrong its probably the most
3611 // useful information in logcat.
3612 if (rand() % 20 == 13) {
3613 ALOGE("Layer: %s", layer->getName().c_str());
3614 }
3615 });
3616 for (Layer* offscreenLayer : mOffscreenLayers) {
3617 if (rand() % 20 == 13) {
3618 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3619 }
3620 }
3621 }));
arthurhungdba591c2021-02-08 17:28:49 +08003622 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003623 }
3624
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003625 {
3626 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3627 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3628 }
arthurhungdba591c2021-02-08 17:28:49 +08003629
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003630 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003631 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003632 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003633 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003634 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003635 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003636 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003637 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003638
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003639 setTransactionFlags(eTransactionNeeded);
3640 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003641}
3642
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003643uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003644 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003645}
3646
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003647uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3648 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003649}
3650
Dominik Laskowski94000c42022-03-17 12:55:14 -07003651void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003652 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003653 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003654
3655 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003656 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003658}
3659
Ady Abraham9dada822022-02-03 10:26:59 -08003660bool SurfaceFlinger::stopTransactionProcessing(
3661 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3662 applyTokensWithUnsignaledTransactions) const {
3663 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3664 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3665 // then we should have only one applyToken for processing.
3666 // so we can stop further transactions on this applyToken.
3667 return !applyTokensWithUnsignaledTransactions.empty();
3668 }
3669
3670 return false;
3671}
3672
ramindani9eff2492022-03-23 00:28:26 +00003673int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3674 std::vector<TransactionState>& transactions,
3675 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3676 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3677 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3678 applyTokensWithUnsignaledTransactions,
3679 /*tryApplyUnsignaled*/ true);
3680}
3681
Robert Carr79dc06a2022-02-22 15:28:59 -08003682int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003683 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003684 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003685 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3686 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003687 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003688 auto it = mPendingTransactionQueues.begin();
3689 while (it != mPendingTransactionQueues.end()) {
3690 auto& [applyToken, transactionQueue] = *it;
3691 while (!transactionQueue.empty()) {
3692 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3693 ATRACE_NAME("stopTransactionProcessing");
3694 break;
3695 }
3696
3697 auto& transaction = transactionQueue.front();
3698 const auto ready =
Robert Carr4c1b6462021-12-21 10:30:50 -08003699 transactionIsReadyToBeApplied(transaction,
3700 transaction.frameTimelineInfo,
3701 transaction.isAutoTimestamp,
3702 transaction.desiredPresentTime,
3703 transaction.originUid, transaction.states,
3704 bufferLayersReadyToPresent, transactions.size(),
3705 tryApplyUnsignaled);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003706 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3707 if (ready == TransactionReadiness::NotReady) {
3708 setTransactionFlags(eTransactionFlushNeeded);
3709 break;
3710 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003711 if (ready == TransactionReadiness::NotReadyBarrier) {
3712 transactionsPendingBarrier++;
3713 setTransactionFlags(eTransactionFlushNeeded);
3714 break;
3715 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003716 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003717 const bool frameNumberChanged = state.bufferData->flags.test(
3718 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003719 if (frameNumberChanged) {
3720 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3721 } else {
3722 // Barrier function only used for BBQ which always includes a frame number
3723 bufferLayersReadyToPresent[state.surface] =
3724 std::numeric_limits<uint64_t>::max();
3725 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003726 });
3727 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3728 if (appliedUnsignaled) {
3729 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3730 }
3731
3732 transactions.emplace_back(std::move(transaction));
3733 transactionQueue.pop();
3734 }
3735
3736 if (transactionQueue.empty()) {
3737 it = mPendingTransactionQueues.erase(it);
3738 mTransactionQueueCV.broadcast();
3739 } else {
3740 it = std::next(it, 1);
3741 }
3742 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003743 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003744}
3745
Vishnu Nair7891e962021-11-11 12:07:21 -08003746bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003747 // to prevent onHandleDestroyed from being called while the lock is held,
3748 // we must keep a copy of the transactions (specifically the composer
3749 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003750 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003751 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003752 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003753 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003754 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003755 Mutex::Autolock _l(mStateLock);
3756 {
3757 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003758
Robert Carr79dc06a2022-02-22 15:28:59 -08003759 int lastTransactionsPendingBarrier = 0;
3760 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003761 // First collect transactions from the pending transaction queues.
3762 // We are not allowing unsignaled buffers here as we want to
3763 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003764 transactionsPendingBarrier =
3765 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3766 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003767
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003768 // Second, collect transactions from the transaction queue.
3769 // Here as well we are not allowing unsignaled buffers for the same
3770 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003771 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003772 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003773 const bool pendingTransactions =
3774 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003775 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003776 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003777 if (pendingTransactions) {
3778 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003779 return TransactionReadiness::NotReady;
3780 }
3781
Robert Carr4c1b6462021-12-21 10:30:50 -08003782 return transactionIsReadyToBeApplied(transaction, transaction.frameTimelineInfo,
Ady Abraham9dada822022-02-03 10:26:59 -08003783 transaction.isAutoTimestamp,
3784 transaction.desiredPresentTime,
3785 transaction.originUid, transaction.states,
3786 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003787 transactions.size(),
3788 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003789 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003790 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003791 if (ready != TransactionReadiness::Ready) {
3792 if (ready == TransactionReadiness::NotReadyBarrier) {
3793 transactionsPendingBarrier++;
3794 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003795 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003796 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003797 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003798 const bool frameNumberChanged = state.bufferData->flags.test(
3799 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003800 if (frameNumberChanged) {
3801 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3802 } else {
3803 // Barrier function only used for BBQ which always includes a frame number.
3804 // This value only used for barrier logic.
3805 bufferLayersReadyToPresent[state.surface] =
3806 std::numeric_limits<uint64_t>::max();
3807 }
Xiang Wang76236e12022-03-22 17:25:30 +00003808 });
Ady Abraham9dada822022-02-03 10:26:59 -08003809 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003810 }
ramindani4d48f902021-09-20 21:07:45 +00003811 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003812 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003813 }
Arthur Hung58144272021-01-16 03:43:53 +00003814
Robert Carr79dc06a2022-02-22 15:28:59 -08003815 // Transactions with a buffer pending on a barrier may be on a different applyToken
3816 // than the transaction which satisfies our barrier. In fact this is the exact use case
3817 // that the primitive is designed for. This means we may first process
3818 // the barrier dependent transaction, determine it ineligible to complete
3819 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3820 // The barrier dependent transaction was eligible to be presented in this frame
3821 // but we would have prevented it without case. To fix this we continually
3822 // loop through flushPendingTransactionQueues until we perform an iteration
3823 // where the number of transactionsPendingBarrier doesn't change. This way
3824 // we can continue to resolve dependency chains of barriers as far as possible.
3825 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3826 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3827 transactionsPendingBarrier =
3828 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3829 applyTokensWithUnsignaledTransactions,
3830 /*tryApplyUnsignaled*/ false);
3831 }
3832
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003833 // We collected all transactions that could apply without latching unsignaled buffers.
3834 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3835 // transactions that were not applied and try to apply them unsignaled.
3836 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003837 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3838 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003839 }
3840
Vishnu Nair7891e962021-11-11 12:07:21 -08003841 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003842 }
ramindani4d48f902021-09-20 21:07:45 +00003843 }
3844}
3845
Vishnu Nair7891e962021-11-11 12:07:21 -08003846bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3847 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003848 bool needsTraversal = false;
3849 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003850 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003851 needsTraversal |=
3852 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3853 transaction.displays, transaction.flags,
3854 transaction.inputWindowCommands,
3855 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3856 transaction.buffer, transaction.postTime,
3857 transaction.permissions, transaction.hasListenerCallbacks,
3858 transaction.listenerCallbacks, transaction.originPid,
3859 transaction.originUid, transaction.id);
3860 if (transaction.transactionCommittedSignal) {
3861 mTransactionCommittedSignals.emplace_back(
3862 std::move(transaction.transactionCommittedSignal));
3863 }
3864 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003865
Dominik Laskowski46471e62022-01-14 15:34:03 -08003866 if (mTransactionTracing) {
3867 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003868 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003869 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003870}
3871
3872bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003873 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003874 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003875}
3876
Ady Abraham8db10102021-03-15 17:19:23 -07003877bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3878 // The amount of time SF can delay a frame if it is considered early based
3879 // on the VsyncModulator::VsyncConfig::appWorkDuration
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003880 constexpr std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
Ady Abraham8db10102021-03-15 17:19:23 -07003881
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003882 const nsecs_t currentVsyncPeriod = mScheduler->getVsyncSchedule().period().ns();
3883 const nsecs_t earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
Ady Abraham8db10102021-03-15 17:19:23 -07003884
3885 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3886 if (!prediction.has_value()) {
3887 return false;
3888 }
3889
3890 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3891 kEarlyLatchMaxThreshold.count()) {
3892 return false;
3893 }
3894
3895 return prediction->presentTime >= expectedPresentTime &&
3896 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3897}
Ady Abraham9dada822022-02-03 10:26:59 -08003898bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003899 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003900 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3901 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3902 return false;
3903 }
Ady Abraham8db10102021-03-15 17:19:23 -07003904
Ady Abraham9dada822022-02-03 10:26:59 -08003905 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3906 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3907 return true;
3908 }
3909
3910 // We only want to latch unsignaled when a single layer is updated in this
3911 // transaction (i.e. not a blast sync transaction).
3912 if (numStates != 1) {
3913 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3914 return false;
3915 }
3916
Ady Abraham2739e832022-02-14 17:42:00 -08003917 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3918 if (totalTXapplied > 0) {
3919 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3920 __func__, totalTXapplied);
3921 return false;
3922 }
3923
3924 // We don't want to latch unsignaled if are in early / client composition
3925 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3926 // or window animations being slow.
3927 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3928 if (!isDefaultVsyncConfig) {
3929 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3930 __func__);
3931 return false;
3932 }
Ady Abraham9dada822022-02-03 10:26:59 -08003933 }
3934
3935 if (!layer->simpleBufferUpdate(state)) {
3936 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3937 return false;
3938 }
3939
3940 ALOGV("%s: true", __func__);
3941 return true;
3942}
3943
Robert Carr4c1b6462021-12-21 10:30:50 -08003944auto SurfaceFlinger::transactionIsReadyToBeApplied(TransactionState& transaction,
Ady Abraham43752eb2021-03-04 16:24:25 -08003945 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003946 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003947 const std::unordered_map<
3948 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003949 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003950 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003951 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003952 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3953 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003954 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08003955 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003956 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003957 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003958 }
3959
Ady Abraham5690bda2021-03-12 15:01:18 -08003960 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
3961 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003962 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003963 }
3964
Ady Abraham8db10102021-03-15 17:19:23 -07003965 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3966 // present time of this transaction.
3967 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
3968 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08003969 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07003970 }
3971
Ady Abraham9dada822022-02-03 10:26:59 -08003972 bool fenceUnsignaled = false;
Robert Carr4c1b6462021-12-21 10:30:50 -08003973 auto queueProcessTime = systemTime();
Marissa Wall713b63f2018-10-17 15:42:43 -07003974 for (const ComposerState& state : states) {
3975 const layer_state_t& s = state.state;
Robert Carr4c1b6462021-12-21 10:30:50 -08003976
Ady Abrahamf20c1922020-12-21 18:39:01 -08003977 sp<Layer> layer = nullptr;
3978 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07003979 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003980 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08003981 ALOGW("Transaction with buffer, but no Layer?");
3982 continue;
3983 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003984 if (!layer) {
3985 continue;
3986 }
Ady Abraham43752eb2021-03-04 16:24:25 -08003987
Robert Carr79dc06a2022-02-22 15:28:59 -08003988 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
3989 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
3990 const bool willApplyBarrierFrame =
3991 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
3992 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
3993 if (!willApplyBarrierFrame) {
3994 ATRACE_NAME("NotReadyBarrier");
3995 return TransactionReadiness::NotReadyBarrier;
3996 }
3997 }
3998
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003999 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08004000 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08004001 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
4002 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08004003
4004 const bool acquireFenceChanged = s.bufferData &&
4005 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
4006 s.bufferData->acquireFence;
4007 fenceUnsignaled = fenceUnsignaled ||
4008 (acquireFenceChanged &&
4009 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
4010
4011 if (fenceUnsignaled && !allowLatchUnsignaled) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004012 if (!transaction.sentFenceTimeoutWarning &&
4013 queueProcessTime - transaction.queueTime > std::chrono::nanoseconds(4s).count()) {
4014 transaction.sentFenceTimeoutWarning = true;
4015 auto listener = s.bufferData->releaseBufferListener;
4016 if (listener) {
4017 listener->onTransactionQueueStalled();
4018 }
4019 }
4020
Ady Abraham9dada822022-02-03 10:26:59 -08004021 ATRACE_NAME("fence unsignaled");
4022 return TransactionReadiness::NotReady;
4023 }
4024
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004025 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08004026 // If backpressure is enabled and we already have a buffer to commit, keep the
4027 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004028 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4029 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004030 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004031 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004032 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004033 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004034 }
4035 }
Ady Abraham9dada822022-02-03 10:26:59 -08004036 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004037}
4038
arthurhungf1b7c7b2021-03-03 17:42:23 +08004039void SurfaceFlinger::queueTransaction(TransactionState& state) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004040 state.queueTime = systemTime();
4041
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004042 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004043
arthurhungf1b7c7b2021-03-03 17:42:23 +08004044 // Generate a CountDownLatch pending state if this is a synchronous transaction.
Patrick Williams641f7f22022-06-22 19:25:35 +00004045 if (state.flags & eSynchronous) {
4046 state.transactionCommittedSignal =
4047 std::make_shared<CountDownLatch>(CountDownLatch::eSyncTransaction);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004048 }
4049
ramindani4d48f902021-09-20 21:07:45 +00004050 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004051 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4052
Ady Abrahame46243a2021-02-23 19:33:49 -08004053 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004054 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4055 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004056 return TransactionSchedule::Late;
4057 }(state.flags);
4058
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004059 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4060
4061 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004062}
4063
arthurhungf1b7c7b2021-03-03 17:42:23 +08004064void SurfaceFlinger::waitForSynchronousTransaction(
4065 const CountDownLatch& transactionCommittedSignal) {
4066 // applyTransactionState is called on the main SF thread. While a given process may wish
4067 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4068 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004069 if (!transactionCommittedSignal.wait_until(
4070 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004071 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004072 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004073}
Ady Abrahame46243a2021-02-23 19:33:49 -08004074
Arthur Hung2274a312021-04-28 15:13:06 +00004075void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004076 for (auto it = mTransactionCommittedSignals.begin();
4077 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004078 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004079 it = mTransactionCommittedSignals.erase(it);
4080 } else {
4081 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004082 }
4083 }
4084}
4085
chaviw308ddba2020-08-11 16:23:51 -07004086status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004087 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004088 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4089 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004090 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004091 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004092 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004093
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004094 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004095 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4096 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004097 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4098 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004099 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004100 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004101 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004102 }
4103
Leon Scroggins9a20f722021-12-28 14:43:12 +00004104 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004105 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004106 }
4107
Robert Carrde6d7b42022-01-07 18:23:06 -08004108 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004109 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4110 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4111 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004112 }
4113
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004114 const int64_t postTime = systemTime();
4115
4116 IPCThreadState* ipc = IPCThreadState::self();
4117 const int originPid = ipc->getCallingPid();
4118 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004119 TransactionState state{frameTimelineInfo, states,
4120 displays, flags,
4121 applyToken, inputWindowCommands,
4122 desiredPresentTime, isAutoTimestamp,
4123 uncacheBuffer, postTime,
4124 permissions, hasListenerCallbacks,
4125 listenerCallbacks, originPid,
4126 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004127
4128 // Check for incoming buffer updates and increment the pending buffer count.
4129 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4130 mBufferCountTracker.increment(state.surface->localBinder());
4131 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004132
Dominik Laskowski46471e62022-01-14 15:34:03 -08004133 if (mTransactionTracing) {
4134 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004135 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004136 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004137
arthurhungf1b7c7b2021-03-03 17:42:23 +08004138 // Check the pending state to make sure the transaction is synchronous.
4139 if (state.transactionCommittedSignal) {
4140 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004141 }
4142
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004143 return NO_ERROR;
4144}
Marissa Wall713b63f2018-10-17 15:42:43 -07004145
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004146bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004147 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004148 const Vector<DisplayState>& displays, uint32_t flags,
4149 const InputWindowCommands& inputWindowCommands,
4150 const int64_t desiredPresentTime, bool isAutoTimestamp,
4151 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004152 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004153 bool hasListenerCallbacks,
4154 const std::vector<ListenerCallbacks>& listenerCallbacks,
4155 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004156 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004157 for (const DisplayState& display : displays) {
4158 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004159 }
4160
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004161 // start and end registration for listeners w/ no surface so they can get their callback. Note
4162 // that listeners with SurfaceControls will start registration during setClientStateLocked
4163 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004164 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004165 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004166 }
4167
Marissa Walle2ffb422018-10-12 11:33:52 -07004168 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004169 for (int i = 0; i < states.size(); i++) {
4170 ComposerState& state = states.editItemAt(i);
4171 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004172 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004173 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004174 if (const auto layer = fromHandle(state.state.surface).promote()) {
4175 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004176 mScheduler->recordLayerHistory(layer.get(),
4177 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004178 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004179 }
4180 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004181 }
4182
Marissa Walle2ffb422018-10-12 11:33:52 -07004183 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004184
Robert Carrde6d7b42022-01-07 18:23:06 -08004185 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004186 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4187 } else if (!inputWindowCommands.empty()) {
4188 ALOGE("Only privileged callers are allowed to send input commands.");
4189 }
chaviw273171b2018-12-26 11:46:30 -08004190
Marissa Wall947d34e2019-03-29 14:03:53 -07004191 if (uncacheBuffer.isValid()) {
4192 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004193 }
4194
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004195 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4196 // anyway. This can be used as a flush mechanism for previous async transactions.
4197 // Empty animation transaction can be used to simulate back-pressure, so also force a
4198 // transaction for empty animation transactions.
4199 if (transactionFlags == 0 &&
4200 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004201 transactionFlags = eTransactionNeeded;
4202 }
4203
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004204 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004205 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004206 if (mInterceptor->isEnabled()) {
4207 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004208 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004209 }
4210
Arthur Hung58144272021-01-16 03:43:53 +00004211 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4212 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4213 if (transactionFlags & eTraversalNeeded) {
4214 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004215 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004216 }
Arthur Hung58144272021-01-16 03:43:53 +00004217 if (transactionFlags) {
4218 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004219 }
4220
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004221 if (flags & eAnimation) {
4222 mAnimTransactionPending = true;
4223 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004224 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004225
4226 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004227}
4228
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004229uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4230 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4231 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004232
Mathias Agopiane57f2922012-08-09 16:29:12 -07004233 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004234 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4235
4236 const uint32_t what = s.what;
4237 if (what & DisplayState::eSurfaceChanged) {
4238 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4239 state.surface = s.surface;
4240 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004241 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004242 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004243 if (what & DisplayState::eLayerStackChanged) {
4244 if (state.layerStack != s.layerStack) {
4245 state.layerStack = s.layerStack;
4246 flags |= eDisplayTransactionNeeded;
4247 }
4248 }
Evan Rosky2239b372021-05-20 13:43:47 -07004249 if (what & DisplayState::eFlagsChanged) {
4250 if (state.flags != s.flags) {
4251 state.flags = s.flags;
4252 flags |= eDisplayTransactionNeeded;
4253 }
4254 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004255 if (what & DisplayState::eDisplayProjectionChanged) {
4256 if (state.orientation != s.orientation) {
4257 state.orientation = s.orientation;
4258 flags |= eDisplayTransactionNeeded;
4259 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004260 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4261 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004262 flags |= eDisplayTransactionNeeded;
4263 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004264 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4265 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004266 flags |= eDisplayTransactionNeeded;
4267 }
4268 }
4269 if (what & DisplayState::eDisplaySizeChanged) {
4270 if (state.width != s.width) {
4271 state.width = s.width;
4272 flags |= eDisplayTransactionNeeded;
4273 }
4274 if (state.height != s.height) {
4275 state.height = s.height;
4276 flags |= eDisplayTransactionNeeded;
4277 }
4278 }
4279
Mathias Agopiane57f2922012-08-09 16:29:12 -07004280 return flags;
4281}
4282
Steven Thomasd4071902020-03-24 16:02:53 -07004283bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004284 IPCThreadState* ipc = IPCThreadState::self();
4285 const int pid = ipc->getCallingPid();
4286 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004287 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004288 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4289 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004290 return false;
4291 }
4292 return true;
4293}
4294
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004295uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004296 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004297 int64_t desiredPresentTime, bool isAutoTimestamp,
4298 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004299 layer_state_t& s = composerState.state;
4300 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004301
4302 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004303 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004304 // Starts a registration but separates the callback ids according to callback type. This
4305 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004306 // note that startRegistration will not re-register if the listener has
4307 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004308
4309 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4310 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004311 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004312 }
4313
4314 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4315 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004316 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004317 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004318 }
4319
arthurhungdba591c2021-02-08 17:28:49 +08004320 const uint64_t what = s.what;
4321 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004322 sp<Layer> layer = nullptr;
4323 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004324 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004325 } else {
4326 // The client may provide us a null handle. Treat it as if the layer was removed.
4327 ALOGW("Attempt to set client state with a null layer handle");
4328 }
chaviw8b3871a2017-11-01 17:41:01 -07004329 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004330 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004331 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004332 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004333 }
chaviw8b3871a2017-11-01 17:41:01 -07004334 return 0;
4335 }
4336
Valerie Hau871d6352020-01-29 08:44:02 -08004337 // Only set by BLAST adapter layers
4338 if (what & layer_state_t::eProducerDisconnect) {
4339 layer->onDisconnect();
4340 }
4341
chaviw8b3871a2017-11-01 17:41:01 -07004342 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004343 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004344 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004345 }
chaviw8b3871a2017-11-01 17:41:01 -07004346 }
4347 if (what & layer_state_t::eLayerChanged) {
4348 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004349 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004350 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004351 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004352 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004353 mCurrentState.layersSortedByZ.removeAt(idx);
4354 mCurrentState.layersSortedByZ.add(layer);
4355 // we need traversal (state changed)
4356 // AND transaction (list changed)
4357 flags |= eTransactionNeeded|eTraversalNeeded;
4358 }
chaviw8b3871a2017-11-01 17:41:01 -07004359 } else {
4360 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004361 flags |= eTransactionNeeded|eTraversalNeeded;
4362 }
4363 }
chaviw8b3871a2017-11-01 17:41:01 -07004364 }
4365 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004366 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004367 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004368 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4369 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004370 if (p == nullptr) {
4371 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004372 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004373 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004374 mCurrentState.layersSortedByZ.removeAt(idx);
4375 mCurrentState.layersSortedByZ.add(layer);
4376 // we need traversal (state changed)
4377 // AND transaction (list changed)
4378 flags |= eTransactionNeeded|eTraversalNeeded;
4379 }
4380 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004381 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004382 flags |= eTransactionNeeded|eTraversalNeeded;
4383 }
chaviw8b3871a2017-11-01 17:41:01 -07004384 }
4385 }
4386 if (what & layer_state_t::eSizeChanged) {
4387 if (layer->setSize(s.w, s.h)) {
4388 flags |= eTraversalNeeded;
4389 }
4390 }
4391 if (what & layer_state_t::eAlphaChanged) {
4392 if (layer->setAlpha(s.alpha))
4393 flags |= eTraversalNeeded;
4394 }
4395 if (what & layer_state_t::eColorChanged) {
4396 if (layer->setColor(s.color))
4397 flags |= eTraversalNeeded;
4398 }
Peiyong Lind3788632018-09-18 16:01:31 -07004399 if (what & layer_state_t::eColorTransformChanged) {
4400 if (layer->setColorTransform(s.colorTransform)) {
4401 flags |= eTraversalNeeded;
4402 }
4403 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004404 if (what & layer_state_t::eBackgroundColorChanged) {
4405 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4406 flags |= eTraversalNeeded;
4407 }
4408 }
chaviw8b3871a2017-11-01 17:41:01 -07004409 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004410 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004411 }
4412 if (what & layer_state_t::eTransparentRegionChanged) {
4413 if (layer->setTransparentRegionHint(s.transparentRegion))
4414 flags |= eTraversalNeeded;
4415 }
4416 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004417 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004418 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004419 if (what & layer_state_t::eCornerRadiusChanged) {
4420 if (layer->setCornerRadius(s.cornerRadius))
4421 flags |= eTraversalNeeded;
4422 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004423 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004424 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4425 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004426 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004427 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4428 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004429 if (what & layer_state_t::eRenderBorderChanged) {
Tianhao Yao10cea3c2022-03-30 01:37:22 +00004430 if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00004431 flags |= eTraversalNeeded;
4432 }
4433 }
chaviw8b3871a2017-11-01 17:41:01 -07004434 if (what & layer_state_t::eLayerStackChanged) {
4435 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4436 // We only allow setting layer stacks for top level layers,
4437 // everything else inherits layer stack from its parent.
4438 if (layer->hasParent()) {
4439 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004440 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004441 } else if (idx < 0) {
4442 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004443 "that also does not appear in the top level layer list. Something"
4444 " has gone wrong.",
4445 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004446 } else if (layer->setLayerStack(s.layerStack)) {
4447 mCurrentState.layersSortedByZ.removeAt(idx);
4448 mCurrentState.layersSortedByZ.add(layer);
4449 // we need traversal (state changed)
4450 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004451 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004452 }
4453 }
Marissa Wall61c58622018-07-18 10:12:20 -07004454 if (what & layer_state_t::eTransformChanged) {
4455 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4456 }
4457 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4458 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4459 flags |= eTraversalNeeded;
4460 }
4461 if (what & layer_state_t::eCropChanged) {
4462 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4463 }
Marissa Wall61c58622018-07-18 10:12:20 -07004464 if (what & layer_state_t::eDataspaceChanged) {
4465 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4466 }
4467 if (what & layer_state_t::eHdrMetadataChanged) {
4468 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4469 }
4470 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4471 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4472 }
4473 if (what & layer_state_t::eApiChanged) {
4474 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4475 }
4476 if (what & layer_state_t::eSidebandStreamChanged) {
4477 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4478 }
Robert Carr720e5062018-07-30 17:45:14 -07004479 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004480 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4481 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004482 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004483 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004484 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004485 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004486
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004487 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4488 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004489 // The transaction will be received on the Task layer and needs to be applied to all
4490 // child layers. Child layers that are added at a later point will obtain the game mode
4491 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004492 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004493 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004494
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004495 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4496 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004497 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4498 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4499 flags |= eTraversalNeeded;
4500 }
4501 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004502 if (what & layer_state_t::eShadowRadiusChanged) {
4503 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4504 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004505 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004506 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004507 flags |= eTraversalNeeded;
4508 }
4509 }
Steven Thomas3172e202020-01-06 19:25:30 -08004510 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004511 const auto compatibility =
4512 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4513 const auto strategy =
4514 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004515
Robert Carrde6d7b42022-01-07 18:23:06 -08004516 if (layer->setFrameRate(
4517 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4518 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004519 }
Steven Thomas3172e202020-01-06 19:25:30 -08004520 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004521 if (what & layer_state_t::eFixedTransformHintChanged) {
4522 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4523 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4524 }
4525 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004526 if (what & layer_state_t::eAutoRefreshChanged) {
4527 layer->setAutoRefresh(s.autoRefresh);
4528 }
Sally Qi421ffb02022-03-21 19:41:33 -07004529 if (what & layer_state_t::eDimmingEnabledChanged) {
4530 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4531 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004532 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004533 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4534 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004535 }
4536 }
John Reckcdb4ed72021-02-04 13:39:33 -05004537 if (what & layer_state_t::eStretchChanged) {
4538 if (layer->setStretchEffect(s.stretchEffect)) {
4539 flags |= eTraversalNeeded;
4540 }
4541 }
chaviwf3f40fe2021-04-27 15:54:02 -05004542 if (what & layer_state_t::eBufferCropChanged) {
4543 if (layer->setBufferCrop(s.bufferCrop)) {
4544 flags |= eTraversalNeeded;
4545 }
4546 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004547 if (what & layer_state_t::eDestinationFrameChanged) {
4548 if (layer->setDestinationFrame(s.destinationFrame)) {
4549 flags |= eTraversalNeeded;
4550 }
4551 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004552 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004553 if (layer->setDropInputMode(s.dropInputMode)) {
4554 flags |= eTraversalNeeded;
Arthur Hung9ed43392022-05-27 06:31:57 +00004555 mUpdateInputInfo = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004556 }
4557 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004558 // This has to happen after we reparent children because when we reparent to null we remove
4559 // child layers from current state and remove its relative z. If the children are reparented in
4560 // the same transaction, then we have to make sure we reparent the children first so we do not
4561 // lose its relative z order.
4562 if (what & layer_state_t::eReparent) {
4563 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004564 auto parentHandle = (s.parentSurfaceControlForChild)
4565 ? s.parentSurfaceControlForChild->getHandle()
4566 : nullptr;
4567 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004568 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004569 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004570 mCurrentState.layersSortedByZ.remove(layer);
4571 }
4572 flags |= eTransactionNeeded | eTraversalNeeded;
4573 }
4574 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004575 std::vector<sp<CallbackHandle>> callbackHandles;
4576 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4577 for (auto& [listener, callbackIds] : filteredListeners) {
4578 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4579 }
4580 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004581
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004582 if (what & layer_state_t::eBufferChanged) {
4583 std::shared_ptr<renderengine::ExternalTexture> buffer =
4584 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4585 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4586 dequeueBufferTimestamp, frameTimelineInfo)) {
4587 flags |= eTraversalNeeded;
4588 }
Ady Abraham8db10102021-03-15 17:19:23 -07004589 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4590 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004591 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004592
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004593 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004594 // Do not put anything that updates layer state or modifies flags after
4595 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004596 return flags;
4597}
4598
chaviw273171b2018-12-26 11:46:30 -08004599uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004600 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004601 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004602}
4603
Vishnu Nair84125ac2021-12-02 08:47:48 -08004604status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4605 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4606 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004607 if (!mirrorFromHandle) {
4608 return NAME_NOT_FOUND;
4609 }
4610
4611 sp<Layer> mirrorLayer;
4612 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004613 {
4614 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004615 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004616 if (!mirrorFrom) {
4617 return NAME_NOT_FOUND;
4618 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004619 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004620 if (result != NO_ERROR) {
4621 return result;
4622 }
4623
Robert Carr6a0382d2021-07-01 15:57:17 -07004624 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004625 }
4626
Ady Abraham9f0a4002020-10-05 15:47:26 -07004627 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004628 if (mTransactionTracing) {
4629 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4630 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004631 }
4632 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004633 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004634}
4635
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004636status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004637 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4638 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004639 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4640 "Expected only one of parentLayer or parentHandle to be non-null. "
4641 "Programmer error?");
4642
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004643 status_t result = NO_ERROR;
4644
4645 sp<Layer> layer;
4646
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004647 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004648 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004649 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004650 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004651 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4652 if (pendingBufferCounter) {
4653 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004654 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004655 pendingBufferCounter);
4656 }
4657 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004658 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004659 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004660 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004661 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004662 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004663 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004664 default:
4665 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004666 break;
4667 }
4668
Dan Stoza7d89d062015-04-30 13:29:25 -07004669 if (result != NO_ERROR) {
4670 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004671 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004672
Vishnu Nair858a3b42022-01-12 20:42:28 -08004673 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004674 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4675 if (parentHandle != nullptr && parent == nullptr) {
4676 ALOGE("Invalid parent handle %p.", parentHandle.get());
4677 addToRoot = false;
4678 }
4679 if (parentLayer != nullptr) {
4680 addToRoot = false;
4681 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004682
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004683 int parentId = -1;
4684 // We can safely promote the layer in binder thread because we have a strong reference
4685 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4686 sp<Layer> parentSp = parent.promote();
4687 if (parentSp != nullptr) {
4688 parentId = parentSp->getSequence();
4689 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004690 if (mTransactionTracing) {
4691 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4692 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004693 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004694
Vishnu Nair047fb332021-12-09 09:54:36 -08004695 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4696 if (result != NO_ERROR) {
4697 return result;
4698 }
4699
Ady Abraham9f0a4002020-10-05 15:47:26 -07004700 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004701 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004702}
4703
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004704status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004705 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004706 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004707 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004708 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004709 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004710}
4711
Vishnu Nair84125ac2021-12-02 08:47:48 -08004712status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004713 sp<Layer>* outLayer) {
4714 *outLayer = getFactory().createEffectLayer(args);
4715 *handle = (*outLayer)->getHandle();
4716 return NO_ERROR;
4717}
4718
Vishnu Nair84125ac2021-12-02 08:47:48 -08004719status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004720 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004721 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004722 *handle = (*outLayer)->getHandle();
4723 return NO_ERROR;
4724}
4725
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004726void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004727 mLayersPendingRemoval.add(layer);
4728 mLayersRemoved = true;
4729 setTransactionFlags(eTransactionNeeded);
4730}
4731
Vishnu Nairf9096652021-07-20 18:49:42 -07004732void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004733 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004734 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004735 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004736 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004737 if (mTransactionTracing) {
4738 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004739 }
Rob Carr4bba3702018-10-08 21:53:30 +00004740}
4741
Mathias Agopianb60314a2012-04-10 22:09:54 -07004742// ---------------------------------------------------------------------------
4743
Andy McFadden13a082e2012-08-24 10:16:42 -07004744void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004745 const auto display = getDefaultDisplayDeviceLocked();
4746 if (!display) return;
4747
4748 const sp<IBinder> token = display->getDisplayToken().promote();
4749 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004750
Jesse Hall01e29052013-02-19 16:13:35 -08004751 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004752 Vector<ComposerState> state;
4753 Vector<DisplayState> displays;
4754 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004755 d.what = DisplayState::eDisplayProjectionChanged |
4756 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004757 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004758 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004759 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004760 d.orientedDisplaySpaceRect.makeInvalid();
4761 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004762 d.width = 0;
4763 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004764 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004765
Vishnu Nair9a69a042021-06-18 13:19:49 -07004766 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004767
4768 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004769 // It should be on the main thread, apply it directly.
4770 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004771 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004772 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004773
Peiyong Lin65248e02020-04-18 21:15:07 -07004774 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004775 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004776 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004777 mActiveDisplayTransformHint = display->getTransformHint();
Andy McFadden13a082e2012-08-24 10:16:42 -07004778}
4779
4780void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004781 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004782 static_cast<void>(
4783 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004784}
4785
Peiyong Lin65248e02020-04-18 21:15:07 -07004786void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004787 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004788 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004789 return;
4790 }
4791
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004792 const auto displayId = display->getPhysicalId();
4793 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004794
Peiyong Lin65248e02020-04-18 21:15:07 -07004795 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004796 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004797 return;
4798 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004799
Ady Abraham4f960d12021-10-13 16:59:49 -07004800 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4801 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4802 activeDisplay->isPoweredOn()) {
4803 ALOGW("Trying to change power mode on non active display while the active display is ON");
4804 }
4805
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004806 display->setPowerMode(mode);
4807
Lloyd Pique4dccc412018-01-22 17:21:36 -08004808 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004809 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004810 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004811 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004812 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004813 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004814 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004815 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004816 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004817 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4818 // We can merge the syscall later.
4819 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4820 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4821 }
Martin Liu4a322352020-03-24 21:30:38 +08004822 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4823 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4824 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004825 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004826 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004827 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004828 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004829 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004830 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004831
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004832 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004833 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004834 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004835 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004836 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004837 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4838 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004839 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004840 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4841 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4842 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004843 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004844 mScheduler->disableHardwareVsync(true);
4845 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004846 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004847
Ady Abraham27c70212019-06-11 10:52:26 -07004848 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004849 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004850
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004851 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004852 mVisibleRegionsDirty = true;
4853 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004854 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004855 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004856 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004857 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Yifei Zhangf0bd62e2021-06-16 15:27:05 -07004858 ALOGI("Force repainting for DOZE_SUSPEND -> DOZE or ON.");
4859 mVisibleRegionsDirty = true;
4860 scheduleRepaint();
Ana Krulecc2870422019-01-29 19:00:58 -08004861 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004862 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004863 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004864 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004865 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004866 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004867 mScheduler->disableHardwareVsync(true);
4868 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004869 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004870 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004871 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004872 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004873 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004874 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004875
Ady Abrahamadc914c2021-10-13 17:04:27 -07004876 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004877 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004878 mRefreshRateStats->setPowerMode(mode);
Rachel Lee6a9731d2022-06-06 17:08:14 -07004879 mScheduler->setDisplayPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004880 }
4881
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004882 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004883}
4884
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004885void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004886 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004887 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004888 if (!display) {
4889 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4890 displayToken.get());
4891 } else if (display->isVirtual()) {
4892 ALOGW("Attempt to set power mode %d for virtual display", mode);
4893 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004894 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004895 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004896 });
4897
4898 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004899}
4900
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004901status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004902 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004903
Mathias Agopianbd115332013-04-18 16:41:04 -07004904 IPCThreadState* ipc = IPCThreadState::self();
4905 const int pid = ipc->getCallingPid();
4906 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004907
Mathias Agopianbd115332013-04-18 16:41:04 -07004908 if ((uid != AID_SHELL) &&
4909 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004910 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4911 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004912 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004913 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004914 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004915 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004916 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004917 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004918 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004919 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4920 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4921 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004922 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004923 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4924 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004925 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004926 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004927 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004928 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004929
Dominik Laskowskic2867142019-01-21 11:33:38 -08004930 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004931
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004932 bool dumpLayers = true;
4933 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004934 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004935 if (!lock.locked()) {
4936 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4937 strerror(-lock.status), lock.status);
4938 }
4939
4940 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4941 (it->second)(args, asProto, result);
4942 dumpLayers = false;
4943 } else if (!asProto) {
4944 dumpAllLocked(args, result);
4945 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004946 }
4947
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004948 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004949 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05004950 LayersTraceProto* layersTrace = traceFileProto.add_entry();
4951 LayersProto layersProto = dumpProtoFromMainThread();
4952 layersTrace->mutable_layers()->Swap(&layersProto);
4953 dumpDisplayProto(*layersTrace);
4954
Dominik Laskowski46470112019-08-02 13:13:11 -07004955 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05004956 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07004957 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004958 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05004959 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07004960 result.append(LayerProtoParser::layerTreeToString(layerTree));
4961 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004962 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004963 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004964 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004965 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004966 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004967 return NO_ERROR;
4968}
4969
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004970status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08004971 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004972 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004973 if (mTransactionTracing) {
4974 mTransactionTracing->writeToFile();
4975 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004976 }
4977
4978 return doDump(fd, DumpArgs(), asProto);
4979}
4980
Dominik Laskowskic2867142019-01-21 11:33:38 -08004981void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004982 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004983 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004984}
4985
Dominik Laskowskic2867142019-01-21 11:33:38 -08004986void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07004987 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004988
Dominik Laskowskic2867142019-01-21 11:33:38 -08004989 if (args.size() > 1) {
4990 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004991 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004992 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004993 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004994 }
Robert Carr2047fae2016-11-28 14:09:09 -08004995 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004996 } else {
4997 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004998 }
4999}
5000
Dominik Laskowskic2867142019-01-21 11:33:38 -08005001void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005002 const bool clearAll = args.size() < 2;
5003 const auto name = clearAll ? String8() : String8(args[1]);
5004
Edgar Arriaga844fa672020-01-16 14:21:42 -08005005 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005006 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005007 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005008 }
Robert Carr2047fae2016-11-28 14:09:09 -08005009 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005010
Svetoslavd85084b2014-03-20 10:28:31 -07005011 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005012}
5013
Dominik Laskowskic2867142019-01-21 11:33:38 -08005014void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5015 mTimeStats->parseArgs(asProto, args, result);
5016}
5017
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005018void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5019 mFrameTimeline->parseArgs(args, result);
5020}
5021
Jamie Gennis6547ff42013-07-16 20:12:42 -07005022void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005023 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005024 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005025 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005026
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005027 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005028}
5029
Yiwei Zhang5434a782018-12-05 18:06:32 -08005030void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005031 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005032
Yiwei Zhang5434a782018-12-05 18:06:32 -08005033 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5034 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005035 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5036 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005037 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5038 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5039 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005040 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005041}
5042
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005043void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005044 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005045
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005046 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005047 result.append("\n");
5048
Ady Abraham8287e852020-08-12 14:44:58 -07005049 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005050 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005051 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005052 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005053
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005054 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5055 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005056
Ana Krulecc2870422019-01-29 19:00:58 -08005057 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005058 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005059 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5060 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005061}
5062
Dan Stoza269dc4d2021-01-15 15:07:43 -08005063void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5064 for (const auto& [token, display] : mDisplays) {
5065 const auto compositionDisplay = display->getCompositionDisplay();
5066 compositionDisplay->dumpPlannerInfo(args, result);
5067 }
5068}
5069
Yiwei Zhang5434a782018-12-05 18:06:32 -08005070void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5071 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005072 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5073 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005074 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005075 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005076 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005077 }
David Sodman4a36e932017-11-07 14:29:47 -08005078 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005079 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005080 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005081 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5082 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005083}
5084
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005085void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5086 for (const auto& [token, display] : mDisplays) {
5087 display->getCompositionDisplay()->dump(result);
5088 result += '\n';
5089 }
5090}
5091
5092void SurfaceFlinger::dumpDisplays(std::string& result) const {
5093 for (const auto& [token, display] : mDisplays) {
5094 display->dump(result);
5095 result += '\n';
5096 }
5097}
5098
Yiwei Zhang5434a782018-12-05 18:06:32 -08005099void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005100 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005101 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005102 if (!displayId) {
5103 continue;
5104 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005105 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005106 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005107 continue;
5108 }
5109
Yiwei Zhang5434a782018-12-05 18:06:32 -08005110 StringAppendF(&result,
5111 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5112 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005113 uint8_t port;
5114 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005115 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005116 result.append("no identification data\n");
5117 continue;
5118 }
5119
5120 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005121 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005122 continue;
5123 }
5124
5125 const auto edid = parseEdid(data);
5126 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005127 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005128 continue;
5129 }
5130
Yiwei Zhang5434a782018-12-05 18:06:32 -08005131 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005132 result.append(edid->displayName.data(), edid->displayName.length());
5133 result.append("\"\n");
5134 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005135}
5136
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005137void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5138 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005139 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005140 uint8_t port;
5141 DisplayIdentificationData data;
5142
5143 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5144 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5145 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5146 }
5147}
5148
Yiwei Zhang5434a782018-12-05 18:06:32 -08005149void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005150 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005151 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5152 StringAppendF(&result, "DisplayColorSetting: %s\n",
5153 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005154
5155 // TODO: print out if wide-color mode is active or not
5156
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005157 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005158 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005159 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005160 continue;
5161 }
5162
Yiwei Zhang5434a782018-12-05 18:06:32 -08005163 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005164 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005165 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005166 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005167 }
5168
Lloyd Pique32cbe282018-10-19 13:09:22 -07005169 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005170 StringAppendF(&result, " Current color mode: %s (%d)\n",
5171 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005172 }
5173 result.append("\n");
5174}
5175
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005176LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005177 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005178 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005179 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005180 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005181
chaviw1d044282017-09-27 12:19:28 -07005182 return layersProto;
5183}
5184
chaviw0a398992021-08-13 10:13:01 -05005185void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005186 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005187 DisplayProto* displayProto = layersTraceProto.add_displays();
5188 displayProto->set_id(display->getId().value);
5189 displayProto->set_name(display->getDisplayName());
5190 displayProto->set_layer_stack(display->getLayerStack().id);
5191 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5192 [&]() { return displayProto->mutable_size(); });
5193 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5194 return displayProto->mutable_layer_stack_space_rect();
5195 });
5196 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5197 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005198 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005199 }
5200}
5201
Alec Mouri6b9e9912020-01-21 10:50:24 -08005202void SurfaceFlinger::dumpHwc(std::string& result) const {
5203 getHwComposer().dump(result);
5204}
5205
Vishnu Nair0f085c62019-08-30 08:49:12 -07005206void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5207 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5208 // it.
5209 LayerProto* rootProto = layersProto.add_layers();
5210 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5211 rootProto->set_id(offscreenRootLayerId);
5212 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005213 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005214
5215 for (Layer* offscreenLayer : mOffscreenLayers) {
5216 // Add layer as child of the fake root
5217 rootProto->add_children(offscreenLayer->sequence);
5218
5219 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005220 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005221 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005222 }
5223}
5224
Vishnu Nair8406fd72019-07-30 11:29:31 -07005225LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005226 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005227}
5228
Vishnu Nair0f085c62019-08-30 08:49:12 -07005229void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005230 auto future = mScheduler->schedule([this] {
5231 std::string result;
5232 for (Layer* offscreenLayer : mOffscreenLayers) {
5233 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5234 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5235 }
5236 return result;
5237 });
5238
Vishnu Nair0f085c62019-08-30 08:49:12 -07005239 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005240 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005241}
5242
Dominik Laskowskic2867142019-01-21 11:33:38 -08005243void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5244 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005245 Colorizer colorizer(colorize);
5246
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005247 // figure out if we're stuck somewhere
5248 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005249 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005250 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5251
5252 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005253 * Dump library configuration.
5254 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005255
5256 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005257 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005258 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005259 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005260 result.append("\n");
5261
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005262 result.append("\nDisplay identification data:\n");
5263 dumpDisplayIdentificationData(result);
5264
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005265 result.append("\nWide-Color information:\n");
5266 dumpWideColorInfo(result);
5267
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005268 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005269 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005270 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005271 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005272 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005273
Andy McFadden41d67d72014-04-25 16:58:34 -07005274 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005275 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005276 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005277 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005278 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005279
Dan Stozab90cf072015-03-05 11:05:59 -08005280 dumpStaticScreenStats(result);
5281 result.append("\n");
5282
Alec Mouri40189b02019-03-05 15:07:54 -08005283 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5284 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5285 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005286
Andy McFadden4803b742012-09-24 19:07:20 -07005287 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005288 * Dump the visible layer list
5289 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005290 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005291 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005292 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005293
Chia-I Wu2f884132018-09-13 15:17:58 -07005294 {
Lloyd Pique207def92019-02-28 16:09:52 -08005295 StringAppendF(&result, "Composition layers\n");
5296 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005297 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005298 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005299
5300 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5301 layer->getDebugName() ? layer->getDebugName()
5302 : "<unknown>");
5303 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005304 });
5305 }
5306
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005307 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005308 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005309 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005310 dumpDisplays(result);
5311 dumpCompositionDisplays(result);
5312 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005313
5314 mCompositionEngine->dump(result);
5315
5316 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005317 * Dump SurfaceFlinger global state
5318 */
5319
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005320 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005321 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005322 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005323
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005324 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005325
Robert Carrbeba6f02021-02-10 21:06:27 -08005326 result.append("ClientCache state:\n");
5327 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005328 DebugEGLImageTracker::getInstance()->dump(result);
5329
Dominik Laskowski075d3172018-05-24 15:50:06 -07005330 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005331 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5332 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005333 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5334 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005335 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005336 StringAppendF(&result,
5337 " transaction-flags : %08x\n"
5338 " gpu_to_cpu_unsupported : %d\n",
5339 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005340
Marin Shalamanov045b7002021-01-07 16:56:24 +01005341 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005342 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005343 if (const auto activeMode = display->getActiveMode()) {
5344 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005345
5346 const auto dpi = activeMode->getDpi();
5347 xDpi = base::StringPrintf("%.2f", dpi.x);
5348 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005349 } else {
5350 fps = "unknown";
5351 xDpi = "unknown";
5352 yDpi = "unknown";
5353 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005354 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005355 " refresh-rate : %s\n"
5356 " x-dpi : %s\n"
5357 " y-dpi : %s\n",
5358 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005359 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005360
Yiwei Zhang5434a782018-12-05 18:06:32 -08005361 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005362
Dan Stozae22aec72016-08-01 13:20:59 -07005363 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005364 * Tracing state
5365 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005366 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005367
5368 result.append("\nTransaction tracing: ");
5369 if (mTransactionTracing) {
5370 result.append("enabled\n");
5371 mTransactionTracing->dump(result);
5372 } else {
5373 result.append("disabled\n");
5374 }
5375 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005376
5377 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005378 * HWC layer minidump
5379 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005380 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005381 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005382 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005383 continue;
5384 }
5385
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005386 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5387 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005388 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005389
5390 const DisplayDevice& ref = *display;
5391 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005392 result.append("\n");
5393 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005394
Ady Abraham2790e9f2021-04-28 13:14:20 -07005395 {
5396 DumpArgs plannerArgs;
5397 plannerArgs.add(); // first argument is ignored
5398 plannerArgs.add(String16("--layers"));
5399 dumpPlannerInfo(plannerArgs, result);
5400 }
5401
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005402 /*
5403 * Dump HWComposer state
5404 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005405 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005406 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005407 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005408 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005409 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005410 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005411
5412 /*
5413 * Dump gralloc state
5414 */
5415 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5416 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005417
rnleea2ecd832021-07-29 13:58:30 -07005418 /*
5419 * Dump flag/property manager state
5420 */
Robert Carr9b623c32022-03-21 15:55:22 -07005421 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005422
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005423 result.append(mTimeStats->miniDump());
5424 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005425}
5426
chaviw17ac24b2021-01-28 18:50:05 -08005427mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5428 if (saturation == 1) {
5429 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005430 }
5431
chaviw17ac24b2021-01-28 18:50:05 -08005432 float3 luminance{0.213f, 0.715f, 0.072f};
5433 luminance *= 1.0f - saturation;
5434 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5435 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5436 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5437 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5438 return saturationMatrix;
5439}
5440
5441void SurfaceFlinger::updateColorMatrixLocked() {
5442 mat4 colorMatrix =
5443 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5444
Chia-I Wu28f320b2018-05-03 11:02:56 -07005445 if (mCurrentState.colorMatrix != colorMatrix) {
5446 mCurrentState.colorMatrix = colorMatrix;
5447 mCurrentState.colorMatrixChanged = true;
5448 setTransactionFlags(eTransactionNeeded);
5449 }
5450}
5451
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005452status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005453#pragma clang diagnostic push
5454#pragma clang diagnostic error "-Wswitch-enum"
5455 switch (static_cast<ISurfaceComposerTag>(code)) {
5456 // These methods should at minimum make sure that the client requested
5457 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005458 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005459 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005460 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005461 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005462 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5463 // permission dynamically. Don't use the permission cache for this check.
5464 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005465 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005466 IPCThreadState* ipc = IPCThreadState::self();
5467 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5468 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005469 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005470 }
Robert Carr1db73f62016-12-21 12:58:51 -08005471 return OK;
5472 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005473 // The following calls are currently used by clients that do not
5474 // request necessary permissions. However, they do not expose any secret
5475 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005476 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005477 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005478 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005479 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005480 // Calling setTransactionState is safe, because you need to have been
5481 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005482 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005483 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005484 return OK;
5485 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005486 case BOOT_FINISHED:
5487 // Used by apps to hook Choreographer to SurfaceFlinger.
5488 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005489 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005490 case CREATE_DISPLAY:
5491 case DESTROY_DISPLAY:
5492 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5493 case GET_PHYSICAL_DISPLAY_IDS:
5494 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005495 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005496 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005497 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005498 case GET_DISPLAY_STATE:
5499 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005500 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005501 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005502 case GET_DISPLAY_NATIVE_PRIMARIES:
5503 case SET_ACTIVE_COLOR_MODE:
5504 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005505 case CLEAR_BOOT_DISPLAY_MODE:
5506 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5507 case SET_AUTO_LOW_LATENCY_MODE:
5508 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005509 case CAPTURE_LAYERS:
5510 case CAPTURE_DISPLAY:
5511 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005512 case CLEAR_ANIMATION_FRAME_STATS:
5513 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005514 case OVERRIDE_HDR_TYPES:
5515 case ON_PULL_ATOM:
5516 case ENABLE_VSYNC_INJECTIONS:
5517 case INJECT_VSYNC:
5518 case GET_LAYER_DEBUG_INFO:
5519 case GET_COLOR_MANAGEMENT:
5520 case GET_COMPOSITION_PREFERENCE:
5521 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5522 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005523 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005524 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005525 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005526 case ADD_REGION_SAMPLING_LISTENER:
5527 case REMOVE_REGION_SAMPLING_LISTENER:
5528 case ADD_FPS_LISTENER:
5529 case REMOVE_FPS_LISTENER:
5530 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5531 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5532 case ADD_WINDOW_INFOS_LISTENER:
5533 case REMOVE_WINDOW_INFOS_LISTENER:
5534 case SET_DESIRED_DISPLAY_MODE_SPECS:
5535 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005536 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5537 case SET_DISPLAY_BRIGHTNESS:
5538 case ADD_HDR_LAYER_INFO_LISTENER:
5539 case REMOVE_HDR_LAYER_INFO_LISTENER:
5540 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005541 case SET_GLOBAL_SHADOW_SETTINGS:
5542 case GET_DISPLAY_DECORATION_SUPPORT:
5543 case SET_FRAME_RATE:
5544 case SET_OVERRIDE_FRAME_RATE:
5545 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005546 case ADD_TRANSACTION_TRACE_LISTENER:
5547 case GET_GPU_CONTEXT_PRIORITY:
5548 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005549 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005550 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005551 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005552
5553 // These codes are used for the IBinder protocol to either interrogate the recipient
5554 // side of the transaction for its canonical interface descriptor or to dump its state.
5555 // We let them pass by default.
5556 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5557 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5558 code == IBinder::SYSPROPS_TRANSACTION) {
5559 return OK;
5560 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005561 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005562 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005563 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005564 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5565 return OK;
5566 }
5567 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5568 return PERMISSION_DENIED;
5569#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005570}
5571
Ana Krulec13be8ad2018-08-21 02:43:56 +00005572status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5573 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005574 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5575 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005576 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005577
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005578 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5579 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005580 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005581 IPCThreadState* ipc = IPCThreadState::self();
5582 const int uid = ipc->getCallingUid();
5583 if (CC_UNLIKELY(uid != AID_SYSTEM
5584 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005585 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005586 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005587 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005588 return PERMISSION_DENIED;
5589 }
5590 int n;
5591 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005592 case 1000: // Unused.
5593 case 1001:
5594 return NAME_NOT_FOUND;
5595 case 1002: // Toggle flashing on surface damage.
5596 if (const int delay = data.readInt32(); delay > 0) {
5597 mDebugFlashDelay = delay;
5598 } else {
5599 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5600 }
5601 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005602 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005603 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005604 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005605 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005606 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005607 case 1005: { // Force commit ahead of next VSYNC.
5608 Mutex::Autolock lock(mStateLock);
5609 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5610 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005611 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005612 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005613 case 1007: // Unused.
5614 return NAME_NOT_FOUND;
5615 case 1008: // Toggle forced GPU composition.
5616 mDebugDisableHWC = data.readInt32() != 0;
5617 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005618 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005619 case 1009: // Toggle use of transform hint.
5620 mDebugDisableTransformHint = data.readInt32() != 0;
5621 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005622 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005623 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005624 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005625 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005626 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005627 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005628 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005629 return NO_ERROR;
5630 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005631 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005632 if (!display) {
5633 return NAME_NOT_FOUND;
5634 }
5635
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005636 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005637 return NO_ERROR;
5638 }
5639 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005640 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005641 // daltonize
5642 n = data.readInt32();
5643 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005644 case 1:
5645 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5646 break;
5647 case 2:
5648 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5649 break;
5650 case 3:
5651 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5652 break;
5653 default:
5654 mDaltonizer.setType(ColorBlindnessType::None);
5655 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005656 }
5657 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005658 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005659 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005660 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005661 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005662
5663 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005664 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005665 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005666 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005667 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005668 // apply a color matrix
5669 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005670 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005671 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005672 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005673 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005674 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005675 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005676 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005677 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005678 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005679 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005680
5681 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5682 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005683 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005684 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5685 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5686 }
5687
Chia-I Wu28f320b2018-05-03 11:02:56 -07005688 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005689 return NO_ERROR;
5690 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005691 case 1016: { // Unused.
5692 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005693 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005694 case 1017: {
5695 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005696 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005697 return NO_ERROR;
5698 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005699 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005700 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005701 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005702 return NO_ERROR;
5703 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005704 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005705 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005706 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005707 return NO_ERROR;
5708 }
Irvel468051e2016-06-13 16:44:44 -07005709 case 1020: { // Layer updates interceptor
5710 n = data.readInt32();
5711 if (n) {
5712 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005713 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005714 }
5715 else{
5716 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005717 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005718 }
5719 return NO_ERROR;
5720 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005721 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005722 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005723 static_cast<void>(
5724 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005725 return NO_ERROR;
5726 }
Romain Guy0147a172017-06-01 13:53:56 -07005727 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005728 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005729 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005730
Chia-I Wu28f320b2018-05-03 11:02:56 -07005731 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005732 return NO_ERROR;
5733 }
Romain Guy54f154a2017-10-24 21:40:32 +01005734 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005735 int32_t colorMode;
5736
Chia-I Wu0d711262018-05-21 15:19:35 -07005737 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005738 if (data.readInt32(&colorMode) == NO_ERROR) {
5739 mForceColorMode = static_cast<ColorMode>(colorMode);
5740 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005741 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005742 return NO_ERROR;
5743 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005744 // Deprecate, use 1030 to check whether the device is color managed.
5745 case 1024: {
5746 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005747 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005748 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005749 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005750 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005751 if (n == 1) {
5752 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005753 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005754 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005755 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005756 int64_t startingTime =
5757 (fixedStartingTime) ? fixedStartingTime : systemTime();
5758 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005759 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Pablo Gamitob8775792022-06-10 15:02:42 +00005760 mLayerTracing.notify(true /* visibleRegionDirty */,
Pablo Gamito6be82442022-06-13 11:04:34 +00005761 startingTime, mLastCommittedVsyncId);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005762 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005763 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005764 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005765 } else if (n == 2) {
5766 std::string filename = std::string(data.readCString());
5767 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5768 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005769 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005770 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005771 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005772 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005773 mTracingEnabledChanged = tracingEnabledChanged;
5774 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005775 return NO_ERROR;
5776 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005777 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005778 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005779 return NO_ERROR;
5780 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005781 // Is a DisplayColorSetting supported?
5782 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005783 const auto display = getDefaultDisplayDevice();
5784 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005785 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005786 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005787
5788 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5789 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005790 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005791 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005792 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005793 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005794 reply->writeBool(true);
5795 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005796 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005797 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005798 break;
5799 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005800 reply->writeBool(
5801 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005802 break;
5803 }
5804 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005805 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005806 case 1028: { // Unused.
5807 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005808 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005809 // Set buffer size for SF tracing (value in KB)
5810 case 1029: {
5811 n = data.readInt32();
5812 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5813 ALOGW("Invalid buffer size: %d KB", n);
5814 reply->writeInt32(BAD_VALUE);
5815 return BAD_VALUE;
5816 }
5817
5818 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005819 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005820 reply->writeInt32(NO_ERROR);
5821 return NO_ERROR;
5822 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005823 // Is device color managed?
5824 case 1030: {
5825 reply->writeBool(useColorManagement);
5826 return NO_ERROR;
5827 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005828 // Override default composition data space
5829 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5830 // && adb shell stop zygote && adb shell start zygote
5831 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5832 // adb shell stop zygote && adb shell start zygote
5833 case 1031: {
5834 Mutex::Autolock _l(mStateLock);
5835 n = data.readInt32();
5836 if (n) {
5837 n = data.readInt32();
5838 if (n) {
5839 Dataspace dataspace = static_cast<Dataspace>(n);
5840 if (!validateCompositionDataspace(dataspace)) {
5841 return BAD_VALUE;
5842 }
5843 mDefaultCompositionDataspace = dataspace;
5844 }
5845 n = data.readInt32();
5846 if (n) {
5847 Dataspace dataspace = static_cast<Dataspace>(n);
5848 if (!validateCompositionDataspace(dataspace)) {
5849 return BAD_VALUE;
5850 }
5851 mWideColorGamutCompositionDataspace = dataspace;
5852 }
5853 } else {
5854 // restore composition data space.
5855 mDefaultCompositionDataspace = defaultCompositionDataspace;
5856 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5857 }
5858 return NO_ERROR;
5859 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005860 // Set trace flags
5861 case 1033: {
5862 n = data.readUint32();
5863 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005864 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005865 reply->writeInt32(NO_ERROR);
5866 return NO_ERROR;
5867 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005868 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005869 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005870 switch (n = data.readInt32()) {
5871 case 0:
5872 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005873 FTL_FAKE_GUARD(mStateLock,
5874 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005875 break;
5876 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005877 reply->writeBool(
5878 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005879 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005880 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005881 });
5882
5883 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005884 return NO_ERROR;
5885 }
Ady Abraham34392f72019-04-10 11:29:27 -07005886 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005887 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005888
Dominik Laskowskif1833852021-03-23 15:06:50 -07005889 const auto display = [&]() -> sp<IBinder> {
5890 uint64_t value;
5891 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005892 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005893 }
5894
Dominik Laskowskif1833852021-03-23 15:06:50 -07005895 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5896 return getPhysicalDisplayToken(*id);
5897 }
5898
5899 ALOGE("Invalid physical display ID");
5900 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005901 }();
5902
Shiyong Li2bcece92021-08-30 20:38:50 +00005903 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005904 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005905 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5906 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005907 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005908 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5909 // manager frame rate policy a new policy which allows switching between all refresh
5910 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005911 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005912 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005913 return mScheduler
5914 ->schedule([this] {
5915 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005916 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005917
Dominik Laskowski756b7892021-08-04 12:53:59 -07005918 // This is a little racy, but not in a way that hurts anything. As
5919 // we grab the defaultMode from the display manager policy, we could
5920 // be setting a new display manager policy, leaving us using a stale
5921 // defaultMode. The defaultMode doesn't matter for the override
5922 // policy though, since we set allowGroupSwitching to true, so it's
5923 // not a problem.
5924 scheduler::RefreshRateConfigs::Policy overridePolicy;
5925 overridePolicy.defaultMode = display->refreshRateConfigs()
5926 .getDisplayManagerPolicy()
5927 .defaultMode;
5928 overridePolicy.allowGroupSwitching = true;
5929 constexpr bool kOverridePolicy = true;
5930 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5931 kOverridePolicy);
5932 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005933 .get();
5934 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07005935 return mScheduler
5936 ->schedule([this] {
5937 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005938 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07005939 constexpr bool kOverridePolicy = true;
5940 return setDesiredDisplayModeSpecsInternal(display, {},
5941 kOverridePolicy);
5942 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005943 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07005944 }
Ady Abraham07e54702020-04-16 15:05:37 -07005945 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02005946 // Inject a hotplug connected event for the primary display. This will deallocate and
5947 // reallocate the display state including framebuffers.
5948 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07005949 const hal::HWDisplayId hwcId =
5950 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
5951
5952 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02005953 return NO_ERROR;
5954 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07005955 // Modify the max number of display frames stored within FrameTimeline
5956 case 1038: {
5957 n = data.readInt32();
5958 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
5959 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
5960 return BAD_VALUE;
5961 }
5962 if (n == 0) {
5963 // restore to default
5964 mFrameTimeline->reset();
5965 return NO_ERROR;
5966 }
5967 mFrameTimeline->setMaxDisplayFrames(n);
5968 return NO_ERROR;
5969 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07005970 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07005971 PhysicalDisplayId displayId = [&]() {
5972 Mutex::Autolock lock(mStateLock);
5973 return getDefaultDisplayDeviceLocked()->getPhysicalId();
5974 }();
5975
5976 auto inUid = static_cast<uid_t>(data.readInt32());
5977 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08005978 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
5979 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07005980 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08005981 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005982 // Toggle caching feature
5983 // First argument is an int32 - nonzero enables caching and zero disables caching
5984 // Second argument is an optional uint64 - if present, then limits enabling/disabling
5985 // caching to a particular physical display
5986 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005987 auto future = mScheduler->schedule([&] {
5988 n = data.readInt32();
5989 std::optional<PhysicalDisplayId> inputId = std::nullopt;
5990 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
5991 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
5992 if (!inputId || getPhysicalDisplayToken(*inputId)) {
5993 ALOGE("No display with id: %" PRIu64, inputDisplayId);
5994 return NAME_NOT_FOUND;
5995 }
5996 }
5997 {
5998 Mutex::Autolock lock(mStateLock);
5999 mLayerCachingEnabled = n != 0;
6000 for (const auto& [_, display] : mDisplays) {
6001 if (!inputId || *inputId == display->getPhysicalId()) {
6002 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006003 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006004 }
6005 }
6006 return OK;
6007 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006008
Dominik Laskowski756b7892021-08-04 12:53:59 -07006009 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006010 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006011 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006012 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006013 return NO_ERROR;
6014 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006015 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006016 if (mTransactionTracing) {
6017 if (data.readInt32()) {
6018 // Transaction tracing is always running but allow the user to temporarily
6019 // increase the buffer when actively debugging.
6020 mTransactionTracing->setBufferSize(
6021 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6022 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006023 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006024 mTransactionTracing->setBufferSize(
6025 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006026 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006027 }
6028 reply->writeInt32(NO_ERROR);
6029 return NO_ERROR;
6030 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006031 case 1042: { // Write layers trace or transaction trace to file
6032 if (mTransactionTracing) {
6033 mTransactionTracing->writeToFile();
6034 }
6035 if (mLayerTracingEnabled) {
6036 mLayerTracing.writeToFile();
6037 }
6038 reply->writeInt32(NO_ERROR);
6039 return NO_ERROR;
6040 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006041 }
6042 }
6043 return err;
6044}
6045
Ady Abrahama09852a2020-02-20 14:23:42 -08006046void SurfaceFlinger::kernelTimerChanged(bool expired) {
6047 static bool updateOverlay =
6048 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006049 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006050
6051 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006052 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006053 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006054 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006055 if (!display) {
6056 ALOGW("%s: default display is null", __func__);
6057 return;
6058 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006059 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006060
6061 const auto desiredActiveMode = display->getDesiredActiveMode();
6062 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6063 ? std::make_optional(desiredActiveMode->mode->getId())
6064 : std::nullopt;
6065
6066 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6067
Ady Abraham1b11bc62021-06-03 19:51:19 -07006068 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006069 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006070 }
6071 }));
6072}
6073
ramindani32cf0602022-03-02 02:30:29 +00006074std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6075SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6076 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6077 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6078 const auto timeout = getIdleTimerTimeout(displayId);
6079 if (isKernelIdleTimerHwcSupported) {
6080 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6081 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6082 // In order to decide if we can use the HWC api for idle timer
6083 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6084 // without relying on hasDisplayCapability.
6085 // hasDisplayCapability relies on DisplayCapabilities
6086 // which are updated after we set the PowerMode::ON.
6087 // DISPLAY_IDLE_TIMER is a display driver property
6088 // and is available before the PowerMode::ON
6089 return {KernelIdleTimerController::HwcApi, timeout};
6090 }
6091 return {std::nullopt, timeout};
6092 }
6093 if (getKernelIdleTimerSyspropConfig(displayId)) {
6094 return {KernelIdleTimerController::Sysprop, timeout};
6095 }
6096
6097 return {std::nullopt, timeout};
6098}
6099
6100void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6101 KernelIdleTimerController controller,
6102 PhysicalDisplayId displayId) {
6103 switch (controller) {
6104 case KernelIdleTimerController::HwcApi: {
6105 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6106 break;
6107 }
6108 case KernelIdleTimerController::Sysprop: {
6109 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6110 break;
6111 }
6112 }
6113}
6114
Ana Krulecb9afd792020-06-11 13:16:15 -07006115void SurfaceFlinger::toggleKernelIdleTimer() {
6116 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6117
Ady Abraham3efa3942021-06-24 19:01:25 -07006118 const auto display = getDefaultDisplayDeviceLocked();
6119 if (!display) {
6120 ALOGW("%s: default display is null", __func__);
6121 return;
6122 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006123
Ady Abrahame9316b72021-09-24 17:04:36 -07006124 // If the support for kernel idle timer is disabled for the active display,
6125 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006126 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6127 display->refreshRateConfigs().kernelIdleTimerController();
6128 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006129 return;
6130 }
6131
Ady Abraham3efa3942021-06-24 19:01:25 -07006132 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006133
Ana Krulecb9afd792020-06-11 13:16:15 -07006134 switch (action) {
6135 case KernelIdleTimerAction::TurnOff:
6136 if (mKernelIdleTimerEnabled) {
6137 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006138 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6139 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6140 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006141 mKernelIdleTimerEnabled = false;
6142 }
6143 break;
6144 case KernelIdleTimerAction::TurnOn:
6145 if (!mKernelIdleTimerEnabled) {
6146 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006147 const std::chrono::milliseconds timeout =
6148 display->refreshRateConfigs().getIdleTimerTimeout();
6149 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6150 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006151 mKernelIdleTimerEnabled = true;
6152 }
6153 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006154 }
6155}
6156
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006157// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6158class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006159public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006160 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6161 ~WindowDisconnector() {
6162 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006163 }
6164
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006165private:
6166 ANativeWindow* mWindow;
6167 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006168};
6169
chaviw93df2ea2019-04-30 16:45:12 -07006170static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6171 switch (colorMode) {
6172 case ColorMode::DISPLAY_P3:
6173 case ColorMode::BT2100_PQ:
6174 case ColorMode::BT2100_HLG:
6175 case ColorMode::DISPLAY_BT2020:
6176 return Dataspace::DISPLAY_P3;
6177 default:
6178 return Dataspace::V0_SRGB;
6179 }
6180}
6181
chaviwf5bb97b2021-04-28 15:35:37 -05006182static bool hasCaptureBlackoutContentPermission() {
6183 IPCThreadState* ipc = IPCThreadState::self();
6184 const int pid = ipc->getCallingPid();
6185 const int uid = ipc->getCallingUid();
6186 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6187 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6188}
6189
chaviw4b9d5e12020-08-04 18:30:35 -07006190static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6191 IPCThreadState* ipc = IPCThreadState::self();
6192 const int pid = ipc->getCallingPid();
6193 const int uid = ipc->getCallingUid();
6194 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6195 return OK;
6196 }
6197
6198 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6199 // itself, we allow it to continue.
6200 if (captureArgs.uid == uid) {
6201 return OK;
6202 }
6203
6204 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6205 return PERMISSION_DENIED;
6206}
6207
Peiyong Lin05cc0112020-10-14 16:16:37 -07006208status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6209 static constexpr int kFifoPriority = 2;
6210 static constexpr int kOtherPriority = 0;
6211
6212 struct sched_param param = {0};
6213 int sched_policy;
6214 if (enabled) {
6215 sched_policy = SCHED_FIFO;
6216 param.sched_priority = kFifoPriority;
6217 } else {
6218 sched_policy = SCHED_OTHER;
6219 param.sched_priority = kOtherPriority;
6220 }
6221
6222 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6223 return -errno;
6224 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006225
6226 return NO_ERROR;
6227}
6228
6229status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6230 static const unsigned int kUclampMin =
6231 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6232
6233 if (!kUclampMin) {
6234 // uclamp.min set to 0 (default), skip setting
6235 return NO_ERROR;
6236 }
6237
6238 // Currently, there is no wrapper in bionic: b/183240349.
6239 struct sched_attr {
6240 uint32_t size;
6241 uint32_t sched_policy;
6242 uint64_t sched_flags;
6243 int32_t sched_nice;
6244 uint32_t sched_priority;
6245 uint64_t sched_runtime;
6246 uint64_t sched_deadline;
6247 uint64_t sched_period;
6248 uint32_t sched_util_min;
6249 uint32_t sched_util_max;
6250 };
6251
6252 sched_attr attr = {};
6253 attr.size = sizeof(attr);
6254
6255 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6256 attr.sched_util_min = enabled ? kUclampMin : 0;
6257 attr.sched_util_max = 1024;
6258
6259 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6260 return -errno;
6261 }
6262
Peiyong Lin05cc0112020-10-14 16:16:37 -07006263 return NO_ERROR;
6264}
6265
chaviwd2432892020-07-24 17:42:39 -07006266status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006267 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006268 ATRACE_CALL();
6269
chaviw4b9d5e12020-08-04 18:30:35 -07006270 status_t validate = validateScreenshotPermissions(args);
6271 if (validate != OK) {
6272 return validate;
6273 }
6274
chaviwd2432892020-07-24 17:42:39 -07006275 if (!args.displayToken) return BAD_VALUE;
6276
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006277 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006278 ui::LayerStack layerStack;
6279 ui::Size reqSize(args.width, args.height);
6280 ui::Dataspace dataspace;
6281 {
6282 Mutex::Autolock lock(mStateLock);
6283 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6284 if (!display) return NAME_NOT_FOUND;
6285 displayWeak = display;
6286 layerStack = display->getLayerStack();
6287
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006288 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006289 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006290 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006291 }
6292
arthurhung79e81aa2020-08-28 00:09:19 +08006293 // The dataspace is depended on the color mode of display, that could use non-native mode
6294 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6295 // and failed if display is not in native mode. This provide a way to force using native
6296 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006297 dataspace = args.dataspace;
6298 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006299 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6300 dataspace = pickDataspaceFromColorMode(colorMode);
6301 }
chaviwd2432892020-07-24 17:42:39 -07006302 }
6303
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006304 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006305 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006306 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006307 });
6308
chaviw4b9d5e12020-08-04 18:30:35 -07006309 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6310 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006311 };
chaviw03900772020-08-18 12:34:51 -07006312
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006313 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6314 args.pixelFormat, args.allowProtected, args.grayscale,
6315 captureListener);
6316 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006317}
6318
Dominik Laskowskif1833852021-03-23 15:06:50 -07006319status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006320 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006321 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006322 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006323 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006324 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006325 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006326 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006327
Dominik Laskowskif1833852021-03-23 15:06:50 -07006328 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006329 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006330 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006331 }
6332
chaviw93df2ea2019-04-30 16:45:12 -07006333 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006334 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006335 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006336
chaviw426b5c02020-07-27 11:20:15 -07006337 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006338 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6339 }
6340
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006341 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006342 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006343 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006344 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006345 });
chaviw93df2ea2019-04-30 16:45:12 -07006346
Marin Shalamanov1c434292020-06-12 01:47:29 +02006347 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006348 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006349 };
6350
Sally Qi59a9f502021-10-12 18:53:23 +00006351 if (captureListener == nullptr) {
6352 ALOGE("capture screen must provide a capture listener callback");
6353 return BAD_VALUE;
6354 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006355
6356 constexpr bool kAllowProtected = false;
6357 constexpr bool kGrayscale = false;
6358
6359 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6360 ui::PixelFormat::RGBA_8888, kAllowProtected, kGrayscale,
6361 captureListener);
6362 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006363}
6364
chaviw3efadb12020-07-27 10:07:15 -07006365status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006366 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006367 ATRACE_CALL();
6368
chaviw4b9d5e12020-08-04 18:30:35 -07006369 status_t validate = validateScreenshotPermissions(args);
6370 if (validate != OK) {
6371 return validate;
6372 }
6373
Marin Shalamanov1c434292020-06-12 01:47:29 +02006374 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006375 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006376 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006377 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006378 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006379
6380 // Call this before holding mStateLock to avoid any deadlocking.
6381 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6382
Robert Carrc0df3122019-04-11 13:18:21 -07006383 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006384 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006385
Vishnu Nairf9096652021-07-20 18:49:42 -07006386 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006387 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006388 ALOGE("captureLayers called with an invalid or removed parent");
6389 return NAME_NOT_FOUND;
6390 }
6391
chaviwf5bb97b2021-04-28 15:35:37 -05006392 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006393 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006394 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6395 return PERMISSION_DENIED;
6396 }
6397
Robert Carr6a160312021-05-17 12:08:20 -07006398 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006399 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006400 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006401 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006402 }
6403
chaviw3efadb12020-07-27 10:07:15 -07006404 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006405 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006406 crop.bottom = parentSourceBounds.getHeight();
6407 }
6408
chaviw17ac24b2021-01-28 18:50:05 -08006409 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006410 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6411 // crop was not specified, or an invalid frame scale was provided.
6412 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006413 }
chaviw17ac24b2021-01-28 18:50:05 -08006414 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006415
chaviw3efadb12020-07-27 10:07:15 -07006416 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006417 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006418 if (excludeLayer != nullptr) {
6419 excludeLayers.emplace(excludeLayer);
6420 } else {
6421 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6422 return NAME_NOT_FOUND;
6423 }
6424 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006425
arthurhung79e81aa2020-08-28 00:09:19 +08006426 // The dataspace is depended on the color mode of display, that could use non-native mode
6427 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6428 // and failed if display is not in native mode. This provide a way to force using native
6429 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006430 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006431 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006432
Chia-I Wu20261cb2018-08-23 12:55:44 -07006433 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006434 if (reqSize.width <= 0 || reqSize.height <= 0) {
6435 ALOGW("Failed to captureLayes: crop or scale too small");
6436 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006437 }
6438
chaviw79468ab2021-10-27 11:11:24 -05006439 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006440 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006441 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006442 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006443 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006444 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006445 });
6446
chaviw03900772020-08-18 12:34:51 -07006447 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006448 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6449 if (!layer->isVisible()) {
6450 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006451 } else if (args.childrenOnly && layer == parent.get()) {
6452 return;
6453 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006454 return;
chaviwa76b2712017-09-20 12:02:26 -07006455 }
Robert Carr866455f2019-04-02 16:28:26 -07006456
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006457 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006458 while (p != nullptr) {
6459 if (excludeLayers.count(p) != 0) {
6460 return;
6461 }
6462 p = p->getParent();
6463 }
6464
chaviwa76b2712017-09-20 12:02:26 -07006465 visitor(layer);
6466 });
6467 };
Robert Carr108b2c72019-04-02 16:32:58 -07006468
Sally Qi59a9f502021-10-12 18:53:23 +00006469 if (captureListener == nullptr) {
6470 ALOGE("capture screen must provide a capture listener callback");
6471 return BAD_VALUE;
6472 }
6473
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006474 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6475 args.pixelFormat, args.allowProtected, args.grayscale,
6476 captureListener);
6477 return fenceStatus(future.get());
chaviwa76b2712017-09-20 12:02:26 -07006478}
6479
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006480ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Sally Qi59a9f502021-10-12 18:53:23 +00006481 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6482 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6483 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006484 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006485
Garfield Tan9c9c1912021-07-19 12:02:16 -07006486 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6487 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6488 ") that exceeds render target size limit.",
6489 bufferSize.getWidth(), bufferSize.getHeight());
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006490 return ftl::yield<FenceResult>(base::unexpected(BAD_VALUE)).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006491 }
6492
Peiyong Lin05cc0112020-10-14 16:16:37 -07006493 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6494 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6495 // A protected layer has no implication on whether it's secure, which is explicitly set by
6496 // application to avoid being screenshot or drawn via unsecure display.
6497 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6498 bool hasProtectedLayer = false;
6499 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006500 auto future = mScheduler->schedule([=]() {
6501 bool protectedLayerFound = false;
6502 traverseLayers([&](Layer* layer) {
6503 protectedLayerFound =
6504 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6505 });
6506 return protectedLayerFound;
6507 });
6508 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006509 }
6510
Richard Liucbcb8952020-04-08 10:51:55 +00006511 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6512 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006513 (hasProtectedLayer && allowProtected && supportsProtected
6514 ? GRALLOC_USAGE_PROTECTED
6515 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006516 sp<GraphicBuffer> buffer =
6517 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6518 static_cast<android_pixel_format>(reqPixelFormat),
6519 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006520
6521 const status_t bufferStatus = buffer->initCheck();
6522 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6523 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006524 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6525 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6526 renderengine::impl::ExternalTexture::Usage::
6527 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006528 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006529 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006530}
6531
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006532ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006533 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6534 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6535 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006536 ATRACE_CALL();
6537
chaviwf5bb97b2021-04-28 15:35:37 -05006538 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006539
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006540 auto future = mScheduler->schedule([=, renderAreaFuture = std::move(renderAreaFuture)]() mutable
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006541 -> ftl::SharedFuture<FenceResult> {
chaviw03900772020-08-18 12:34:51 -07006542 ScreenCaptureResults captureResults;
6543 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6544 if (!renderArea) {
6545 ALOGW("Skipping screen capture because of invalid render area.");
6546 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006547 captureListener->onScreenCaptureCompleted(captureResults);
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006548 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
chaviw03900772020-08-18 12:34:51 -07006549 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006550
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006551 ftl::SharedFuture<FenceResult> renderFuture;
chaviw03900772020-08-18 12:34:51 -07006552 renderArea->render([&] {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006553 renderFuture =
6554 renderScreenImpl(*renderArea, traverseLayers, buffer, canCaptureBlackoutContent,
6555 regionSampling, grayscale, captureResults);
chaviw03900772020-08-18 12:34:51 -07006556 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006557
6558 if (captureListener) {
Dominik Laskowskifb3beed2022-07-07 07:34:38 -07006559 // Defer blocking on renderFuture back to the Binder thread.
6560 return ftl::Future(std::move(renderFuture))
6561 .then([captureListener, captureResults = std::move(captureResults)](
6562 FenceResult fenceResult) mutable -> FenceResult {
6563 // TODO(b/232535621): Change ScreenCaptureResults to store a FenceResult.
6564 captureResults.result = fenceStatus(fenceResult);
6565 captureResults.fence = std::move(fenceResult).value_or(Fence::NO_FENCE);
6566 captureListener->onScreenCaptureCompleted(captureResults);
6567 return base::unexpected(NO_ERROR);
6568 })
6569 .share();
Sally Qi59a9f502021-10-12 18:53:23 +00006570 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006571 return renderFuture;
Sally Qi59a9f502021-10-12 18:53:23 +00006572 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006573
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006574 // Flatten nested futures.
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006575 auto chain = ftl::Future(std::move(future)).then([](ftl::SharedFuture<FenceResult> future) {
6576 return future;
6577 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006578
6579 return chain.share();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006580}
6581
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006582ftl::SharedFuture<FenceResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006583 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006584 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6585 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6586 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006587 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006588
chaviw426b5c02020-07-27 11:20:15 -07006589 traverseLayers([&](Layer* layer) {
6590 captureResults.capturedSecureLayers =
6591 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6592 });
6593
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006594 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006595
chaviw426b5c02020-07-27 11:20:15 -07006596 // We allow the system server to take screenshots of secure layers for
6597 // use in situations like the Screen-rotation animation and place
6598 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006599 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006600 ALOGW("FB is protected: PERMISSION_DENIED");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006601 return ftl::yield<FenceResult>(base::unexpected(PERMISSION_DENIED)).share();
chaviw426b5c02020-07-27 11:20:15 -07006602 }
6603
Alec Mouria90a5702021-04-16 16:36:21 +00006604 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006605 auto dataspace = renderArea.getReqDataSpace();
6606 auto parent = renderArea.getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00006607 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07006608 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
6609 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
6610
Robert Carr12a3b9b2022-03-10 09:55:29 -08006611 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6612 Mutex::Autolock lock(mStateLock);
6613 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6614 return display.getLayerStack() == layerStack;
6615 });
6616 if (!display) {
6617 // If the layer is not on a display, use the dataspace for the default display.
6618 display = getDefaultDisplayDeviceLocked();
6619 }
6620
6621 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6622 dataspace = pickDataspaceFromColorMode(colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00006623 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07006624 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
6625 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08006626 }
6627 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006628
chaviwa76b2712017-09-20 12:02:26 -07006629 const auto reqWidth = renderArea.getReqWidth();
6630 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006631 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006632 const auto transform = renderArea.getTransform();
6633 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006634 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006635
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006636 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006637 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006638
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006639 // assume that bounds are never offset, and that they are the same as the
6640 // buffer bounds.
6641 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006642 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006643 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006644
Robert Carr12a3b9b2022-03-10 09:55:29 -08006645 clientCompositionDisplay.outputDataspace = dataspace;
Sally Qie258f092022-05-19 15:24:12 -07006646 clientCompositionDisplay.currentLuminanceNits = displayBrightnessNits;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006647 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006648 clientCompositionDisplay.renderIntent =
6649 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006650
chaviw17ac24b2021-01-28 18:50:05 -08006651 const float colorSaturation = grayscale ? 0 : 1;
6652 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6653
chaviw50da5042018-04-09 13:49:37 -07006654 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006655
Vishnu Nair9b079a22020-01-21 14:36:08 -08006656 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006657 fillLayer.source.buffer.buffer = nullptr;
6658 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006659 fillLayer.geometry.boundaries =
6660 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006661 fillLayer.alpha = half(alpha);
6662 clientCompositionLayers.push_back(fillLayer);
6663
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006664 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006665 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006666 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006667 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006668 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006669
Lloyd Piquef16688f2019-02-19 17:47:57 -08006670 Region clip(renderArea.getBounds());
6671 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6672 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006673 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006674 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006675 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006676 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006677 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006678 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006679 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006680 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006681 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6682 BlurSetting::Disabled
6683 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6684 BlurSetting::Enabled,
Sally Qidb653012022-05-04 13:12:22 -07006685 isHdrLayer(layer) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006686
Lloyd Piquef16688f2019-02-19 17:47:57 -08006687 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006688 std::vector<compositionengine::LayerFE::LayerSettings> results =
6689 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006690 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006691 for (auto& settings : results) {
6692 settings.geometry.positionTransform =
6693 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006694 // There's no need to process blurs when we're executing region sampling,
6695 // we're just trying to understand what we're drawing, and doing so without
6696 // blurs is already a pretty good approximation.
6697 if (regionSampling) {
6698 settings.backgroundBlurRadius = 0;
6699 }
Sally Qidb653012022-05-04 13:12:22 -07006700 captureResults.capturedHdrLayers |= isHdrLayer(layer);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006701 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006702
Yichi Chen40773d92020-04-01 10:10:18 +08006703 clientCompositionLayers.insert(clientCompositionLayers.end(),
6704 std::make_move_iterator(results.begin()),
6705 std::make_move_iterator(results.end()));
6706 renderedLayers.push_back(layer);
6707 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006708
chaviwa76b2712017-09-20 12:02:26 -07006709 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006710
Sally Qi59a9f502021-10-12 18:53:23 +00006711 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6712 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006713 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006714 std::back_inserter(clientRenderEngineLayers),
6715 [](compositionengine::LayerFE::LayerSettings& settings)
6716 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006717
Alec Mouri6338c9d2019-02-07 16:57:51 -08006718 // Use an empty fence for the buffer fence, since we just created the buffer so
6719 // there is no need for synchronization with the GPU.
6720 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006721 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006722
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006723 constexpr bool kUseFramebufferCache = false;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006724 auto chain =
6725 ftl::Future(getRenderEngine().drawLayers(clientCompositionDisplay,
6726 clientRenderEngineLayers, buffer,
6727 kUseFramebufferCache, std::move(bufferFence)))
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006728 .then(&toFenceResult);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006729
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006730 const auto future = chain.share();
Sally Qi59a9f502021-10-12 18:53:23 +00006731 for (auto* layer : renderedLayers) {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006732 layer->onLayerDisplayed(future);
Yichi Chen40773d92020-04-01 10:10:18 +08006733 }
Ady Abraham99599942021-01-27 20:27:23 -08006734
Peiyong Lin05cc0112020-10-14 16:16:37 -07006735 // Always switch back to unprotected context.
6736 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006737
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006738 return future;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006739}
6740
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006741// ---------------------------------------------------------------------------
6742
Edgar Arriaga844fa672020-01-16 14:21:42 -08006743void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6744 layersSortedByZ.traverse(visitor);
6745}
6746
Dan Stoza412903f2017-04-27 13:42:17 -07006747void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6748 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006749}
6750
Dan Stoza412903f2017-04-27 13:42:17 -07006751void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6752 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006753}
6754
chaviw4b9d5e12020-08-04 18:30:35 -07006755void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006756 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006757 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006758 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006759 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006760 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006761 continue;
6762 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006763 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006764 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006765 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006766 return;
6767 }
chaviwa76b2712017-09-20 12:02:26 -07006768 if (!layer->isVisible()) {
6769 return;
6770 }
chaviw4b9d5e12020-08-04 18:30:35 -07006771 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6772 return;
6773 }
chaviwa76b2712017-09-20 12:02:26 -07006774 visitor(layer);
6775 });
6776 }
6777}
6778
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006779status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006780 const sp<DisplayDevice>& display,
6781 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006782 Mutex::Autolock lock(mStateLock);
6783
Ady Abrahamfb853662021-04-09 11:46:40 -07006784 if (mDebugDisplayModeSetByBackdoor) {
6785 // ignore this request as mode is overridden by backdoor
6786 return NO_ERROR;
6787 }
6788
Ady Abrahama92a5682022-06-07 23:35:38 +00006789 const status_t setPolicyResult = display->setRefreshRatePolicy(policy, overridePolicy);
Ady Abraham3efa3942021-06-24 19:01:25 -07006790 if (setPolicyResult < 0) {
6791 return BAD_VALUE;
6792 }
6793 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6794 return NO_ERROR;
6795 }
6796
Ady Abraham3efa3942021-06-24 19:01:25 -07006797 scheduler::RefreshRateConfigs::Policy currentPolicy =
6798 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006799
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006800 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006801
Ana Krulecb9afd792020-06-11 13:16:15 -07006802 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6803 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006804 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006805 if (isDisplayActiveLocked(display)) {
6806 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6807 toggleKernelIdleTimer();
6808 } else {
6809 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6810 }
Ady Abraham838de062019-02-04 10:24:03 -08006811
Ady Abraham690f4612021-07-01 23:24:03 -07006812 const DisplayModePtr preferredDisplayMode = [&] {
6813 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6814 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6815 return schedulerMode;
6816 }
6817
6818 return display->getMode(currentPolicy.defaultMode);
6819 }();
6820
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006821 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006822 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006823
Ady Abraham690f4612021-07-01 23:24:03 -07006824 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006825 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006826 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006827 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006828 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006829 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006830 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006831 }
6832
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006833 return NO_ERROR;
6834}
6835
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006836status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6837 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6838 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6839 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006840 ATRACE_CALL();
6841
6842 if (!displayToken) {
6843 return BAD_VALUE;
6844 }
6845
Dominik Laskowski756b7892021-08-04 12:53:59 -07006846 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006847 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006848 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006849 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006850 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006851 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006852 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006853 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006854 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006855 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006856 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006857 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006858 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006859 {Fps::fromValue(primaryRefreshRateMin),
6860 Fps::fromValue(primaryRefreshRateMax)},
6861 {Fps::fromValue(appRequestRefreshRateMin),
6862 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006863 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006864
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006865 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006866 }
6867 });
6868
6869 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006870}
6871
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006872status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6873 ui::DisplayModeId* outDefaultMode,
6874 bool* outAllowGroupSwitching,
6875 float* outPrimaryRefreshRateMin,
6876 float* outPrimaryRefreshRateMax,
6877 float* outAppRequestRefreshRateMin,
6878 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006879 ATRACE_CALL();
6880
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006881 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006882 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006883 return BAD_VALUE;
6884 }
6885
6886 Mutex::Autolock lock(mStateLock);
6887 const auto display = getDisplayDeviceLocked(displayToken);
6888 if (!display) {
6889 return NAME_NOT_FOUND;
6890 }
6891
Ady Abraham3efa3942021-06-24 19:01:25 -07006892 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006893 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006894 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006895
6896 scheduler::RefreshRateConfigs::Policy policy =
6897 display->refreshRateConfigs().getDisplayManagerPolicy();
6898 *outDefaultMode = policy.defaultMode.value();
6899 *outAllowGroupSwitching = policy.allowGroupSwitching;
6900 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6901 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6902 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6903 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6904 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006905}
6906
Vishnu Nairf9096652021-07-20 18:49:42 -07006907wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6908 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006909}
6910
Dominik Laskowski75848362019-11-11 17:57:20 -08006911void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006912 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006913 if (!layer->isRemovedFromCurrentState()) {
6914 mScheduler->registerLayer(layer);
6915 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006916}
6917
6918void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6919 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006920 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006921 if (!layer->isRemovedFromCurrentState()) {
6922 mScheduler->deregisterLayer(layer);
6923 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08006924 if (mTransactionTracing) {
6925 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08006926 }
Valerie Hauc5686802019-11-22 14:18:09 -08006927}
6928
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006929void SurfaceFlinger::onLayerUpdate() {
6930 scheduleCommit(FrameHint::kActive);
6931}
6932
Valerie Hauc5686802019-11-22 14:18:09 -08006933// WARNING: ONLY CALL THIS FROM LAYER DTOR
6934// Here we add children in the current state to offscreen layers and remove the
6935// layer itself from the offscreen layer list. Since
6936// this is the dtor, it is safe to access the current state. This keeps us
6937// from dangling children layers such that they are not reachable from the
6938// Drawing state nor the offscreen layer list
6939// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07006940void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08006941 for (auto& child : layer->getCurrentChildren()) {
6942 mOffscreenLayers.emplace(child.get());
6943 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006944 mOffscreenLayers.erase(layer);
6945}
6946
Robert Carr867be372021-06-29 17:36:02 -07006947void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6948 mOffscreenLayers.erase(layer);
6949}
6950
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006951status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6952 float lightPosY, float lightPosZ,
6953 float lightRadius) {
6954 Mutex::Autolock _l(mStateLock);
6955 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6956 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6957 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6958 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6959 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6960
6961 // these values are overridden when calculating the shadow settings for a layer.
6962 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6963 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006964 return NO_ERROR;
6965}
6966
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006967const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6968 const {
6969 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6970 // on the work to remove the table in that bug rather than adding more to
6971 // it.
6972 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08006973 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
6974 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006975 };
6976 return genericLayerMetadataKeyMap;
6977}
6978
Andy Yu2ae6b6b2021-11-18 14:51:06 -08006979status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
6980 PhysicalDisplayId displayId = [&]() {
6981 Mutex::Autolock lock(mStateLock);
6982 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6983 }();
6984
6985 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
6986 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
6987 return NO_ERROR;
6988}
6989
Dominik Laskowski20134642020-04-20 22:36:44 -07006990void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07006991 for (const auto& [ignored, display] : mDisplays) {
6992 if (display->isInternal()) {
6993 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07006994 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07006995 }
Dominik Laskowski20134642020-04-20 22:36:44 -07006996}
6997
Pablo Gamito6ee484d2020-07-30 14:26:28 +00006998status_t SurfaceFlinger::addTransactionTraceListener(
6999 const sp<gui::ITransactionTraceListener>& listener) {
7000 if (!listener) {
7001 return BAD_VALUE;
7002 }
7003
7004 mInterceptor->addTransactionTraceListener(listener);
7005
7006 return NO_ERROR;
7007}
7008
Huihong Luo02186fb2022-02-23 14:21:54 -08007009int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007010 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007011}
7012
Ady Abraham899dcdb2021-06-15 16:56:21 -07007013int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7014 std::chrono::nanoseconds presentLatency) {
7015 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7016 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007017 pipelineDepth++;
7018 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007019 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007020}
7021
Ady Abraham899dcdb2021-06-15 16:56:21 -07007022status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007023 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007024
7025 if (!getHwComposer().isHeadless()) {
7026 if (const auto display = getDefaultDisplayDevice()) {
7027 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007028 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007029 }
7030
7031 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007032 return NO_ERROR;
7033}
7034
rnleeed20fa42021-08-10 18:00:03 -07007035uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007036 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007037
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007038 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7039 refreshRate = *frameRateOverride;
7040 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007041 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007042 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007043 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007044 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007045
Ady Abraham899dcdb2021-06-15 16:56:21 -07007046 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7047}
7048
7049int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7050 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7051 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7052 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7053}
7054
Vishnu Nair286f4f92022-06-08 16:37:39 -07007055void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state, int64_t vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007056 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007057 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007058 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7059 return;
arthurhungdba591c2021-02-08 17:28:49 +08007060 }
7061
7062 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007063 bool addToRoot = state.addToRoot;
7064 if (state.initialParent != nullptr) {
7065 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007066 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007067 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007068 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007069 }
arthurhungdba591c2021-02-08 17:28:49 +08007070 }
7071
Garfield Tand712ad32021-10-27 13:44:22 -07007072 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007073 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007074 mCurrentState.layersSortedByZ.add(layer);
7075 } else if (parent == nullptr) {
7076 layer->onRemovedFromCurrentState();
7077 } else if (parent->isRemovedFromCurrentState()) {
7078 parent->addChild(layer);
7079 layer->onRemovedFromCurrentState();
7080 } else {
7081 parent->addChild(layer);
7082 }
7083
Ady Abraham1273ac12021-08-26 17:31:53 -07007084 layer->updateTransformHint(mActiveDisplayTransformHint);
Vishnu Nair286f4f92022-06-08 16:37:39 -07007085 if (mTransactionTracing) {
7086 mTransactionTracing->onLayerAddedToDrawingState(layer->getSequence(), vsyncId);
7087 }
Arthur Hung23e07502021-10-15 11:58:19 +00007088 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007089}
Ady Abraham562c2712021-05-07 15:10:42 -07007090
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007091void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007092 if (!mLumaSampling || !mRegionSamplingThread) {
7093 return;
7094 }
7095
Dominik Laskowski756b7892021-08-04 12:53:59 -07007096 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007097}
7098
Ady Abrahamed3290f2021-05-17 15:12:14 -07007099void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7100 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7101 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7102}
7103
7104void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7105 ATRACE_CALL();
7106
Ady Abrahamdb036a82021-07-16 14:18:34 -07007107 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7108 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7109 }
7110
Ady Abrahamed3290f2021-05-17 15:12:14 -07007111 if (!activeDisplay) {
7112 ALOGE("%s: activeDisplay is null", __func__);
7113 return;
7114 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007115 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007116 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007117 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007118 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007119 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007120 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007121 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007122
7123 // Update the kernel timer for the current active display, since the policy
7124 // for this display might have changed when it was not the active display.
7125 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007126}
7127
chaviw60c9d3e2021-06-04 12:52:17 -05007128status_t SurfaceFlinger::addWindowInfosListener(
7129 const sp<IWindowInfosListener>& windowInfosListener) const {
7130 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7131 return NO_ERROR;
7132}
7133
7134status_t SurfaceFlinger::removeWindowInfosListener(
7135 const sp<IWindowInfosListener>& windowInfosListener) const {
7136 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7137 return NO_ERROR;
7138}
7139
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007140std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7141 const BufferData& bufferData, const char* layerName) const {
7142 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7143 bool bufferSizeExceedsLimit = false;
7144 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7145 if (cacheIdChanged && bufferData.buffer != nullptr) {
7146 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7147 bufferData.buffer->getHeight());
7148 if (!bufferSizeExceedsLimit) {
7149 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7150 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7151 }
7152 } else if (cacheIdChanged) {
7153 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7154 } else if (bufferData.buffer != nullptr) {
7155 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7156 bufferData.buffer->getHeight());
7157 if (!bufferSizeExceedsLimit) {
7158 buffer = std::make_shared<
7159 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7160 renderengine::impl::ExternalTexture::
7161 Usage::READABLE);
7162 }
7163 }
7164 ALOGE_IF(bufferSizeExceedsLimit,
7165 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7166 "limit.",
7167 layerName);
7168 return buffer;
7169}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007170
Vishnu Nair286f4f92022-06-08 16:37:39 -07007171bool SurfaceFlinger::commitCreatedLayers(int64_t vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007172 std::vector<LayerCreatedState> createdLayers;
7173 {
7174 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7175 createdLayers = std::move(mCreatedLayers);
7176 mCreatedLayers.clear();
7177 if (createdLayers.size() == 0) {
7178 return false;
7179 }
7180 }
7181
7182 Mutex::Autolock _l(mStateLock);
7183 for (const auto& createdLayer : createdLayers) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07007184 handleLayerCreatedLocked(createdLayer, vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007185 }
7186 createdLayers.clear();
7187 mLayersAdded = true;
7188 return true;
7189}
Huihong Luof5029222021-12-16 14:33:46 -08007190
7191// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007192
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007193binder::Status SurfaceComposerAIDL::bootFinished() {
7194 status_t status = checkAccessPermission();
7195 if (status != OK) {
7196 return binderStatusFromStatusT(status);
7197 }
7198 mFlinger->bootFinished();
7199 return binder::Status::ok();
7200}
7201
7202binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7203 VsyncSource vsyncSource, EventRegistration eventRegistration,
7204 sp<IDisplayEventConnection>* outConnection) {
7205 sp<IDisplayEventConnection> conn =
7206 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration);
7207 if (conn == nullptr) {
7208 *outConnection = nullptr;
7209 return binderStatusFromStatusT(BAD_VALUE);
7210 } else {
7211 *outConnection = conn;
7212 return binder::Status::ok();
7213 }
7214}
7215
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007216binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
7217 const sp<Client> client = new Client(mFlinger);
7218 if (client->initCheck() == NO_ERROR) {
7219 *outClient = client;
7220 return binder::Status::ok();
7221 } else {
7222 *outClient = nullptr;
7223 return binderStatusFromStatusT(BAD_VALUE);
7224 }
7225}
7226
Huihong Luo07e72362022-02-14 14:26:04 -08007227binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7228 sp<IBinder>* outDisplay) {
7229 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007230 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007231 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007232 }
Huihong Luo37396db2022-02-15 10:43:00 -08007233 String8 displayName8 = String8::format("%s", displayName.c_str());
7234 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7235 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007236}
7237
7238binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7239 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007240 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007241 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007242 }
Huihong Luo37396db2022-02-15 10:43:00 -08007243 mFlinger->destroyDisplay(display);
7244 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007245}
7246
7247binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7248 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7249 std::vector<int64_t> displayIds;
7250 displayIds.reserve(physicalDisplayIds.size());
7251 for (auto item : physicalDisplayIds) {
7252 displayIds.push_back(static_cast<int64_t>(item.value));
7253 }
7254 *outDisplayIds = displayIds;
7255 return binder::Status::ok();
7256}
7257
7258binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7259 status_t status = checkAccessPermission();
7260 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007261 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007262 }
7263
7264 PhysicalDisplayId id;
7265 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7266 if (status == NO_ERROR) {
7267 *outDisplayId = id.value;
7268 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007269 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007270}
7271
7272binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7273 sp<IBinder>* outDisplay) {
7274 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7275 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7276 return binder::Status::ok();
7277}
7278
Huihong Luo37396db2022-02-15 10:43:00 -08007279binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7280 status_t status = checkAccessPermission();
7281 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007282 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007283 }
7284 mFlinger->setPowerMode(display, mode);
7285 return binder::Status::ok();
7286}
7287
Huihong Luo0a81aa32022-02-22 16:02:36 -08007288binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7289 std::vector<FrameEvent>* outSupported) {
7290 status_t status;
7291 if (!outSupported) {
7292 status = UNEXPECTED_NULL;
7293 } else {
7294 outSupported->clear();
7295 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7296 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007297 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007298}
7299
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007300binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7301 gui::DisplayStatInfo* outStatInfo) {
7302 DisplayStatInfo statInfo;
7303 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7304 if (status == NO_ERROR) {
7305 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7306 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7307 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007308 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007309}
7310
7311binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7312 gui::DisplayState* outState) {
7313 ui::DisplayState state;
7314 status_t status = mFlinger->getDisplayState(display, &state);
7315 if (status == NO_ERROR) {
7316 outState->layerStack = state.layerStack.id;
7317 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7318 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7319 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7320 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007321 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007322}
7323
Huihong Luoa79ddf42022-02-17 00:01:38 -08007324binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7325 gui::StaticDisplayInfo* outInfo) {
7326 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7327 ui::StaticDisplayInfo info;
7328 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7329 if (status == NO_ERROR) {
7330 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7331 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7332 outInfo->density = info.density;
7333 outInfo->secure = info.secure;
7334 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7335
7336 gui::DeviceProductInfo dinfo;
7337 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7338 dinfo.name = std::move(dpi->name);
7339 dinfo.manufacturerPnpId =
7340 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7341 dinfo.productId = dpi->productId;
Kriti Dang1de958d2022-05-30 15:26:58 +02007342 dinfo.relativeAddress =
7343 std::vector<uint8_t>(dpi->relativeAddress.begin(), dpi->relativeAddress.end());
Huihong Luoa79ddf42022-02-17 00:01:38 -08007344 if (const auto* model =
7345 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7346 gui::DeviceProductInfo::ModelYear modelYear;
7347 modelYear.year = model->year;
7348 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7349 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7350 &dpi->manufactureOrModelDate)) {
7351 gui::DeviceProductInfo::ManufactureYear date;
7352 date.modelYear.year = manufacture->year;
7353 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7354 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7355 &dpi->manufactureOrModelDate)) {
7356 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7357 date.manufactureYear.modelYear.year = manufacture->year;
7358 date.week = manufacture->week;
7359 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7360 }
7361
7362 outInfo->deviceProductInfo = dinfo;
7363 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007364 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007365}
7366
Huihong Luo38603fd2022-02-21 14:32:54 -08007367binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7368 gui::DynamicDisplayInfo* outInfo) {
7369 ui::DynamicDisplayInfo info;
7370 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7371 if (status == NO_ERROR) {
7372 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7373 outInfo->supportedDisplayModes.clear();
7374 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7375 for (const auto& mode : info.supportedDisplayModes) {
7376 gui::DisplayMode outMode;
7377 outMode.id = mode.id;
7378 outMode.resolution.width = mode.resolution.width;
7379 outMode.resolution.height = mode.resolution.height;
7380 outMode.xDpi = mode.xDpi;
7381 outMode.yDpi = mode.yDpi;
7382 outMode.refreshRate = mode.refreshRate;
7383 outMode.appVsyncOffset = mode.appVsyncOffset;
7384 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7385 outMode.presentationDeadline = mode.presentationDeadline;
7386 outMode.group = mode.group;
7387 outInfo->supportedDisplayModes.push_back(outMode);
7388 }
7389
7390 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7391
7392 outInfo->supportedColorModes.clear();
7393 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7394 for (const auto& cmode : info.supportedColorModes) {
7395 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7396 }
7397
7398 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7399
7400 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7401 hdrCapabilities.supportedHdrTypes.clear();
7402 hdrCapabilities.supportedHdrTypes.reserve(
7403 info.hdrCapabilities.getSupportedHdrTypes().size());
7404 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7405 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7406 }
7407 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7408 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7409 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7410
7411 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7412 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7413 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7414 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007415 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007416}
7417
Huihong Luoca3d9a42022-02-22 11:07:34 -08007418binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7419 gui::DisplayPrimaries* outPrimaries) {
7420 ui::DisplayPrimaries primaries;
7421 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7422 if (status == NO_ERROR) {
7423 outPrimaries->red.X = primaries.red.X;
7424 outPrimaries->red.Y = primaries.red.Y;
7425 outPrimaries->red.Z = primaries.red.Z;
7426
7427 outPrimaries->green.X = primaries.green.X;
7428 outPrimaries->green.Y = primaries.green.Y;
7429 outPrimaries->green.Z = primaries.green.Z;
7430
7431 outPrimaries->blue.X = primaries.blue.X;
7432 outPrimaries->blue.Y = primaries.blue.Y;
7433 outPrimaries->blue.Z = primaries.blue.Z;
7434
7435 outPrimaries->white.X = primaries.white.X;
7436 outPrimaries->white.Y = primaries.white.Y;
7437 outPrimaries->white.Z = primaries.white.Z;
7438 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007439 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007440}
7441
7442binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7443 status_t status = checkAccessPermission();
7444 if (status == OK) {
7445 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7446 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007447 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007448}
7449
7450binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7451 int displayModeId) {
7452 status_t status = checkAccessPermission();
7453 if (status == OK) {
7454 status = mFlinger->setBootDisplayMode(display,
7455 static_cast<ui::DisplayModeId>(displayModeId));
7456 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007457 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007458}
7459
Huihong Luo37396db2022-02-15 10:43:00 -08007460binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7461 status_t status = checkAccessPermission();
7462 if (status == OK) {
7463 status = mFlinger->clearBootDisplayMode(display);
7464 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007465 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007466}
7467
7468binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7469 status_t status = checkAccessPermission();
7470 if (status == OK) {
7471 status = mFlinger->getBootDisplayModeSupport(outMode);
7472 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007473 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007474}
7475
7476binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7477 status_t status = checkAccessPermission();
7478 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007479 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007480 }
7481 mFlinger->setAutoLowLatencyMode(display, on);
7482 return binder::Status::ok();
7483}
7484
7485binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7486 status_t status = checkAccessPermission();
7487 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007488 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007489 }
7490 mFlinger->setGameContentType(display, on);
7491 return binder::Status::ok();
7492}
7493
Huihong Luof5029222021-12-16 14:33:46 -08007494binder::Status SurfaceComposerAIDL::captureDisplay(
7495 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7496 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007497 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007498}
7499
7500binder::Status SurfaceComposerAIDL::captureDisplayById(
7501 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7502 status_t status;
7503 IPCThreadState* ipc = IPCThreadState::self();
7504 const int uid = ipc->getCallingUid();
7505 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7506 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7507 status = mFlinger->captureDisplay(*id, captureListener);
7508 } else {
7509 status = PERMISSION_DENIED;
7510 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007511 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007512}
7513
7514binder::Status SurfaceComposerAIDL::captureLayers(
7515 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7516 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007517 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007518}
7519
Huihong Luo4ed1c912022-02-22 14:30:01 -08007520binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7521 status_t status = checkAccessPermission();
7522 if (status == OK) {
7523 status = mFlinger->clearAnimationFrameStats();
7524 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007525 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007526}
7527
7528binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7529 status_t status = checkAccessPermission();
7530 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007531 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007532 }
7533
7534 FrameStats stats;
7535 status = mFlinger->getAnimationFrameStats(&stats);
7536 if (status == NO_ERROR) {
7537 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7538 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7539 for (const auto& t : stats.desiredPresentTimesNano) {
7540 outStats->desiredPresentTimesNano.push_back(t);
7541 }
7542 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7543 for (const auto& t : stats.actualPresentTimesNano) {
7544 outStats->actualPresentTimesNano.push_back(t);
7545 }
7546 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7547 for (const auto& t : stats.frameReadyTimesNano) {
7548 outStats->frameReadyTimesNano.push_back(t);
7549 }
7550 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007551 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007552}
7553
Huihong Luo05539a12022-02-23 10:29:40 -08007554binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7555 const std::vector<int32_t>& hdrTypes) {
7556 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7557 // permission dynamically. Don't use the permission cache for this check.
7558 status_t status = checkAccessPermission(false);
7559 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007560 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007561 }
7562
7563 std::vector<ui::Hdr> hdrTypesVector;
7564 for (int32_t i : hdrTypes) {
7565 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7566 }
7567 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007568 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007569}
7570
7571binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7572 status_t status;
7573 const int uid = IPCThreadState::self()->getCallingUid();
7574 if (uid != AID_SYSTEM) {
7575 status = PERMISSION_DENIED;
7576 } else {
7577 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7578 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007579 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007580}
7581
7582binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7583 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007584 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007585 }
7586
7587 status_t status = checkAccessPermission();
7588 if (status == OK) {
7589 status = mFlinger->enableVSyncInjections(enable);
7590 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007591 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007592}
7593
7594binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7595 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007596 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007597 }
7598
7599 status_t status = checkAccessPermission();
7600 if (status == OK) {
7601 status = mFlinger->injectVSync(when);
7602 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007603 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007604}
7605
7606binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7607 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007608 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007609 }
7610
7611 IPCThreadState* ipc = IPCThreadState::self();
7612 const int pid = ipc->getCallingPid();
7613 const int uid = ipc->getCallingUid();
7614 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7615 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007616 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007617 }
7618 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007619 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007620}
7621
7622binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7623 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007624 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007625}
7626
7627binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7628 ui::Dataspace dataspace;
7629 ui::PixelFormat pixelFormat;
7630 ui::Dataspace wideColorGamutDataspace;
7631 ui::PixelFormat wideColorGamutPixelFormat;
7632 status_t status =
7633 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7634 &wideColorGamutPixelFormat);
7635 if (status == NO_ERROR) {
7636 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7637 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7638 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7639 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7640 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007641 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007642}
7643
7644binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7645 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7646 status_t status = checkAccessPermission();
7647 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007648 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007649 }
7650
7651 ui::PixelFormat format;
7652 ui::Dataspace dataspace;
7653 uint8_t componentMask;
7654 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7655 &componentMask);
7656 if (status == NO_ERROR) {
7657 outAttrs->format = static_cast<int32_t>(format);
7658 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7659 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7660 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007661 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007662}
7663
7664binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7665 bool enable,
7666 int8_t componentMask,
7667 int64_t maxFrames) {
7668 status_t status = checkAccessPermission();
7669 if (status == OK) {
7670 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7671 static_cast<uint8_t>(componentMask),
7672 static_cast<uint64_t>(maxFrames));
7673 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007674 return binderStatusFromStatusT(status);
7675}
7676
7677binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7678 int64_t maxFrames, int64_t timestamp,
7679 gui::DisplayedFrameStats* outStats) {
7680 if (!outStats) {
7681 return binderStatusFromStatusT(BAD_VALUE);
7682 }
7683
7684 status_t status = checkAccessPermission();
7685 if (status != OK) {
7686 return binderStatusFromStatusT(status);
7687 }
7688
7689 DisplayedFrameStats stats;
7690 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7691 static_cast<uint64_t>(timestamp), &stats);
7692 if (status == NO_ERROR) {
7693 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7694 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7695 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7696 for (const auto& s : stats.component_0_sample) {
7697 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7698 }
7699 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7700 for (const auto& s : stats.component_1_sample) {
7701 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7702 }
7703 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7704 for (const auto& s : stats.component_2_sample) {
7705 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7706 }
7707 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7708 for (const auto& s : stats.component_3_sample) {
7709 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7710 }
7711 }
7712 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007713}
7714
7715binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7716 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007717 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007718}
7719
Huihong Luo37396db2022-02-15 10:43:00 -08007720binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7721 bool* outIsWideColorDisplay) {
7722 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007723 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007724}
7725
Huihong Luo02186fb2022-02-23 14:21:54 -08007726binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7727 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7728 const sp<gui::IRegionSamplingListener>& listener) {
7729 status_t status = checkReadFrameBufferPermission();
7730 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007731 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007732 }
7733 android::Rect rect;
7734 rect.left = samplingArea.left;
7735 rect.top = samplingArea.top;
7736 rect.right = samplingArea.right;
7737 rect.bottom = samplingArea.bottom;
7738 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007739 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007740}
7741
7742binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7743 const sp<gui::IRegionSamplingListener>& listener) {
7744 status_t status = checkReadFrameBufferPermission();
7745 if (status == OK) {
7746 status = mFlinger->removeRegionSamplingListener(listener);
7747 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007748 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007749}
7750
7751binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7752 const sp<gui::IFpsListener>& listener) {
7753 status_t status = checkReadFrameBufferPermission();
7754 if (status == OK) {
7755 status = mFlinger->addFpsListener(taskId, listener);
7756 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007757 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007758}
7759
7760binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7761 status_t status = checkReadFrameBufferPermission();
7762 if (status == OK) {
7763 status = mFlinger->removeFpsListener(listener);
7764 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007765 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007766}
7767
7768binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7769 const sp<gui::ITunnelModeEnabledListener>& listener) {
7770 status_t status = checkAccessPermission();
7771 if (status == OK) {
7772 status = mFlinger->addTunnelModeEnabledListener(listener);
7773 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007774 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007775}
7776
7777binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7778 const sp<gui::ITunnelModeEnabledListener>& listener) {
7779 status_t status = checkAccessPermission();
7780 if (status == OK) {
7781 status = mFlinger->removeTunnelModeEnabledListener(listener);
7782 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007783 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007784}
7785
7786binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7787 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7788 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7789 float appRequestRefreshRateMax) {
7790 status_t status = checkAccessPermission();
7791 if (status == OK) {
7792 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7793 static_cast<ui::DisplayModeId>(defaultMode),
7794 allowGroupSwitching, primaryRefreshRateMin,
7795 primaryRefreshRateMax,
7796 appRequestRefreshRateMin,
7797 appRequestRefreshRateMax);
7798 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007799 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007800}
7801
7802binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7803 gui::DisplayModeSpecs* outSpecs) {
7804 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007805 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007806 }
7807
7808 status_t status = checkAccessPermission();
7809 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007810 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007811 }
7812
7813 ui::DisplayModeId displayModeId;
7814 bool allowGroupSwitching;
7815 float primaryRefreshRateMin;
7816 float primaryRefreshRateMax;
7817 float appRequestRefreshRateMin;
7818 float appRequestRefreshRateMax;
7819 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7820 &allowGroupSwitching, &primaryRefreshRateMin,
7821 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7822 &appRequestRefreshRateMax);
7823 if (status == NO_ERROR) {
7824 outSpecs->defaultMode = displayModeId;
7825 outSpecs->allowGroupSwitching = allowGroupSwitching;
7826 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7827 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7828 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7829 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7830 }
7831
Huihong Luo3bdef862022-03-03 11:57:19 -08007832 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007833}
7834
Huihong Luo37396db2022-02-15 10:43:00 -08007835binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7836 bool* outSupport) {
7837 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007838 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007839}
7840
7841binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7842 const gui::DisplayBrightness& brightness) {
7843 status_t status = checkControlDisplayBrightnessPermission();
7844 if (status == OK) {
7845 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7846 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007847 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007848}
7849
7850binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7851 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7852 status_t status = checkControlDisplayBrightnessPermission();
7853 if (status == OK) {
7854 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7855 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007856 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007857}
7858
7859binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7860 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7861 status_t status = checkControlDisplayBrightnessPermission();
7862 if (status == OK) {
7863 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7864 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007865 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007866}
7867
7868binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7869 status_t status = checkAccessPermission();
7870 if (status == OK) {
7871 status = mFlinger->notifyPowerBoost(boostId);
7872 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007873 return binderStatusFromStatusT(status);
7874}
7875
7876binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7877 const gui::Color& spotColor,
7878 float lightPosY, float lightPosZ,
7879 float lightRadius) {
7880 status_t status = checkAccessPermission();
7881 if (status != OK) {
7882 return binderStatusFromStatusT(status);
7883 }
7884
7885 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7886 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7887 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7888 lightPosZ, lightRadius);
7889 return binderStatusFromStatusT(status);
7890}
7891
7892binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7893 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7894 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7895 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7896 if (status != NO_ERROR) {
7897 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7898 return binderStatusFromStatusT(status);
7899 }
7900
7901 if (!support || !support.has_value()) {
7902 outSupport->reset();
7903 } else {
7904 outSupport->emplace();
7905 outSupport->value().format = static_cast<int32_t>(support->format);
7906 outSupport->value().alphaInterpretation =
7907 static_cast<int32_t>(support->alphaInterpretation);
7908 }
7909
7910 return binder::Status::ok();
7911}
7912
7913binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
7914 status_t status;
7915 const int c_uid = IPCThreadState::self()->getCallingUid();
7916 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
7917 status = mFlinger->setOverrideFrameRate(uid, frameRate);
7918 } else {
7919 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
7920 status = PERMISSION_DENIED;
7921 }
7922 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007923}
7924
Huihong Luo02186fb2022-02-23 14:21:54 -08007925binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
7926 const sp<gui::ITransactionTraceListener>& listener) {
7927 status_t status;
7928 IPCThreadState* ipc = IPCThreadState::self();
7929 const int uid = ipc->getCallingUid();
7930 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7931 status = mFlinger->addTransactionTraceListener(listener);
7932 } else {
7933 status = PERMISSION_DENIED;
7934 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007935 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007936}
7937
7938binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
7939 *outPriority = mFlinger->getGpuContextPriority();
7940 return binder::Status::ok();
7941}
7942
7943binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
7944 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007945 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007946}
7947
7948binder::Status SurfaceComposerAIDL::addWindowInfosListener(
7949 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7950 status_t status;
7951 const int uid = IPCThreadState::self()->getCallingUid();
7952 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7953 status = mFlinger->addWindowInfosListener(windowInfosListener);
7954 } else {
7955 status = PERMISSION_DENIED;
7956 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007957 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007958}
7959
7960binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
7961 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7962 status_t status;
7963 const int uid = IPCThreadState::self()->getCallingUid();
7964 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7965 status = mFlinger->removeWindowInfosListener(windowInfosListener);
7966 } else {
7967 status = PERMISSION_DENIED;
7968 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007969 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007970}
7971
Huihong Luo07e72362022-02-14 14:26:04 -08007972status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
7973 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
7974 IPCThreadState* ipc = IPCThreadState::self();
7975 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
7976 ipc->getCallingUid());
7977 return PERMISSION_DENIED;
7978 }
7979 return OK;
7980}
7981
Huihong Luo37396db2022-02-15 10:43:00 -08007982status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
7983 IPCThreadState* ipc = IPCThreadState::self();
7984 const int pid = ipc->getCallingPid();
7985 const int uid = ipc->getCallingUid();
7986 if ((uid != AID_GRAPHICS) &&
7987 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
7988 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
7989 return PERMISSION_DENIED;
7990 }
7991 return OK;
7992}
7993
Huihong Luo02186fb2022-02-23 14:21:54 -08007994status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
7995 IPCThreadState* ipc = IPCThreadState::self();
7996 const int pid = ipc->getCallingPid();
7997 const int uid = ipc->getCallingUid();
7998 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
7999 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
8000 return PERMISSION_DENIED;
8001 }
8002 return OK;
8003}
8004
Dominik Laskowski9dab3432019-03-27 13:21:10 -07008005} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07008006
Mathias Agopian3f844832013-08-07 21:24:32 -07008007#if defined(__gl_h_)
8008#error "don't include gl/gl.h in this file"
8009#endif
8010
8011#if defined(__gl2_h_)
8012#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008013#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008014
8015// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008016#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"