blob: f7146c66cb89663dbbc39c32b8baa28b785e5b51 [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"
Marissa Wall61c58622018-07-18 10:12:20 -0700108#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200109#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200110#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800111#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700112#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700113#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700114#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100115#include "DisplayHardware/Hal.h"
Xiang Wang839fe5b2022-04-04 17:39:38 +0000116#include "DisplayHardware/PowerAdvisor.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700117#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200118#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800119#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700120#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700121#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800122#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700123#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700124#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400125#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800126#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500127#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200128#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800129#include "LayerVector.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800130#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800131#include "NativeWindowSurface.h"
132#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700133#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700134#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700135#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700136#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700137#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700138#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700139#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800140#include "StartPropertySetThread.h"
141#include "SurfaceFlingerProperties.h"
142#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800143#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200144#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500145#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800146
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500147#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500148#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
Alec Mourifcedb9c2022-04-11 20:02:17 +0000149#include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500150
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700151#undef NO_THREAD_SAFETY_ANALYSIS
152#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800153 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500154
Tianhao Yao67dd7122022-02-22 17:48:33 +0000155// To enable layer borders in the system, change the below flag to true.
156#undef DOES_CONTAIN_BORDER
157#define DOES_CONTAIN_BORDER false
158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700160
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700161using namespace std::chrono_literals;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700162using namespace std::string_literals;
163
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800164using namespace hardware::configstore;
165using namespace hardware::configstore::V1_0;
166using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800167
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800168using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
169using aidl::android::hardware::graphics::composer3::Capability;
170using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800171using CompositionStrategyPredictionState = android::compositionengine::impl::
172 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800173
Yiwei Zhang5434a782018-12-05 18:06:32 -0800174using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700175using gui::DisplayInfo;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800176using gui::GameMode;
Huihong Luo6fac5232021-11-22 16:05:23 -0800177using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500178using gui::IWindowInfosListener;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800179using gui::LayerMetadata;
chaviw98318de2021-05-19 16:45:23 -0500180using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800181using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700182using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700183using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800184using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700185using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900186
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800187using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
188
Peiyong Line9d809e2020-04-14 13:10:48 -0700189namespace hal = android::hardware::graphics::composer::hal;
190
Steven Thomasb02664d2017-07-26 18:48:28 -0700191namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700192
193#pragma clang diagnostic push
194#pragma clang diagnostic error "-Wswitch-enum"
195
196bool isWideColorMode(const ColorMode colorMode) {
197 switch (colorMode) {
198 case ColorMode::DISPLAY_P3:
199 case ColorMode::ADOBE_RGB:
200 case ColorMode::DCI_P3:
201 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700202 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700203 case ColorMode::BT2100_PQ:
204 case ColorMode::BT2100_HLG:
205 return true;
206 case ColorMode::NATIVE:
207 case ColorMode::STANDARD_BT601_625:
208 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
209 case ColorMode::STANDARD_BT601_525:
210 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
211 case ColorMode::STANDARD_BT709:
212 case ColorMode::SRGB:
213 return false;
214 }
215 return false;
216}
217
218#pragma clang diagnostic pop
219
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100220// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700221constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800222
223float getDensityFromProperty(const char* property, bool required) {
224 char value[PROPERTY_VALUE_MAX];
225 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
226 if (!density && required) {
227 ALOGE("%s must be defined as a build property", property);
228 return FALLBACK_DENSITY;
229 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700230 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800231}
232
Peiyong Lin9d846a52018-11-05 13:18:20 -0800233// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
234bool validateCompositionDataspace(Dataspace dataspace) {
235 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
236}
237
ramindani32cf0602022-03-02 02:30:29 +0000238std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700239 const auto displayIdleTimerMsKey = [displayId] {
240 std::stringstream ss;
241 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
242 return ss.str();
243 }();
244
ramindani32cf0602022-03-02 02:30:29 +0000245 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
246 if (displayIdleTimerMs > 0) {
247 return std::chrono::milliseconds(displayIdleTimerMs);
248 }
249
250 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
251 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
252 return std::chrono::milliseconds(millis);
253}
254
255bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700256 const auto displaySupportKernelIdleTimerKey = [displayId] {
257 std::stringstream ss;
258 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
259 return ss.str();
260 }();
261
Ady Abraham6d885932021-09-03 18:05:48 -0700262 const auto displaySupportKernelIdleTimer =
263 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000264 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700265}
266
Steven Thomasb02664d2017-07-26 18:48:28 -0700267} // namespace anonymous
268
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800269// ---------------------------------------------------------------------------
270
Mathias Agopian99b49842011-06-27 16:05:52 -0700271const String16 sHardwareTest("android.permission.HARDWARE_TEST");
272const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800273const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700274const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400275const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700276const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500277const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000278const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500279
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800280const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700281
Vishnu Nair4fb00ed2022-06-03 10:25:09 -0700282static const int MAX_TRACING_MEMORY = 1024 * 1024 * 1024; // 1GB
283
Mathias Agopian99b49842011-06-27 16:05:52 -0700284// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700285int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700286bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800287bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800288int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100289uint32_t SurfaceFlinger::maxGraphicsWidth;
290uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600291bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700292bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700293Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
294ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
295Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
296ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000297LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700298
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800299std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
300 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800301 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700302 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800303 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700304 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800305 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700306 return std::string("Enhanced");
307 default:
308 return std::string("Unknown ") +
309 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800310 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800311}
312
Hongwei Wang46213ea2020-12-04 17:17:31 -0800313bool callingThreadHasRotateSurfaceFlingerAccess() {
314 IPCThreadState* ipc = IPCThreadState::self();
315 const int pid = ipc->getCallingPid();
316 const int uid = ipc->getCallingUid();
317 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
318 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
319}
320
Leon Scroggins9a20f722021-12-28 14:43:12 +0000321bool callingThreadHasInternalSystemWindowAccess() {
322 IPCThreadState* ipc = IPCThreadState::self();
323 const int pid = ipc->getCallingPid();
324 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500325 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
326 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000327}
328
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700329SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
330 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800331 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000332 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700333 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800334 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800335 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700336 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700337 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700338 mTunnelModeEnabledReporter(sp<TunnelModeEnabledReporter>::make()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800339 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700340 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000341 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Patrick Williams641f7f22022-06-22 19:25:35 +0000342 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make()) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700343 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700344}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800345
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700346SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800347 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800348
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900349 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800350
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900351 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700352
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900353 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700354
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900355 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800356
Brian Lindahla13f2d52020-03-05 11:54:17 +0100357 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
358 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
359
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900360 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900361 mDefaultCompositionDataspace =
362 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700363 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
364 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900365 defaultCompositionDataspace = mDefaultCompositionDataspace;
366 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
367 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
368 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
369 wideColorGamutCompositionPixelFormat =
370 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700371
Yichi Chenda901bf2019-06-28 14:58:27 +0800372 mColorSpaceAgnosticDataspace =
373 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
374
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700375 mLayerCachingEnabled = [] {
376 const bool enable =
377 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
378 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
379 }();
380
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900381 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800382
Sundong Ahn85131bd2019-02-18 15:51:53 +0900383 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800384
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385 // debugging stuff...
386 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700387
Mathias Agopianb4b17302013-03-20 18:36:41 -0700388 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700389 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700390
Alec Mouri5f487d42020-02-06 09:26:19 -0800391 property_get("ro.build.type", value, "user");
392 mIsUserBuild = strcmp(value, "user") == 0;
393
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700394 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000395
396 // DDMS debugging deprecated (b/120782499)
397 property_get("debug.sf.ddms", value, "0");
398 int debugDdms = atoi(value);
399 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700400
Ady Abrahamadb9a992019-09-19 21:21:55 +0000401 property_get("debug.sf.enable_gl_backpressure", value, "0");
402 mPropagateBackpressureClientComposition = atoi(value);
403 ALOGI_IF(mPropagateBackpressureClientComposition,
404 "Enabling backpressure propagation for Client Composition");
405
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800406 property_get("ro.surface_flinger.supports_background_blur", value, "0");
407 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700408 mSupportsBlur = supportsBlurs;
409 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800410 property_get("ro.sf.blurs_are_expensive", value, "0");
411 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800412
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700413 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700414 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
415 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800416 mGraphicBufferProducerListSizeLogThreshold =
417 std::max(static_cast<int>(0.95 *
418 static_cast<double>(mMaxGraphicBufferProducerListSize)),
419 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700420
Dan Stozaec460082018-12-17 15:35:09 -0800421 property_get("debug.sf.luma_sampling", value, "1");
422 mLumaSampling = atoi(value);
423
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800424 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800425 mDisableClientCompositionCache = atoi(value);
426
Vishnu Nair3539d812022-02-26 09:20:17 -0800427 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800428 mPredictCompositionStrategy = atoi(value);
429
Alec Mouridda07d92022-04-25 22:39:25 +0000430 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
431 mTreat170mAsSrgb = atoi(value);
432
Romain Guy11d63f42017-07-20 12:47:14 -0700433 // We should be reading 'persist.sys.sf.color_saturation' here
434 // but since /data may be encrypted, we need to wait until after vold
435 // comes online to attempt to read the property. The property is
436 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800437
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700438 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800439 // Without the override SurfaceFlinger cannot connect to HIDL
440 // services that are not listed in the manifests. Considered
441 // deriving the setting from the set service name, but it
442 // would be brittle if the name that's not 'default' is used
443 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700444 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000445 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800446 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800447
Ady Abraham29d0da32020-07-16 18:39:33 -0700448 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400449
Dominik Laskowski46471e62022-01-14 15:34:03 -0800450 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
451 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800452 }
John Reck49d9ad32022-02-23 19:03:31 -0500453
454 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
Matt Buckley50c44062022-01-17 20:48:10 +0000455
456 // Power hint session mode, representing which hint(s) to send: early, late, or both)
457 mPowerHintSessionMode =
458 {.late = base::GetBoolProperty("debug.sf.send_late_power_session_hint"s, true),
Matt Buckley58a36452022-07-20 20:53:32 +0000459 .early = base::GetBoolProperty("debug.sf.send_early_power_session_hint"s, false)};
ramindani4d48f902021-09-20 21:07:45 +0000460}
461
462LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000463 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800464 return LatchUnsignaledConfig::AutoSingleLayer;
465 }
466
Ady Abrahamfb67be12022-08-10 10:46:22 -0700467 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
468 return LatchUnsignaledConfig::Always;
469 }
470
Ady Abraham9dada822022-02-03 10:26:59 -0800471 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800472}
473
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700474SurfaceFlinger::~SurfaceFlinger() = default;
475
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700476void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800477 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700478 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800479
Dominik Laskowski756b7892021-08-04 12:53:59 -0700480 // Sever the link to inputflinger since it's gone as well.
Ady Abrahamd11bade2022-08-01 16:18:03 -0700481 static_cast<void>(mScheduler->schedule(
Ady Abraham81015532022-08-02 16:27:53 +0000482 [this] { mInputFlinger.clear(); }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800483
Andy McFadden13a082e2012-08-24 10:16:42 -0700484 // restore initial conditions (default device unblank, etc)
485 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800486
487 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700488 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800489}
490
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700491void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700492 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800493}
494
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700495sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700496 // onTransact already checks for some permissions, but adding an additional check here.
497 // This is to ensure that only system and graphics can request to create a secure
498 // display. Secure displays can show secure content so we add an additional restriction on it.
499 const int uid = IPCThreadState::self()->getCallingUid();
500 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
501 ALOGE("Only privileged processes can create a secure display");
502 return nullptr;
503 }
504
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505 class DisplayToken : public BBinder {
506 sp<SurfaceFlinger> flinger;
507 virtual ~DisplayToken() {
508 // no more references, this display must be terminated
509 Mutex::Autolock _l(flinger->mStateLock);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700510 flinger->mCurrentState.displays.removeItem(wp<IBinder>::fromExisting(this));
Mathias Agopiane57f2922012-08-09 16:29:12 -0700511 flinger->setTransactionFlags(eDisplayTransactionNeeded);
512 }
513 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700514 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700515 : flinger(flinger) {
516 }
517 };
518
Ady Abrahamd11bade2022-08-01 16:18:03 -0700519 sp<BBinder> token = sp<DisplayToken>::make(sp<SurfaceFlinger>::fromExisting(this));
Mathias Agopiane57f2922012-08-09 16:29:12 -0700520
521 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700522 // Display ID is assigned when virtual display is allocated by HWC.
523 DisplayDeviceState state;
524 state.isSecure = secure;
525 state.displayName = displayName;
526 mCurrentState.displays.add(token, state);
527 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700528 return token;
529}
530
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700531void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700532 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700533
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700534 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700535 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800536 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700537 return;
538 }
539
Dominik Laskowski075d3172018-05-24 15:50:06 -0700540 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700541 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800542 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700543 return;
544 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700545 mInterceptor->saveDisplayDeletion(state.sequenceId);
546 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700547 setTransactionFlags(eDisplayTransactionNeeded);
548}
549
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800550void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
551 auto& generator = mVirtualDisplayIdGenerators.hal;
552 if (!generator && enable) {
553 ALOGI("Enabling HAL virtual displays");
554 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
555 } else if (generator && !enable) {
556 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
557 generator.reset();
558 }
559}
560
Dominik Laskowski263eec42021-07-21 23:13:24 -0700561VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
562 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800563 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
564 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700565 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800566 return *id;
567 }
568
569 generator->releaseId(*id);
570 } else {
571 ALOGW("%s: Exhausted HAL virtual displays", __func__);
572 }
573
574 ALOGW("%s: Falling back to GPU virtual display", __func__);
575 }
576
577 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
578 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
579 return *id;
580}
581
582void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
583 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
584 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
585 generator->releaseId(*id);
586 }
587 return;
588 }
589
590 const auto id = GpuVirtualDisplayId::tryCast(displayId);
591 LOG_ALWAYS_FATAL_IF(!id);
592 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
593}
594
Ady Abrahamed3290f2021-05-17 15:12:14 -0700595std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800596 std::vector<PhysicalDisplayId> displayIds;
597 displayIds.reserve(mPhysicalDisplayTokens.size());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700598
Dominik Laskowski3c363242022-04-07 10:44:12 -0700599 const auto defaultDisplayId = getDefaultDisplayDeviceLocked()->getPhysicalId();
Ady Abraham2a0066d2021-07-15 20:16:58 -0700600 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800601
602 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700603 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200604 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800605 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700606 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700607
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800608 return displayIds;
609}
610
611sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
612 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200613 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700614}
615
Ady Abraham37965d42018-11-01 13:43:32 -0700616status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
617 if (!outGetColorManagement) {
618 return BAD_VALUE;
619 }
620 *outGetColorManagement = useColorManagement;
621 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700622}
623
Lloyd Pique441d5042018-10-18 16:49:51 -0700624HWComposer& SurfaceFlinger::getHwComposer() const {
625 return mCompositionEngine->getHwComposer();
626}
627
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700628renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
629 return mCompositionEngine->getRenderEngine();
630}
631
Lloyd Pique70d91362018-10-18 16:02:55 -0700632compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
633 return *mCompositionEngine.get();
634}
635
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100636void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700637 if (mBootFinished == true) {
638 ALOGE("Extra call to bootFinished");
639 return;
640 }
641 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700642 if (mStartPropertySetThread->join() != NO_ERROR) {
643 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800644 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700645
646 if (mRenderEnginePrimeCacheFuture.valid()) {
647 mRenderEnginePrimeCacheFuture.get();
648 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800649 const nsecs_t now = systemTime();
650 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000651 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700652
Mikael Pessa90092f42019-08-26 17:22:04 -0700653 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700654 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700655 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700656
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700657 // wait patiently for the window manager death
658 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700659 mWindowManager = defaultServiceManager()->getService(name);
660 if (mWindowManager != 0) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700661 mWindowManager->linkToDeath(sp<IBinder::DeathRecipient>::fromExisting(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700662 }
663
664 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700665 // formerly we would just kill the process, but we now ask it to exit so it
666 // can choose where to stop the animation.
667 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700668
669 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
670 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
671 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700672
Denis Hsue70cc6c2020-06-17 10:17:30 +0800673 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
674
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000675 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800676 if (input == nullptr) {
677 ALOGE("Failed to link to input service");
678 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700679 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800680 }
681
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800682 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000683 mPowerAdvisor->onBootFinished();
Matt Buckley618c43f2022-08-12 18:09:48 +0000684 const bool powerHintEnabled = mFlagManager.use_adpf_cpu_hint();
685 mPowerAdvisor->enablePowerHint(powerHintEnabled);
686 const bool powerHintUsed = mPowerAdvisor->usePowerHintSession();
687 ALOGD("Power hint is %s",
688 powerHintUsed ? "supported" : (powerHintEnabled ? "unsupported" : "disabled"));
689 if (powerHintUsed) {
690 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
691 std::vector<int32_t> tidList;
692 tidList.emplace_back(gettid());
693 if (renderEngineTid.has_value()) {
694 tidList.emplace_back(*renderEngineTid);
695 }
696 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
697 ALOGW("Cannot start power hint session");
Xiang Wange12b4fa2022-03-25 23:48:40 +0000698 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000699 }
700
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800701 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800702
Ady Abraham8a82ba62020-01-17 12:43:17 -0800703 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800704 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800705 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800706 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800707}
708
Dan Stoza436ccf32018-06-21 12:10:12 -0700709uint32_t SurfaceFlinger::getNewTexture() {
710 {
711 std::lock_guard lock(mTexturePoolMutex);
712 if (!mTexturePool.empty()) {
713 uint32_t name = mTexturePool.back();
714 mTexturePool.pop_back();
715 ATRACE_INT("TexturePoolSize", mTexturePool.size());
716 return name;
717 }
718
719 // The pool was too small, so increase it for the future
720 ++mTexturePoolSize;
721 }
722
723 // The pool was empty, so we need to get a new texture name directly using a
724 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700725 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700726 uint32_t name = 0;
727 getRenderEngine().genTextures(1, &name);
728 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700729 };
730 if (std::this_thread::get_id() == mMainThreadId) {
731 return genTextures();
732 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700733 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700734 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700735}
736
Mathias Agopian3f844832013-08-07 21:24:32 -0700737void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700738 std::lock_guard lock(mTexturePoolMutex);
739 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
740 // to actually delete this or not based on mTexturePoolSize
741 mTexturePool.push_back(texture);
742 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700743}
744
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500745static std::optional<renderengine::RenderEngine::RenderEngineType>
746chooseRenderEngineTypeViaSysProp() {
747 char prop[PROPERTY_VALUE_MAX];
748 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
749
750 if (strcmp(prop, "gles") == 0) {
751 return renderengine::RenderEngine::RenderEngineType::GLES;
752 } else if (strcmp(prop, "threaded") == 0) {
753 return renderengine::RenderEngine::RenderEngineType::THREADED;
754 } else if (strcmp(prop, "skiagl") == 0) {
755 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
756 } else if (strcmp(prop, "skiaglthreaded") == 0) {
757 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
758 } else {
759 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
760 return {};
761 }
762}
763
Wei Wangf9b05ee2017-07-19 20:59:39 -0700764// Do not call property_set on main thread which will be blocked by init
765// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700766void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700767 ALOGI( "SurfaceFlinger's main thread ready to run. "
768 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700769 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800770
Steven Thomasb02664d2017-07-26 18:48:28 -0700771 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700772 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800773 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500774 auto builder = renderengine::RenderEngineCreationArgs::Builder()
775 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
776 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
777 .setUseColorManagerment(useColorManagement)
778 .setEnableProtectedContext(enable_protected_contents(false))
779 .setPrecacheToneMapperShaderOnly(false)
780 .setSupportsBackgroundBlur(mSupportsBlur)
781 .setContextPriority(
782 useContextPriority
783 ? renderengine::RenderEngine::ContextPriority::REALTIME
784 : renderengine::RenderEngine::ContextPriority::MEDIUM);
785 if (auto type = chooseRenderEngineTypeViaSysProp()) {
786 builder.setRenderEngineType(type.value());
787 }
788 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700789 mMaxRenderTargetSize =
790 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700791
792 // Set SF main policy after initializing RenderEngine which has its own policy.
793 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
794 ALOGW("Failed to set main task profile");
795 }
796
Alec Mourie4034bb2019-11-19 12:45:54 -0800797 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700798 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800799 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000800 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800801
Ady Abraham9dada822022-02-03 10:26:59 -0800802 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
803
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800804 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
805 enableHalVirtualDisplays(true);
806 }
807
Lloyd Piqueba04e622017-12-14 17:11:26 -0800808 // Process any initial hotplug and resulting display changes.
809 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700810 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700811 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200812 const auto displayId = display->getPhysicalId();
813 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700814 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800815
Mathias Agopian92a979a2012-08-02 18:32:23 -0700816 // initialize our drawing state
817 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700818
Andy McFadden13a082e2012-08-24 10:16:42 -0700819 // set initial conditions (e.g. unblank default device)
820 initializeDisplays();
821
Xiang Wang839fe5b2022-04-04 17:39:38 +0000822 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700823
Steven Thomas137d4bc2019-07-25 16:55:14 -0700824 char primeShaderCache[PROPERTY_VALUE_MAX];
825 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
826 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700827 if (setSchedFifo(false) != NO_ERROR) {
828 ALOGW("Can't set SCHED_OTHER for primeCache");
829 }
830
831 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
832
833 if (setSchedFifo(true) != NO_ERROR) {
834 ALOGW("Can't set SCHED_OTHER for primeCache");
835 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700836 }
Dan Stoza4e637772016-07-28 13:31:51 -0700837
Ady Abrahamed3290f2021-05-17 15:12:14 -0700838 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400839
Wei Wangf9b05ee2017-07-19 20:59:39 -0700840 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700841
842 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800843 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700844 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700845
846 if (mStartPropertySetThread->Start() != NO_ERROR) {
847 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800848 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800849
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700851}
852
Romain Guy11d63f42017-07-20 12:47:14 -0700853void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700854 Mutex::Autolock _l(mStateLock);
855
Romain Guy11d63f42017-07-20 12:47:14 -0700856 char value[PROPERTY_VALUE_MAX];
857
858 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800859 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700860 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800861 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100862
863 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700864 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800865
866 property_get("persist.sys.sf.color_mode", value, "0");
867 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700868}
869
Mathias Agopiana67e4182012-06-19 17:26:12 -0700870void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800871 // Start boot animation service by setting a property mailbox
872 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700873 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800874 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700875 if (mStartPropertySetThread->join() != NO_ERROR) {
876 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800877 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700878}
879
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800880// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800881
Brian Anderson6b376712017-04-04 10:51:39 -0700882status_t SurfaceFlinger::getSupportedFrameTimestamps(
883 std::vector<FrameEvent>* outSupported) const {
884 *outSupported = {
885 FrameEvent::REQUESTED_PRESENT,
886 FrameEvent::ACQUIRE,
887 FrameEvent::LATCH,
888 FrameEvent::FIRST_REFRESH_START,
889 FrameEvent::LAST_REFRESH_START,
890 FrameEvent::GPU_COMPOSITION_DONE,
891 FrameEvent::DEQUEUE_READY,
892 FrameEvent::RELEASE,
893 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800894
895 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
896
Ady Abrahamde549d42022-01-26 19:19:17 -0800897 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700898 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
899 }
900 return NO_ERROR;
901}
902
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800903status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
904 if (!displayToken || !state) {
905 return BAD_VALUE;
906 }
907
908 Mutex::Autolock lock(mStateLock);
909
910 const auto display = getDisplayDeviceLocked(displayToken);
911 if (!display) {
912 return NAME_NOT_FOUND;
913 }
914
915 state->layerStack = display->getLayerStack();
916 state->orientation = display->getOrientation();
917
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200918 const Rect layerStackRect = display->getLayerStackSpaceRect();
919 state->layerStackSpaceRect =
920 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800921
922 return NO_ERROR;
923}
924
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100925status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
926 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800927 if (!displayToken || !info) {
928 return BAD_VALUE;
929 }
930
931 Mutex::Autolock lock(mStateLock);
932
933 const auto display = getDisplayDeviceLocked(displayToken);
934 if (!display) {
935 return NAME_NOT_FOUND;
936 }
937
Dominik Laskowski55c85402020-01-21 16:25:47 -0800938 if (const auto connectionType = display->getConnectionType())
939 info->connectionType = *connectionType;
940 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800941 return INVALID_OPERATION;
942 }
943
944 if (mEmulatedDisplayDensity) {
945 info->density = mEmulatedDisplayDensity;
946 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100947 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800948 ? mInternalDisplayDensity
949 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800950 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700951 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800952
953 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200954 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000955 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800956
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800957 return NO_ERROR;
958}
959
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100960status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
961 ui::DynamicDisplayInfo* info) {
962 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700963 return BAD_VALUE;
964 }
965
Dominik Laskowski22488f62019-03-28 09:53:04 -0700966 Mutex::Autolock lock(mStateLock);
967
Marin Shalamanov5801c942020-12-17 17:00:13 +0100968 const auto display = getDisplayDeviceLocked(displayToken);
969 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700970 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700971 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700972
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700973 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
974 if (!displayId) {
975 return INVALID_OPERATION;
976 }
977
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800978 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700979
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100980 const auto& supportedModes = display->getSupportedModes();
981 info->supportedDisplayModes.clear();
982 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800983
984 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100985 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800986 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700987
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800988 auto [width, height] = mode->getResolution();
989 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700990
ramindani06e518e2022-03-14 18:47:53 +0000991 if (const auto physicalOrientation = display->getPhysicalOrientation();
992 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800993 std::swap(width, height);
994 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700995 }
996
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100997 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800998
Huan Songf7eeb102022-03-28 11:02:38 -0700999 outMode.xDpi = xDpi;
1000 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001001
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001002 const nsecs_t period = mode->getVsyncPeriod();
1003 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001004
Ady Abraham8287e852020-08-12 14:44:58 -07001005 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001006 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001007 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1008 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1009 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001010
Andy McFadden91b2ca82014-06-13 14:04:23 -07001011 // This is how far in advance a buffer must be queued for
1012 // presentation at a given time. If you want a buffer to appear
1013 // on the screen at time N, you must submit the buffer before
1014 // (N - presentationDeadline).
1015 //
1016 // Normally it's one full refresh period (to give SF a chance to
1017 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001018 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001019 // composer or panel must be accounted for here.
1020 //
1021 // We add an additional 1ms to allow for processing time and
1022 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001023 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001024
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001025 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001026 }
1027
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001028 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001029 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001030 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001031
Marin Shalamanovb173f752021-02-16 19:38:36 +01001032 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001033 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001034 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001035 info->gameContentTypeSupported =
1036 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001037
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001038 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001039
1040 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001041 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1042 if (const auto modeId = display->translateModeId(*hwcId)) {
1043 info->preferredBootDisplayMode = modeId->value();
1044 }
1045 }
1046 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001047
Dan Stoza7f7da322014-05-02 15:26:25 -07001048 return NO_ERROR;
1049}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001050
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001051status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* outStats) {
1052 if (!outStats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001053 return BAD_VALUE;
1054 }
1055
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001056 const auto& schedule = mScheduler->getVsyncSchedule();
1057 outStats->vsyncTime = schedule.vsyncDeadlineAfter(scheduler::SchedulerClock::now()).ns();
1058 outStats->vsyncPeriod = schedule.period().ns();
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001059 return NO_ERROR;
1060}
1061
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001062void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001063 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001064
1065 if (!info.mode) {
1066 ALOGW("requested display mode is null");
1067 return;
1068 }
1069 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001070 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001071 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001072 return;
1073 }
1074
Ady Abraham690f4612021-07-01 23:24:03 -07001075 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001076 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001077
Alec Mouri754c98a2019-03-18 18:53:42 -07001078 // Start receiving vsync samples now, so that we can detect a period
1079 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001080 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001081 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001082 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001083 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001084
Ady Abraham690f4612021-07-01 23:24:03 -07001085 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001086 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001087 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001088}
1089
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001090status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001091 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001092
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001093 if (!displayToken) {
1094 return BAD_VALUE;
1095 }
Ady Abraham838de062019-02-04 10:24:03 -08001096
Dominik Laskowski756b7892021-08-04 12:53:59 -07001097 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001098 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001099 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001100 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001101 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001102 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001103 }
1104
1105 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001106 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001107 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001108 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001109
1110 const auto mode = display->getMode(DisplayModeId{modeId});
1111 if (!mode) {
1112 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1113 return BAD_VALUE;
1114 }
1115
1116 const auto fps = mode->getFps();
1117 // Keep the old switching type.
1118 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001119 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001120 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1121 allowGroupSwitching,
1122 {fps, fps}};
1123 constexpr bool kOverridePolicy = false;
1124
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001125 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001126 });
1127
1128 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001129}
1130
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001131void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001132 ATRACE_CALL();
1133
Dominik Laskowski22488f62019-03-28 09:53:04 -07001134 const auto display = getDefaultDisplayDeviceLocked();
1135 if (!display) {
1136 return;
1137 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001138
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001139 const auto upcomingModeInfo =
1140 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1141
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001142 if (!upcomingModeInfo.mode) {
1143 // There is no pending mode change. This can happen if the active
1144 // display changed and the mode change happened on a different display.
1145 return;
1146 }
1147
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001148 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001149 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1150 // We need to generate new sequenceId in order to recreate the display (and this
1151 // way the framebuffer).
1152 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001153 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001154 processDisplayChangesLocked();
1155
1156 // processDisplayChangesLocked will update all necessary components so we're done here.
1157 return;
1158 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001159
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001160 // We just created this display so we can call even if we are not on the main thread.
1161 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001162 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001163
Ady Abraham690f4612021-07-01 23:24:03 -07001164 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001165 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001166 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001167
Dominik Laskowski068173d2021-08-11 17:22:59 -07001168 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001169 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001170 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001171}
1172
Ady Abraham690f4612021-07-01 23:24:03 -07001173void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1174 display->clearDesiredActiveModeState();
1175 if (isDisplayActiveLocked(display)) {
1176 mScheduler->setModeChangePending(false);
1177 }
Ady Abraham53852a52019-05-28 18:07:44 -07001178}
1179
Ady Abraham690f4612021-07-01 23:24:03 -07001180void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1181 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1182 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001183 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001184 updatePhaseConfiguration(refreshRate);
1185}
1186
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001187void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001188 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001189
Marin Shalamanovdd594312021-11-09 16:37:37 +01001190 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1191
Ady Abraham690f4612021-07-01 23:24:03 -07001192 for (const auto& iter : mDisplays) {
1193 const auto& display = iter.second;
1194 if (!display || !display->isInternal()) {
1195 continue;
1196 }
1197
1198 // Store the local variable to release the lock.
1199 const auto desiredActiveMode = display->getDesiredActiveMode();
1200 if (!desiredActiveMode) {
1201 // No desired active mode pending to be applied
1202 continue;
1203 }
1204
1205 if (!isDisplayActiveLocked(display)) {
1206 // display is no longer the active display, so abort the mode change
1207 clearDesiredActiveModeState(display);
1208 continue;
1209 }
1210
1211 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1212 if (!desiredMode) {
1213 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1214 desiredActiveMode->mode->getId().value());
1215 clearDesiredActiveModeState(display);
1216 continue;
1217 }
1218
1219 const auto refreshRate = desiredMode->getFps();
1220 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1221 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1222 to_string(display->getId()).c_str());
1223
1224 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001225 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001226 desiredActiveModeChangeDone(display);
1227 continue;
1228 }
1229
1230 // Desired active mode was set, it is different than the mode currently in use, however
1231 // allowed modes might have changed by the time we process the refresh.
1232 // Make sure the desired mode is still allowed
1233 const auto displayModeAllowed =
1234 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1235 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001236 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001237 continue;
1238 }
1239
1240 // TODO(b/142753666) use constrains
1241 hal::VsyncPeriodChangeConstraints constraints;
1242 constraints.desiredTimeNanos = systemTime();
1243 constraints.seamlessRequired = false;
1244 hal::VsyncPeriodChangeTimeline outTimeline;
1245
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001246 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1247 display->initiateModeChange(*desiredActiveMode,
1248 constraints, &outTimeline));
1249
Ady Abraham690f4612021-07-01 23:24:03 -07001250 if (status != NO_ERROR) {
1251 // initiateModeChange may fail if a hotplug event is just about
1252 // to be sent. We just log the error in this case.
1253 ALOGW("initiateModeChange failed: %d", status);
1254 continue;
1255 }
1256 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1257
Marin Shalamanovdd594312021-11-09 16:37:37 +01001258 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001259 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001260 mSetActiveModePending = true;
1261 } else {
1262 // Updating the internal state should be done outside the loop,
1263 // because it can recreate a DisplayDevice and modify mDisplays
1264 // which will invalidate the iterator.
1265 displayToUpdateImmediately = display->getPhysicalId();
1266 }
1267 }
1268
1269 if (displayToUpdateImmediately) {
1270 updateInternalStateWithChangedMode();
1271
1272 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1273 const auto desiredActiveMode = display->getDesiredActiveMode();
1274 if (desiredActiveMode &&
1275 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1276 desiredActiveModeChangeDone(display);
1277 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001278 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001279}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001280
Alec Mouridea1ac52021-06-23 18:12:18 -07001281void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001282 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001283 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001284 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001285 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001286 for (const auto& [_, display] : mDisplays) {
1287 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001288 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001289 }
1290 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001291 });
1292
1293 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001294}
1295
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001296std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1297 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001298
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001299 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001300 // filter out all wide color modes. The typical reason why this happens is that the
1301 // hardware is not good enough to support GPU composition of wide color, and thus the
1302 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001303 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1304 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001305 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1306 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001307 }
Michael Wright28f24d02016-07-12 13:30:53 -07001308
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001309 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001310}
1311
Daniel Solomon42d04562019-01-20 21:03:19 -08001312status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001313 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001314 if (!displayToken) {
1315 return BAD_VALUE;
1316 }
1317
Dominik Laskowski3c363242022-04-07 10:44:12 -07001318 Mutex::Autolock lock(mStateLock);
1319
1320 const auto display = getDisplayDeviceLocked(displayToken);
1321 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001322 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001323 }
1324
Dominik Laskowski3c363242022-04-07 10:44:12 -07001325 const auto connectionType = display->getConnectionType();
1326 if (connectionType != ui::DisplayConnectionType::Internal) {
1327 return INVALID_OPERATION;
1328 }
1329
1330 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1331 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001332 return NO_ERROR;
1333}
1334
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001335status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001336 if (!displayToken) {
1337 return BAD_VALUE;
1338 }
1339
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001340 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001341 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001342 if (!display) {
1343 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1344 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001345 return NAME_NOT_FOUND;
1346 }
1347
1348 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001349 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1350 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001351 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001352 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001353
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001354 const auto modes = getDisplayColorModes(*display);
1355 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1356
1357 if (mode < ColorMode::NATIVE || !exists) {
1358 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1359 decodeColorMode(mode).c_str(), mode, displayToken.get());
1360 return BAD_VALUE;
1361 }
1362
1363 display->getCompositionDisplay()->setColorProfile(
1364 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1365
1366 return NO_ERROR;
1367 });
1368
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001369 // TODO(b/195698395): Propagate error.
1370 future.wait();
1371 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001372}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001373
Kriti Dang7defaf32021-11-15 11:55:43 +01001374status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001375 auto future = mScheduler->schedule(
1376 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1377
1378 *outSupport = future.get();
1379 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001380}
1381
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001382status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1383 ui::DisplayModeId modeId) {
1384 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001385 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001386 const auto display = getDisplayDeviceLocked(displayToken);
1387 if (!display) {
1388 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1389 return NAME_NOT_FOUND;
1390 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001391
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001392 if (display->isVirtual()) {
1393 ALOGE("%s: Invalid operation on virtual display", whence);
1394 return INVALID_OPERATION;
1395 }
1396
1397 const auto displayId = display->getPhysicalId();
1398 const auto mode = display->getMode(DisplayModeId{modeId});
1399 if (!mode) {
1400 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1401 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001402 return BAD_VALUE;
1403 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001404
1405 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001406 });
1407 return future.get();
1408}
1409
1410status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001411 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001412 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001413 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1414 return getHwComposer().clearBootDisplayMode(*displayId);
1415 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001416 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001417 return BAD_VALUE;
1418 }
1419 });
1420 return future.get();
1421}
1422
Galia Peycheva5492cb52019-10-30 14:13:16 +01001423void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001424 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001425 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001426 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1427 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1428 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001429 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001430 }
1431 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001432}
1433
Galia Peycheva5492cb52019-10-30 14:13:16 +01001434void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001435 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001436 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001437 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001438 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001439 getHwComposer().setContentType(*displayId, type);
1440 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001441 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001442 }
1443 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001444}
1445
Kriti Dang49ad4132021-01-08 11:49:56 +01001446status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1447 const std::vector<ui::Hdr>& hdrTypes) {
1448 Mutex::Autolock lock(mStateLock);
1449
1450 auto display = getDisplayDeviceLocked(displayToken);
1451 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001452 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001453 return NAME_NOT_FOUND;
1454 }
1455
1456 display->overrideHdrTypes(hdrTypes);
1457 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1458 return NO_ERROR;
1459}
1460
Tej Singhe2751772021-04-06 22:05:29 -07001461status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1462 *success = mTimeStats->onPullAtom(atomId, pulledData);
1463 return NO_ERROR;
1464}
1465
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001466status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1467 ui::PixelFormat* outFormat,
1468 ui::Dataspace* outDataspace,
1469 uint8_t* outComponentMask) const {
1470 if (!outFormat || !outDataspace || !outComponentMask) {
1471 return BAD_VALUE;
1472 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001473
1474 Mutex::Autolock lock(mStateLock);
1475
1476 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1477 if (!displayId) {
1478 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001479 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001480
1481 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001482 outDataspace, outComponentMask);
1483}
1484
Kevin DuBois74e53772018-11-19 10:52:38 -08001485status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1486 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001487 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001488 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001489 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001490 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1491 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1492 componentMask, maxFrames);
1493 } else {
1494 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1495 return NAME_NOT_FOUND;
1496 }
1497 });
1498
1499 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001500}
1501
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001502status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1503 uint64_t maxFrames, uint64_t timestamp,
1504 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001505 Mutex::Autolock lock(mStateLock);
1506
1507 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1508 if (!displayId) {
1509 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001510 }
1511
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001512 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001513}
1514
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001515status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1516 if (!outSupported) {
1517 return BAD_VALUE;
1518 }
1519 *outSupported = getRenderEngine().supportsProtectedContent();
1520 return NO_ERROR;
1521}
1522
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001523status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1524 bool* outIsWideColorDisplay) const {
1525 if (!displayToken || !outIsWideColorDisplay) {
1526 return BAD_VALUE;
1527 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001528
1529 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001530 const auto display = getDisplayDeviceLocked(displayToken);
1531 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001532 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001533 }
Peiyong Linff84a152019-05-17 18:36:19 -07001534
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001535 *outIsWideColorDisplay =
1536 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001537 return NO_ERROR;
1538}
1539
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001540status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001541 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001542 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001543
Dominik Laskowski6505f792019-09-18 11:10:05 -07001544 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001545 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001546 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001547 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001548
Dominik Laskowski756b7892021-08-04 12:53:59 -07001549 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001550 return NO_ERROR;
1551}
1552
1553status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001554 Mutex::Autolock lock(mStateLock);
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001555 const nsecs_t expectedPresentTime = calculateExpectedPresentTime(TimePoint::fromNs(when)).ns();
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001556 const nsecs_t deadlineTimestamp = expectedPresentTime;
1557 return mScheduler->injectVSync(when, expectedPresentTime, deadlineTimestamp) ? NO_ERROR
1558 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001559}
1560
Huihong Luo05539a12022-02-23 10:29:40 -08001561status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001562 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001563 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001564 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001565 mDrawingState.traverseInZOrder([&](Layer* layer) {
1566 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1567 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001568 });
1569
1570 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001571 return NO_ERROR;
1572}
1573
Peiyong Linc6780972018-10-28 15:24:08 -07001574status_t SurfaceFlinger::getCompositionPreference(
1575 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1576 Dataspace* outWideColorGamutDataspace,
1577 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001578 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001579 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001580 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001581 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001582 return NO_ERROR;
1583}
1584
Dan Stozaec460082018-12-17 15:35:09 -08001585status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1586 const sp<IBinder>& stopLayerHandle,
1587 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001588 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001589 return BAD_VALUE;
1590 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001591
1592 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1593 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001594 return NO_ERROR;
1595}
1596
Dan Stozaec460082018-12-17 15:35:09 -08001597status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001598 if (!listener) {
1599 return BAD_VALUE;
1600 }
Dan Stozaec460082018-12-17 15:35:09 -08001601 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001602 return NO_ERROR;
1603}
Dan Gittik57e63c52019-01-18 16:37:54 +00001604
Alec Mouria9a68a62021-03-04 19:14:50 -08001605status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001606 if (!listener) {
1607 return BAD_VALUE;
1608 }
1609
Alec Mouria9a68a62021-03-04 19:14:50 -08001610 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001611 return NO_ERROR;
1612}
1613
1614status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1615 if (!listener) {
1616 return BAD_VALUE;
1617 }
1618 mFpsReporter->removeListener(listener);
1619 return NO_ERROR;
1620}
1621
Galia Peycheva8f04b302021-04-27 13:25:38 +02001622status_t SurfaceFlinger::addTunnelModeEnabledListener(
1623 const sp<gui::ITunnelModeEnabledListener>& listener) {
1624 if (!listener) {
1625 return BAD_VALUE;
1626 }
1627
1628 mTunnelModeEnabledReporter->addListener(listener);
1629 return NO_ERROR;
1630}
1631
1632status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1633 const sp<gui::ITunnelModeEnabledListener>& listener) {
1634 if (!listener) {
1635 return BAD_VALUE;
1636 }
1637
1638 mTunnelModeEnabledReporter->removeListener(listener);
1639 return NO_ERROR;
1640}
1641
Dan Gittik57e63c52019-01-18 16:37:54 +00001642status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1643 bool* outSupport) const {
1644 if (!displayToken || !outSupport) {
1645 return BAD_VALUE;
1646 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001647
1648 Mutex::Autolock lock(mStateLock);
1649
Dan Gittik57e63c52019-01-18 16:37:54 +00001650 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1651 if (!displayId) {
1652 return NAME_NOT_FOUND;
1653 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001654 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001655 return NO_ERROR;
1656}
1657
Alec Mouricdf16792021-12-10 13:16:06 -08001658bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1659 bool hasHdrLayers = false;
1660 mDrawingState.traverse([&,
1661 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1662 hasHdrLayers |= (layer->isVisible() &&
1663 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1664 isHdrDataspace(layer->getDataSpace()));
1665 });
1666 return hasHdrLayers;
1667}
1668
John Reck22be6962021-03-10 12:59:54 -05001669status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1670 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001671 if (!displayToken) {
1672 return BAD_VALUE;
1673 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001674
Dominik Laskowski756b7892021-08-04 12:53:59 -07001675 const char* const whence = __func__;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001676 return ftl::Future(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001677 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001678 const bool supportsDisplayBrightnessCommand =
1679 getHwComposer().getComposer()->isSupported(
1680 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1681 // If we support applying display brightness as a command, then we also support
1682 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001683 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001684 auto compositionDisplay = display->getCompositionDisplay();
1685 float currentDimmingRatio =
1686 compositionDisplay->editState().sdrWhitePointNits /
1687 compositionDisplay->editState().displayBrightnessNits;
1688 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1689 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001690 FTL_FAKE_GUARD(kMainThreadContext,
1691 display->stageBrightness(brightness.displayBrightness));
1692
Alec Mouri6da0e272022-02-07 12:45:57 -08001693 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1694 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001695 scheduleComposite(FrameHint::kNone);
1696 } else {
1697 scheduleCommit(FrameHint::kNone);
1698 }
1699 return ftl::yield<status_t>(OK);
1700 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001701 return getHwComposer()
1702 .setDisplayBrightness(display->getPhysicalId(),
1703 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001704 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001705 Hwc2::Composer::DisplayBrightnessOptions{
1706 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001707 }
Alec Mouricdf16792021-12-10 13:16:06 -08001708
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001709 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001710 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001711 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001712 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001713 }))
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001714 .then([](ftl::Future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001715 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001716}
1717
John Reck88270902021-03-18 11:27:35 -04001718status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1719 const sp<gui::IHdrLayerInfoListener>& listener) {
1720 if (!displayToken) {
1721 return BAD_VALUE;
1722 }
1723
1724 Mutex::Autolock lock(mStateLock);
1725
1726 const auto display = getDisplayDeviceLocked(displayToken);
1727 if (!display) {
1728 return NAME_NOT_FOUND;
1729 }
1730 const auto displayId = display->getId();
1731 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1732 if (!hdrInfoReporter) {
1733 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1734 }
1735 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001736
1737
1738 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001739 return OK;
1740}
1741
1742status_t SurfaceFlinger::removeHdrLayerInfoListener(
1743 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1744 if (!displayToken) {
1745 return BAD_VALUE;
1746 }
1747
1748 Mutex::Autolock lock(mStateLock);
1749
1750 const auto display = getDisplayDeviceLocked(displayToken);
1751 if (!display) {
1752 return NAME_NOT_FOUND;
1753 }
1754 const auto displayId = display->getId();
1755 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1756 if (hdrInfoReporter) {
1757 hdrInfoReporter->removeListener(listener);
1758 }
1759 return OK;
1760}
1761
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001762status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001763 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001764 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001765
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001766 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001767 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001768 }
1769
1770 return NO_ERROR;
1771}
1772
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001773status_t SurfaceFlinger::getDisplayDecorationSupport(
1774 const sp<IBinder>& displayToken,
1775 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001776 if (!displayToken || !outSupport) {
1777 return BAD_VALUE;
1778 }
1779
1780 Mutex::Autolock lock(mStateLock);
1781
1782 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1783 if (!displayId) {
1784 return NAME_NOT_FOUND;
1785 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001786 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001787 return NO_ERROR;
1788}
1789
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001790// ----------------------------------------------------------------------------
1791
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001792sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001793 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001794 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001795 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1796 ? mSfConnectionHandle
1797 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001798
Ady Abraham62f216c2020-10-13 19:07:23 -07001799 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001800}
1801
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001802void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001803 if (hint == FrameHint::kActive) {
1804 mScheduler->resetIdleTimer();
1805 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001806 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001807 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001808}
1809
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001810void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1811 mMustComposite = true;
1812 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001813}
1814
1815void SurfaceFlinger::scheduleRepaint() {
1816 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001817 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001818}
1819
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001820void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001821 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001822}
1823
Ady Abraham2492a022020-07-24 11:09:55 -07001824nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001825 if (const auto display = getDefaultDisplayDeviceLocked()) {
1826 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001827 }
1828
Marin Shalamanov045b7002021-01-07 16:56:24 +01001829 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001830}
1831
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001832void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1833 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001834 const std::string tracePeriod = [vsyncPeriod]() {
1835 if (ATRACE_ENABLED() && vsyncPeriod) {
1836 std::stringstream ss;
1837 ss << "(" << *vsyncPeriod << ")";
1838 return ss.str();
1839 }
1840 return std::string();
1841 }();
1842 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001843
Steven Thomas3cfac282017-02-06 12:29:30 -08001844 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001845 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1846 if (displayId) {
1847 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1848 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001849 display->onVsync(timestamp);
1850 }
1851
Dominik Laskowski075d3172018-05-24 15:50:06 -07001852 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001853 return;
1854 }
1855
Ady Abrahame1166472021-07-15 10:56:06 -07001856 const bool isActiveDisplay =
1857 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1858 if (!isActiveDisplay) {
1859 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001860 return;
1861 }
1862
Alec Mourif8e689c2019-05-20 18:32:22 -07001863 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001864 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001865 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001866 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001867 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001868}
1869
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001870void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1871 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001872 const bool connected = connection == hal::Connection::CONNECTED;
1873 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001874
Steven Thomasb02664d2017-07-26 18:48:28 -07001875 // Only lock if we're not on the main thread. This function is normally
1876 // called on a hwbinder thread, but for the primary display it's called on
1877 // the main thread with the state lock already held, so don't attempt to
1878 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001879 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001880
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001881 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001882
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001883 if (std::this_thread::get_id() == mMainThreadId) {
1884 // Process all pending hot plug events immediately if we are on the main thread.
1885 processDisplayHotplugEventsLocked();
1886 }
1887
Lloyd Piqueba04e622017-12-14 17:11:26 -08001888 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001889}
1890
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001891void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1892 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001893 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001894 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001895
1896 if (timeline.refreshRequired) {
1897 scheduleComposite(FrameHint::kNone);
1898 }
Ady Abraham7159f572019-10-11 11:10:18 -07001899}
1900
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001901void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001902 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001903 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1904}
1905
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001906void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001907 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001908 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001909}
1910
Yichi Chen3401b562022-01-17 15:42:35 +08001911void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001912 ATRACE_CALL();
1913 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001914}
1915
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001916void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001917 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001918
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001919 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001920 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001921 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001922
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001923 if (const auto display = getDefaultDisplayDeviceLocked();
1924 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001925 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001926 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001927 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001928}
1929
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001930auto SurfaceFlinger::getPreviousPresentFence(TimePoint frameTime, Period vsyncPeriod)
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001931 -> const FenceTimePtr& {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001932 const bool isTwoVsyncsAhead = mExpectedPresentTime - frameTime > vsyncPeriod;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001933 const size_t i = static_cast<size_t>(isTwoVsyncsAhead);
1934 return mPreviousPresentFences[i].fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001935}
1936
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001937bool SurfaceFlinger::isFencePending(const FenceTimePtr& fence, int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001938 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001939 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001940 return false;
1941 }
1942
Dan Stoza59083052020-04-28 10:13:20 -07001943 const status_t status = fence->wait(graceTimeMs);
1944 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1945 // which calls wait(0) again internally
1946 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001947}
1948
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001949TimePoint SurfaceFlinger::calculateExpectedPresentTime(TimePoint frameTime) const {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001950 const auto& schedule = mScheduler->getVsyncSchedule();
Alec Mouri6d414b52020-03-17 11:18:05 -07001951
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001952 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(frameTime);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001953 if (mVsyncModulator->getVsyncConfig().sfOffset > 0) {
1954 return vsyncDeadline;
Alec Mouri6d414b52020-03-17 11:18:05 -07001955 }
1956
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001957 // Inflate the expected present time if we're targeting the next vsync.
1958 return vsyncDeadline + schedule.period();
Alec Mouriaa614192019-06-06 13:28:34 -07001959}
1960
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001961bool SurfaceFlinger::commit(TimePoint frameTime, VsyncId vsyncId, TimePoint expectedVsyncTime)
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001962 FTL_FAKE_GUARD(kMainThreadContext) {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001963 // The expectedVsyncTime, which was predicted when this frame was scheduled, is normally in the
1964 // future relative to frameTime, but may not be for delayed frames. Adjust mExpectedPresentTime
1965 // accordingly, but not mScheduledPresentTime.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001966 const TimePoint lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001967 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07001968
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001969 // Calculate the expected present time once and use the cached value throughout this frame to
1970 // make sure all layers are seeing this same value.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001971 mExpectedPresentTime = expectedVsyncTime >= frameTime ? expectedVsyncTime
1972 : calculateExpectedPresentTime(frameTime);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001973
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001974 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId.value,
1975 ticks<std::milli, float>(mExpectedPresentTime - scheduler::SchedulerClock::now()),
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001976 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07001977
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001978 const Period vsyncPeriod = mScheduler->getVsyncSchedule().period();
1979 const FenceTimePtr& previousPresentFence = getPreviousPresentFence(frameTime, vsyncPeriod);
1980
Dan Stoza28d46a52020-04-28 09:54:54 -07001981 // When Backpressure propagation is enabled we want to give a small grace period
1982 // for the present fence to fire instead of just giving up on this frame to handle cases
1983 // where present fence is just about to get signaled.
1984 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07001985 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07001986
1987 // Pending frames may trigger backpressure propagation.
1988 const TracedOrdinal<bool> framePending = {"PrevFramePending",
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001989 isFencePending(previousPresentFence,
1990 graceTimeForPresentFenceMs)};
Dan Stoza28d46a52020-04-28 09:54:54 -07001991
1992 // Frame missed counts for metrics tracking.
1993 // A frame is missed if the prior frame is still pending. If no longer pending,
1994 // then we still count the frame as missed if the predicted present time
1995 // was further in the past than when the fence actually fired.
1996
1997 // Add some slop to correct for drift. This should generally be
1998 // smaller than a typical frame duration, but should not be so small
1999 // that it reports reasonable drift as a missed frame.
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002000 const nsecs_t frameMissedSlop = vsyncPeriod.ns() / 2;
2001 const nsecs_t previousPresentTime = previousPresentFence->getSignalTime();
Dan Stoza28d46a52020-04-28 09:54:54 -07002002 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2003 framePending ||
2004 (previousPresentTime >= 0 &&
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002005 (lastScheduledPresentTime.ns() <
Dan Stoza28d46a52020-04-28 09:54:54 -07002006 previousPresentTime - frameMissedSlop))};
2007 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2008 mHadDeviceComposition && frameMissed};
2009 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2010 mHadClientComposition && frameMissed};
2011
2012 if (frameMissed) {
2013 mFrameMissedCount++;
2014 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002015 }
2016
2017 if (hwcFrameMissed) {
2018 mHwcFrameMissedCount++;
2019 }
2020
2021 if (gpuFrameMissed) {
2022 mGpuFrameMissedCount++;
2023 }
2024
Vishnu Nair286f4f92022-06-08 16:37:39 -07002025 if (mTracingEnabledChanged) {
2026 mLayerTracingEnabled = mLayerTracing.isEnabled();
2027 mTracingEnabledChanged = false;
2028 }
2029
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002030 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002031 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002032 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002033 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002034 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002035 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002036 }
2037
2038 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002039 // the mode, hence we update SF.
2040 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002041 {
2042 Mutex::Autolock lock(mStateLock);
2043 updateInternalStateWithChangedMode();
2044 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002045 }
2046
John Reck2ec53912020-07-07 16:53:55 -07002047 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002048 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002049 scheduleCommit(FrameHint::kNone);
2050 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002051 }
2052 }
2053
Matt Buckley50c44062022-01-17 20:48:10 +00002054 // Save this once per commit + composite to ensure consistency
Matt Buckleyba8d15a2022-08-02 20:10:15 +00002055 // TODO (b/240619471): consider removing active display check once AOD is fixed
2056 const auto activeDisplay =
2057 FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(mActiveDisplayToken));
2058 mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession() && activeDisplay &&
2059 activeDisplay->getPowerMode() == hal::PowerMode::ON;
Matt Buckley50c44062022-01-17 20:48:10 +00002060 if (mPowerHintSessionEnabled) {
Matt Buckley1151f462022-07-29 00:13:27 +00002061 const auto& display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Matt Buckley1151f462022-07-29 00:13:27 +00002062 const nsecs_t vsyncPeriod = display->getActiveMode()->getVsyncPeriod();
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002063 mPowerAdvisor->setCommitStart(frameTime.ns());
2064 mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime.ns());
2065
2066 // Frame delay is how long we should have minus how long we actually have.
2067 const Duration idealSfWorkDuration = mVsyncModulator->getVsyncConfig().sfWorkDuration;
2068 const Duration frameDelay = idealSfWorkDuration - (mExpectedPresentTime - frameTime);
2069
2070 mPowerAdvisor->setFrameDelay(frameDelay.ns());
2071 mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration.ns());
Matt Buckley50c44062022-01-17 20:48:10 +00002072 mPowerAdvisor->setTargetWorkDuration(vsyncPeriod);
2073
2074 // Send early hint here to make sure there's not another frame pending
2075 if (mPowerHintSessionMode.early) {
2076 // Send a rough prediction for this frame based on last frame's timing info
2077 mPowerAdvisor->sendPredictedWorkDuration();
2078 }
2079 }
2080
Ady Abraham29d0da32020-07-16 18:39:33 -07002081 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002082 Mutex::Autolock lock(mStateLock);
2083 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002084 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002085 }
2086 }
2087
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002088 // Composite if transactions were committed, or if requested by HWC.
2089 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002090 {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002091 mFrameTimeline->setSfWakeUp(vsyncId.value, frameTime.ns(),
2092 Fps::fromPeriodNsecs(vsyncPeriod.ns()));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002093
chaviw6b9ffea2021-11-08 09:25:48 -06002094 bool needsTraversal = false;
2095 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00002096 needsTraversal |= commitMirrorDisplays(vsyncId);
Vishnu Nair286f4f92022-06-08 16:37:39 -07002097 needsTraversal |= commitCreatedLayers(vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002098 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002099 }
2100
2101 const bool shouldCommit =
2102 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2103 if (shouldCommit) {
2104 commitTransactions();
2105 }
2106
2107 if (transactionFlushNeeded()) {
2108 setTransactionFlags(eTransactionFlushNeeded);
2109 }
2110
2111 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002112 mustComposite |= latchBuffers();
2113
chaviw6b9ffea2021-11-08 09:25:48 -06002114 // This has to be called after latchBuffers because we want to include the layers that have
2115 // been latched in the commit callback
2116 if (!needsTraversal) {
2117 // Invoke empty transaction callbacks early.
2118 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2119 } else {
2120 // Invoke OnCommit callbacks.
2121 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2122 }
2123
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002124 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002125 }
2126
2127 // Layers need to get updated (in the previous line) before we can use them for
2128 // choosing the refresh rate.
2129 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2130 // and may eventually call to ~Layer() if it holds the last reference
2131 {
2132 Mutex::Autolock _l(mStateLock);
2133 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002134 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002135 }
2136
Dan Stoza28d46a52020-04-28 09:54:54 -07002137 updateCursorAsync();
2138 updateInputFlinger();
2139
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002140 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2141 // This will block and tracing should only be enabled for debugging.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002142 mLayerTracing.notify(mVisibleRegionsDirty, frameTime.ns(), vsyncId.value);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002143 }
Pablo Gamito6be82442022-06-13 11:04:34 +00002144 mLastCommittedVsyncId = vsyncId;
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002145
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002146 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002147
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002148 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002149}
2150
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002151void SurfaceFlinger::composite(TimePoint frameTime, VsyncId vsyncId)
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002152 FTL_FAKE_GUARD(kMainThreadContext) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002153 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId.value);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002154
Lloyd Piqueab039b52019-02-13 14:22:42 -08002155 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002156 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002157 refreshArgs.outputs.reserve(displays.size());
Matt Buckley50c44062022-01-17 20:48:10 +00002158 std::vector<DisplayId> displayIds;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002159 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002160 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Matt Buckley50c44062022-01-17 20:48:10 +00002161 displayIds.push_back(display->getId());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002162 }
Matt Buckley50c44062022-01-17 20:48:10 +00002163 mPowerAdvisor->setDisplays(displayIds);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002164 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002165 if (auto layerFE = layer->getCompositionEngineLayerFE())
2166 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002167 });
Tianhao Yao67dd7122022-02-22 17:48:33 +00002168
2169 if (DOES_CONTAIN_BORDER) {
2170 refreshArgs.borderInfoList.clear();
2171 mDrawingState.traverse([&refreshArgs](Layer* layer) {
2172 if (layer->isBorderEnabled()) {
2173 compositionengine::BorderRenderInfo info;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00002174 info.width = layer->getBorderWidth();
2175 info.color = layer->getBorderColor();
Tianhao Yao67dd7122022-02-22 17:48:33 +00002176 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2177 info.layerIds.push_back(ilayer->getSequence());
2178 });
2179 refreshArgs.borderInfoList.emplace_back(std::move(info));
2180 }
2181 });
2182 }
2183
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002184 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002185 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002186 if (auto layerFE = layer->getCompositionEngineLayerFE())
2187 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002188 }
2189
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002190 refreshArgs.outputColorSetting = useColorManagement
2191 ? mDisplayColorSetting
2192 : compositionengine::OutputColorSetting::kUnmanaged;
2193 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2194 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002195
2196 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002197 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002198 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002199 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002200
2201 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2202 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2203 mDrawingState.colorMatrixChanged = false;
2204 }
2205
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002206 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002207
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002208 if (mDebugFlashDelay != 0) {
2209 refreshArgs.devOptForceClientComposition = true;
2210 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002211 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002212
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002213 const auto prevVsyncTime = mExpectedPresentTime - mScheduler->getVsyncSchedule().period();
Ady Abrahamcaba2982021-06-16 16:45:04 -07002214 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002215
Ady Abrahamcaba2982021-06-16 16:45:04 -07002216 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002217 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002218 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002219 refreshArgs.expectedPresentTime = mExpectedPresentTime.ns();
Ady Abraham3645e642021-04-20 18:39:00 -07002220
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002221 // Store the present time just before calling to the composition engine so we could notify
2222 // the scheduler.
2223 const auto presentTime = systemTime();
2224
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002225 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002226
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002227 mTimeStats->recordFrameDuration(frameTime.ns(), systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002228
Matt Buckley50c44062022-01-17 20:48:10 +00002229 // Send a power hint hint after presentation is finished
2230 if (mPowerHintSessionEnabled) {
Matt Buckley1809d902022-08-05 06:51:43 +00002231 mPowerAdvisor->setSfPresentTiming(mPreviousPresentFences[0].fenceTime->getSignalTime(),
2232 systemTime());
Matt Buckley50c44062022-01-17 20:48:10 +00002233 if (mPowerHintSessionMode.late) {
2234 mPowerAdvisor->sendActualWorkDuration();
2235 }
2236 }
2237
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002238 if (mScheduler->onPostComposition(presentTime)) {
2239 scheduleComposite(FrameHint::kNone);
2240 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002241
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002242 postComposition();
2243
Midas Chien50f52e22020-09-26 17:57:42 +08002244 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002245
Vishnu Nair9cf89262022-02-26 09:17:49 -08002246 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2247 TimeStats::ClientCompositionRecord clientCompositionRecord;
2248 for (const auto& [_, display] : displays) {
2249 const auto& state = display->getCompositionDisplay()->getState();
2250 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2251 mHadDeviceComposition |= state.usesDeviceComposition;
2252 mReusedClientComposition |= state.reusedClientComposition;
2253 clientCompositionRecord.predicted |=
2254 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2255 clientCompositionRecord.predictionSucceeded |=
2256 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002257 }
2258
Vishnu Nair9cf89262022-02-26 09:17:49 -08002259 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2260 clientCompositionRecord.reused = mReusedClientComposition;
2261 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2262 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2263
Yichi Chen28dee2c2020-07-06 21:24:14 +08002264 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002265 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2266 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002267
David Sodman7e4ae112018-02-09 15:02:28 -08002268 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002269 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002270 // This will block and should only be used for debugging.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002271 mLayerTracing.notify(mVisibleRegionsDirty, frameTime.ns(), vsyncId.value);
Vishnu Nairdf529052019-06-07 14:53:14 -07002272 }
Robert Carr167bdde2021-07-28 11:26:51 -07002273
2274 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002275 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002276
2277 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002278 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002279 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002280
Matt Buckley50c44062022-01-17 20:48:10 +00002281 if (mPowerHintSessionEnabled) {
2282 mPowerAdvisor->setCompositeEnd(systemTime());
Matt Buckleyef51fba2021-10-12 19:30:12 +00002283 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002284}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002285
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002286void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002287 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002288
Vishnu Nair4351ad52019-02-11 14:13:02 -08002289 if (mVisibleRegionsDirty) {
2290 computeLayerBounds();
2291 }
2292
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002293 for (auto& layer : mLayersPendingRefresh) {
2294 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002295 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002296 invalidateLayerStack(layer, visibleReg);
2297 }
2298 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002299}
2300
John Reck49d9ad32022-02-23 19:03:31 -05002301bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002302 // Treat all layers as non-HDR if:
2303 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2304 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2305 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2306 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2307 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002308 return false;
2309 }
2310 if (mIgnoreHdrCameraLayers) {
2311 auto buffer = layer->getBuffer();
2312 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2313 return false;
2314 }
2315 }
2316 return true;
2317}
2318
ramindani06e518e2022-03-14 18:47:53 +00002319ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2320 bool isPrimary) const {
2321 const auto id = PhysicalDisplayId::tryCast(displayId);
2322 if (!id) {
2323 return ui::ROTATION_0;
2324 }
2325 if (getHwComposer().getComposer()->isSupported(
2326 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2327 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2328 case Hwc2::AidlTransform::ROT_90:
2329 return ui::ROTATION_90;
2330 case Hwc2::AidlTransform::ROT_180:
2331 return ui::ROTATION_180;
2332 case Hwc2::AidlTransform::ROT_270:
2333 return ui::ROTATION_270;
2334 default:
2335 return ui::ROTATION_0;
2336 }
2337 }
2338
2339 if (isPrimary) {
2340 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2341 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2342 case Values::ORIENTATION_90:
2343 return ui::ROTATION_90;
2344 case Values::ORIENTATION_180:
2345 return ui::ROTATION_180;
2346 case Values::ORIENTATION_270:
2347 return ui::ROTATION_270;
2348 default:
2349 break;
2350 }
2351 }
2352 return ui::ROTATION_0;
2353}
2354
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002355void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002356 ATRACE_CALL();
Dominik Laskowski8792c112022-07-12 09:03:39 -07002357 ALOGV(__func__);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002358
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002359 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002360
2361 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002362 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002363 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002364 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002365 ->getRenderSurface()
2366 ->getClientTargetAcquireFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002367 } else {
2368 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2369 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002370
Ady Abrahambe0f9482019-04-24 15:41:53 -07002371 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002372
Dominik Laskowski8792c112022-07-12 09:03:39 -07002373 auto presentFence =
2374 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
2375
2376 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
2377 mPreviousPresentFences[0] = {presentFence, presentFenceTime};
2378
2379 const TimePoint presentTime = scheduler::SchedulerClock::now();
Vishnu Nair9a69a042021-06-18 13:19:49 -07002380
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002381 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2382 // information from previous' frame classification is already available when sending jank info
2383 // to clients, so they get jank classification as early as possible.
Dominik Laskowski8792c112022-07-12 09:03:39 -07002384 mFrameTimeline->setSfPresent(presentTime.ns(), presentFenceTime, glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002385
Lloyd Piqueab039b52019-02-13 14:22:42 -08002386 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2387 // be sampled a little later than when we started doing work for this frame,
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002388 // but that should be okay since CompositorTiming has snapping logic.
Dominik Laskowski80c77272022-07-08 12:47:29 -07002389 const TimePoint compositeTime =
2390 TimePoint::fromNs(mCompositionEngine->getLastFrameRefreshTimestamp());
2391 const Duration presentLatency =
Dominik Laskowski8792c112022-07-12 09:03:39 -07002392 mPresentLatencyTracker.trackPendingFrame(compositeTime, presentFenceTime);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002393
2394 const auto& schedule = mScheduler->getVsyncSchedule();
Dominik Laskowski8792c112022-07-12 09:03:39 -07002395 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(presentTime);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002396 const Period vsyncPeriod = schedule.period();
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002397 const nsecs_t vsyncPhase = mVsyncConfiguration->getCurrentConfigs().late.sfOffset;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002398
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002399 const CompositorTiming compositorTiming(vsyncDeadline.ns(), vsyncPeriod.ns(), vsyncPhase,
Dominik Laskowski80c77272022-07-08 12:47:29 -07002400 presentLatency.ns());
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002401
Robert Carrc747ad02021-06-11 14:01:24 -07002402 for (const auto& layer: mLayersWithQueuedFrames) {
Dominik Laskowski8792c112022-07-12 09:03:39 -07002403 layer->onPostComposition(display, glCompositionDoneFenceTime, presentFenceTime,
2404 compositorTiming);
2405 layer->releasePendingBuffer(presentTime.ns());
Robert Carrc747ad02021-06-11 14:01:24 -07002406 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002407
John Reck88270902021-03-18 11:27:35 -04002408 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2409 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002410 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002411 {
2412 Mutex::Autolock lock(mStateLock);
2413 if (mFpsReporter) {
2414 mFpsReporter->dispatchLayerFps();
2415 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002416
2417 if (mTunnelModeEnabledReporter) {
2418 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2419 }
John Reck88270902021-03-18 11:27:35 -04002420 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002421 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2422 if (reporter && reporter->hasListeners()) {
2423 if (const auto display = getDisplayDeviceLocked(displayId)) {
2424 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002425 }
2426 }
2427 }
Robert Carr167bdde2021-07-28 11:26:51 -07002428 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2429 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002430 }
2431
Robert Carr167bdde2021-07-28 11:26:51 -07002432 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2433 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2434 HdrLayerInfoReporter::HdrLayerInfo info;
2435 int32_t maxArea = 0;
2436 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2437 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002438 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002439 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002440 const auto* outputLayer =
2441 compositionDisplay->getOutputLayerForLayer(layerFe);
2442 if (outputLayer) {
2443 info.numberOfHdrLayers++;
2444 const auto displayFrame = outputLayer->getState().displayFrame;
2445 const int32_t area = displayFrame.width() * displayFrame.height();
2446 if (area > maxArea) {
2447 maxArea = area;
2448 info.maxW = displayFrame.width();
2449 info.maxH = displayFrame.height();
2450 }
John Reckdb1a16b2021-07-09 13:05:52 -04002451 }
John Reck88270902021-03-18 11:27:35 -04002452 }
2453 }
Robert Carr167bdde2021-07-28 11:26:51 -07002454 });
2455 listener->dispatchHdrLayerInfo(info);
2456 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002457 }
2458
Robert Carr167bdde2021-07-28 11:26:51 -07002459 mSomeDataspaceChanged = false;
2460 mVisibleRegionsWereDirtyThisFrame = false;
2461
Dominik Laskowski8792c112022-07-12 09:03:39 -07002462 mTransactionCallbackInvoker.addPresentFence(std::move(presentFence));
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002463 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002464 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002465
Dominik Laskowski8792c112022-07-12 09:03:39 -07002466 mTimeStats->incrementTotalFrames();
2467 mTimeStats->setPresentFenceGlobal(presentFenceTime);
2468
Ady Abrahamed3290f2021-05-17 15:12:14 -07002469 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Dominik Laskowski8792c112022-07-12 09:03:39 -07002470 presentFenceTime->isValid()) {
2471 mScheduler->addPresentFence(std::move(presentFenceTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002472 }
2473
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002474 const bool isDisplayConnected =
2475 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002476
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002477 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002478 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002479 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002480 }
2481 }
2482
Alec Mouri717bcb62020-02-10 17:07:19 -08002483 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2484 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2485 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2486
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002487 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002488 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002489 return;
2490 }
2491
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002492 // Cleanup any outstanding resources due to rendering a prior frame.
2493 getRenderEngine().cleanupPostRender();
2494
Dan Stoza436ccf32018-06-21 12:10:12 -07002495 {
2496 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002497 if (mTexturePool.size() < mTexturePoolSize) {
2498 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002499 const size_t offset = mTexturePool.size();
2500 mTexturePool.resize(mTexturePoolSize);
2501 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2502 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002503 } else if (mTexturePool.size() > mTexturePoolSize) {
2504 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2505 const size_t offset = mTexturePoolSize;
2506 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2507 mTexturePool.resize(mTexturePoolSize);
2508 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002509 }
2510 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002511
Dan Stoza45de5ba2019-04-25 14:12:09 -07002512 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2513 // side-effect of getTotalSize(), so we check that again here
2514 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002515 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002516 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2517 }
Dominik Laskowski8792c112022-07-12 09:03:39 -07002518
2519 logFrameStats(presentTime);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002520}
2521
chaviw79468ab2021-10-27 11:11:24 -05002522FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002523 const ui::Size maxSize = [this] {
2524 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002525
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002526 // The LayerTraceGenerator tool runs without displays.
2527 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002528
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002529 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2530 [](ui::Size size, const auto& pair) -> ui::Size {
2531 const auto& display = pair.second;
2532 return {std::max(size.getWidth(), display->getWidth()),
2533 std::max(size.getHeight(), display->getHeight())};
2534 });
2535 }();
chaviwb09c6552021-08-12 17:20:43 -05002536
2537 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2538 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002539 const float xMax = maxSize.getWidth() * 10.f;
2540 const float yMax = maxSize.getHeight() * 10.f;
2541
2542 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002543}
2544
2545void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002546 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002547 for (const auto& layer : mDrawingState.layersSortedByZ) {
2548 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002549 }
2550}
2551
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002552void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002553 ATRACE_CALL();
2554
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002555 // Keep a copy of the drawing state (that is going to be overwritten
2556 // by commitTransactionsLocked) outside of mStateLock so that the side
2557 // effects of the State assignment don't happen with mStateLock held,
2558 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002559 State drawingState(mDrawingState);
2560
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002561 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002562 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563
Mathias Agopianca4d3602011-05-19 15:38:14 -07002564 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002565 // so we can call commitTransactionsLocked unconditionally.
2566 // We clear the flags with mStateLock held to guarantee that
2567 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002568 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002569 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002570
Mathias Agopianca4d3602011-05-19 15:38:14 -07002571 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002572}
2573
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002574std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2575 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002576 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2577 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002578
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002579 int attempt = 0;
2580 constexpr int kMaxAttempts = 3;
2581 do {
2582 hwcModes = getHwComposer().getModes(displayId);
2583 activeModeHwcId = getHwComposer().getActiveMode(displayId);
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002584
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002585 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
Dominik Laskowskibab51282022-08-12 09:28:55 -07002586 return mode.hwcId == activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002587 };
2588
2589 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2590 break;
2591 }
2592 } while (++attempt < kMaxAttempts);
2593
Dominik Laskowskibab51282022-08-12 09:28:55 -07002594 if (attempt == kMaxAttempts) {
2595 const std::string activeMode =
2596 activeModeHwcId ? std::to_string(*activeModeHwcId) : "unknown"s;
2597 ALOGE("HWC failed to report an active mode that is supported: activeModeHwcId=%s, "
2598 "hwcModes={%s}",
2599 activeMode.c_str(), base::Join(hwcModes, ", ").c_str());
2600 return {};
2601 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002602
2603 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002604 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2605 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002606 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002607
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002608 ui::DisplayModeId nextModeId = 1 +
2609 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2610 [](ui::DisplayModeId max, const auto& pair) {
2611 return std::max(max, pair.first.value());
2612 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002613
2614 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002615 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002616 const DisplayModeId id{nextModeId++};
2617 newModes.try_emplace(id,
2618 DisplayMode::Builder(hwcMode.hwcId)
2619 .setId(id)
2620 .setPhysicalDisplayId(displayId)
2621 .setResolution({hwcMode.width, hwcMode.height})
2622 .setVsyncPeriod(hwcMode.vsyncPeriod)
2623 .setDpiX(hwcMode.dpiX)
2624 .setDpiY(hwcMode.dpiY)
2625 .setGroup(hwcMode.configGroup)
2626 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002627 }
2628
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002629 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002630 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002631 [](const auto& lhs, const auto& rhs) {
2632 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002633 });
2634
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002635 // Keep IDs if modes have not changed.
2636 const auto& modes = sameModes ? oldModes : newModes;
2637 const DisplayModePtr activeMode =
2638 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2639 return pair.second->getHwcId() == activeModeHwcId;
2640 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002641
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002642 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002643}
2644
Lloyd Piqueba04e622017-12-14 17:11:26 -08002645void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2646 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002647 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002648 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002649
Dominik Laskowski075d3172018-05-24 15:50:06 -07002650 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002651 continue;
2652 }
2653
Marin Shalamanova524a092020-07-27 21:39:55 +02002654 const auto displayId = info->id;
Dominik Laskowskieb627312022-04-07 09:13:16 -07002655 const auto token = mPhysicalDisplayTokens.get(displayId);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002656
Peiyong Line9d809e2020-04-14 13:10:48 -07002657 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002658 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Dominik Laskowskibab51282022-08-12 09:28:55 -07002659 if (!activeMode) {
2660 // TODO(b/241286153): Report hotplug failure to the framework.
2661 ALOGE("Failed to hotplug display %s", to_string(displayId).c_str());
2662 getHwComposer().disconnectDisplay(displayId);
2663 continue;
2664 }
Marin Shalamanova903d032020-12-29 20:35:13 +01002665
Dominik Laskowskieb627312022-04-07 09:13:16 -07002666 if (!token) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002667 ALOGV("Creating display %s", to_string(displayId).c_str());
2668
Dominik Laskowski075d3172018-05-24 15:50:06 -07002669 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002670 state.physical = {.id = displayId,
2671 .type = getHwComposer().getDisplayConnectionType(displayId),
2672 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002673 .deviceProductInfo = std::move(info->deviceProductInfo),
2674 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002675 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002676 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002677 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002678
Ady Abrahamd11bade2022-08-01 16:18:03 -07002679 sp<IBinder> token = sp<BBinder>::make();
Dominik Laskowski55c85402020-01-21 16:25:47 -08002680 mCurrentState.displays.add(token, state);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002681 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002682 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002683 } else {
2684 ALOGV("Recreating display %s", to_string(displayId).c_str());
2685
Dominik Laskowskieb627312022-04-07 09:13:16 -07002686 auto& state = mCurrentState.displays.editValueFor(token->get());
2687 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
Marin Shalamanova903d032020-12-29 20:35:13 +01002688 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002689 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002690 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2691 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2692 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002693 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002694 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002695 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002696
Dominik Laskowskieb627312022-04-07 09:13:16 -07002697 if (const ssize_t index = mCurrentState.displays.indexOfKey(token->get()); index >= 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002698 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2699 mInterceptor->saveDisplayDeletion(state.sequenceId);
2700 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002701 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002702
2703 mPhysicalDisplayTokens.erase(displayId);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002704 }
2705
2706 processDisplayChangesLocked();
2707 }
2708
2709 mPendingHotplugEvents.clear();
2710}
2711
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002712void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002713 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2714 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002715 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2716 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002717}
2718
Lloyd Pique99d3da52018-01-22 17:48:03 -08002719sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002720 const wp<IBinder>& displayToken,
2721 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002722 const DisplayDeviceState& state,
2723 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002724 const sp<IGraphicBufferProducer>& producer) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002725 DisplayDeviceCreationArgs creationArgs(sp<SurfaceFlinger>::fromExisting(this), getHwComposer(),
2726 displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002727 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002728 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002729 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002730 creationArgs.hasWideColorGamut = false;
2731 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002732
Dominik Laskowski55c85402020-01-21 16:25:47 -08002733 if (const auto& physical = state.physical) {
2734 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002735 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002736 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002737 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2738 getKernelIdleTimerProperties(compositionDisplay->getId());
2739
Ady Abraham3efa3942021-06-24 19:01:25 -07002740 scheduler::RefreshRateConfigs::Config config =
2741 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2742 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002743 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002744 .idleTimerTimeout = idleTimerTimeoutMs,
2745 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002746 creationArgs.refreshRateConfigs =
2747 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2748 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002749 }
2750
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002751 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002752 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002754 if (useColorManagement) {
2755 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2756 for (ColorMode colorMode : modes) {
2757 if (isWideColorMode(colorMode)) {
2758 creationArgs.hasWideColorGamut = true;
2759 }
2760
2761 std::vector<RenderIntent> renderIntents =
2762 getHwComposer().getRenderIntents(*id, colorMode);
2763 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002764 }
2765 }
tangrobin6753a022018-08-10 10:58:54 +08002766 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002767
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002768 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2769 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2770 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002771 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002772
Lloyd Pique90c115d2018-09-18 21:39:42 -07002773 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002774 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002775 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002776
Lloyd Pique99d3da52018-01-22 17:48:03 -08002777 // Make sure that composition can never be stalled by a virtual display
2778 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002779 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002780 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002781 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2782 }
2783
Dominik Laskowski718f9602019-11-09 20:01:35 -08002784 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002785 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2786 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002787
Lloyd Pique99d3da52018-01-22 17:48:03 -08002788 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002789 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002790
Lloyd Pique9370a482019-10-03 17:58:30 -07002791 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002792
Ady Abraham8565ad22021-06-22 17:45:44 -07002793 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002794
2795 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002796 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002797 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002798 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002799 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002800 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002801 display->getCompositionDisplay()->setColorProfile(
2802 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2803 RenderIntent::COLORIMETRIC,
2804 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002805 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002806 FTL_FAKE_GUARD(kMainThreadContext,
2807 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002808 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002809 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002810
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002811 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002812 display->setProjection(state.orientation, state.layerStackSpaceRect,
2813 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002814 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002815 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002816
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002817 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002818}
2819
Marin Shalamanovae685592020-02-12 17:12:22 +01002820void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2821 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002822 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002823 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2824 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002825 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002826 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2827 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002828 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002829 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002830 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002831 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002832 int format;
2833 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002834 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002835 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002836 } else {
2837 // Virtual displays without a surface are dormant:
2838 // they have external state (layer stack, projection,
2839 // etc.) but no internal state (i.e. a DisplayDevice).
2840 return;
2841 }
2842
2843 compositionengine::DisplayCreationArgsBuilder builder;
2844 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002845 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002846 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002847 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002848 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002849
Marin Shalamanov045b7002021-01-07 16:56:24 +01002850 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002851 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002852 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002853 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002854 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002855 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002856
2857 sp<compositionengine::DisplaySurface> displaySurface;
2858 sp<IGraphicBufferProducer> producer;
2859 sp<IGraphicBufferProducer> bqProducer;
2860 sp<IGraphicBufferConsumer> bqConsumer;
2861 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2862
Marin Shalamanovae685592020-02-12 17:12:22 +01002863 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002864 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2865 LOG_FATAL_IF(!displayId);
2866 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2867 bqProducer, bqConsumer, state.displayName);
2868 displaySurface = surface;
2869 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002870 } else {
2871 ALOGE_IF(state.surface != nullptr,
2872 "adding a supported display, but rendering "
2873 "surface is provided (%p), ignoring it",
2874 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002875 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2876 LOG_FATAL_IF(!displayId);
2877 displaySurface =
2878 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002879 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002880 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002881 producer = bqProducer;
2882 }
2883
Marin Shalamanov700e6392020-02-12 20:22:26 +01002884 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002885 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2886 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002887 if (display->isPrimary()) {
2888 initScheduler(display);
2889 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002890 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002891 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002892 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002893
2894 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01002895}
2896
2897void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002898 auto display = getDisplayDeviceLocked(displayToken);
2899 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002900 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002901
2902 if (display->isVirtual()) {
2903 releaseVirtualDisplay(display->getVirtualId());
2904 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002905 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01002906 }
2907 }
2908
2909 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08002910
2911 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002912 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002913 // Destroy the display without holding the mStateLock.
2914 // This is a temporary solution until we can manage transaction queues without
2915 // holding the mStateLock.
2916 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
2917 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
2918 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
2919 // ends up running on the main thread causing a deadlock since setTransactionstate
2920 // will try to acquire the mStateLock. Instead we extend the lifetime of
2921 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
2922 // The display will be disconnected and removed from the mDisplays list so it will
2923 // not be accessible.
2924 }));
2925 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002926}
2927
2928void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2929 const DisplayDeviceState& currentState,
2930 const DisplayDeviceState& drawingState) {
2931 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2932 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002933
2934 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01002935 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02002936 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002937
Marin Shalamanovae685592020-02-12 17:12:22 +01002938 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2939 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002940 if (display->isVirtual()) {
2941 releaseVirtualDisplay(display->getVirtualId());
2942 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002943 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002944
Marin Shalamanovae685592020-02-12 17:12:22 +01002945 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002946
Marin Shalamanov700e6392020-02-12 20:22:26 +01002947 if (const auto& physical = currentState.physical) {
2948 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2949 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002950
Marin Shalamanovae685592020-02-12 17:12:22 +01002951 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002952
Marin Shalamanov700e6392020-02-12 20:22:26 +01002953 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002954 const auto display = getDisplayDeviceLocked(displayToken);
2955 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01002956
2957 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002958 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07002959 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01002960 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002961 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002962 return;
2963 }
2964
2965 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2966 if (currentState.layerStack != drawingState.layerStack) {
2967 display->setLayerStack(currentState.layerStack);
2968 }
Evan Rosky2239b372021-05-20 13:43:47 -07002969 if (currentState.flags != drawingState.flags) {
2970 display->setFlags(currentState.flags);
2971 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002972 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002973 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
2974 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
2975 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
2976 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07002977 if (isDisplayActiveLocked(display)) {
2978 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08002979 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002980 }
2981 if (currentState.width != drawingState.width ||
2982 currentState.height != drawingState.height) {
2983 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07002984
Ady Abrahamed3290f2021-05-17 15:12:14 -07002985 if (isDisplayActiveLocked(display)) {
2986 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01002987 }
2988 }
2989 }
2990}
Ady Abraham3efa3942021-06-24 19:01:25 -07002991void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07002992 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002993 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07002994 updatePhaseConfiguration(refreshRate);
2995 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07002996}
Marin Shalamanovae685592020-02-12 17:12:22 +01002997
Lloyd Pique347200f2017-12-14 17:00:15 -08002998void SurfaceFlinger::processDisplayChangesLocked() {
2999 // here we take advantage of Vector's copy-on-write semantics to
3000 // improve performance by skipping the transaction entirely when
3001 // know that the lists are identical
3002 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3003 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3004 if (!curr.isIdenticalTo(draw)) {
3005 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003006 mUpdateInputInfo = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003007
3008 // find the displays that were removed
3009 // (ie: in drawing state but not in current state)
3010 // also handle displays that changed
3011 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003012 for (size_t i = 0; i < draw.size(); i++) {
3013 const wp<IBinder>& displayToken = draw.keyAt(i);
3014 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003015 if (j < 0) {
3016 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003017 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003018 } else {
3019 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003020 const DisplayDeviceState& currentState = curr[j];
3021 const DisplayDeviceState& drawingState = draw[i];
3022 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003023 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003024 }
3025
3026 // find displays that were added
3027 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003028 for (size_t i = 0; i < curr.size(); i++) {
3029 const wp<IBinder>& displayToken = curr.keyAt(i);
3030 if (draw.indexOfKey(displayToken) < 0) {
3031 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003032 }
3033 }
3034 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003035
3036 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003037}
3038
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003039void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3040 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003041 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3042 if (displayTransactionNeeded) {
3043 processDisplayChangesLocked();
3044 processDisplayHotplugEventsLocked();
3045 }
Robert Carrb552ff52021-06-11 13:35:54 -07003046 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047
Robert Carre450fb52021-06-11 13:21:09 -07003048 if (mSomeChildrenChanged) {
3049 mVisibleRegionsDirty = true;
3050 mSomeChildrenChanged = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003051 mUpdateInputInfo = true;
Robert Carre450fb52021-06-11 13:21:09 -07003052 }
3053
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003054 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003055 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003056 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003057 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003058 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003059 // the hint is set before we acquire a buffer from the surface texture.
3060 //
3061 // NOTE: layer transactions have taken place already, so we use their
3062 // drawing state. However, SurfaceFlinger's own transaction has not
3063 // happened yet, so we must use the current state layer list
3064 // (soon to become the drawing state list).
3065 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003066 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003067 ui::LayerStack layerStack;
3068
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003069 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003070 // NOTE: we rely on the fact that layers are sorted by
3071 // layerStack first (so we don't have to traverse the list
3072 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003073 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3074 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003075 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003076
3077 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003078 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003079 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3080 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003081 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003082
3083 // Pick the primary display if another display mirrors the layer.
3084 if (hintDisplay) {
3085 hintDisplay = nullptr;
3086 break;
3087 }
3088
3089 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003090 }
3091 }
Chet Haase91d25932013-04-11 15:24:55 -07003092
Vishnu Naire3066de2022-06-08 12:16:25 -07003093 if (!hintDisplay && mDisplays.size() > 0) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003094 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3095 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003096
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003097 // could be null when this layer is using a layerStack
3098 // that is not visible on any display. Also can occur at
3099 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003100 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003101 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003102
Vishnu Naire3066de2022-06-08 12:16:25 -07003103 if (hintDisplay) {
3104 layer->updateTransformHint(hintDisplay->getTransformHint());
3105 } else {
3106 ALOGW("Ignoring transform hint update for %s", layer->getDebugName());
3107 }
Robert Carr2047fae2016-11-28 14:09:09 -08003108 });
Mathias Agopian84300952012-11-21 16:02:13 -08003109 }
3110
Robert Carr1f0a16a2016-10-24 16:27:39 -07003111 if (mLayersAdded) {
3112 mLayersAdded = false;
3113 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003114 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003115 mUpdateInputInfo = true;
Mathias Agopian3559b072012-08-15 13:46:03 -07003116 }
3117
3118 // some layers might have been removed, so
3119 // we need to update the regions they're exposing.
3120 if (mLayersRemoved) {
3121 mLayersRemoved = false;
3122 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003123 mUpdateInputInfo = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003124 mDrawingState.traverseInZOrder([&](Layer* layer) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07003125 if (mLayersPendingRemoval.indexOf(sp<Layer>::fromExisting(layer)) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003126 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003127 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003128 visibleReg.set(layer->getScreenBounds());
Ady Abrahamd11bade2022-08-01 16:18:03 -07003129 invalidateLayerStack(sp<Layer>::fromExisting(layer), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003130 }
Robert Carr2047fae2016-11-28 14:09:09 -08003131 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132 }
3133
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003134 doCommitTransactions();
3135 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
Riley Andrews03414a12014-07-01 14:22:59 -07003136}
3137
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003138void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003139 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003140 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003141 return;
3142 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003143
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003144 std::vector<WindowInfo> windowInfos;
3145 std::vector<DisplayInfo> displayInfos;
3146 bool updateWindowInfo = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003147 if (mUpdateInputInfo) {
3148 mUpdateInputInfo = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003149 updateWindowInfo = true;
3150 buildWindowInfos(windowInfos, displayInfos);
Arthur Hung9ed43392022-05-27 06:31:57 +00003151 } else if (mInputWindowCommands.empty()) {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003152 return;
3153 }
Arthur Hung9ed43392022-05-27 06:31:57 +00003154
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003155 BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
3156 windowInfos = std::move(windowInfos),
3157 displayInfos = std::move(displayInfos),
3158 inputWindowCommands =
3159 std::move(mInputWindowCommands),
3160 inputFlinger = mInputFlinger, this]() {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003161 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3162 if (updateWindowInfo) {
Patrick Williams641f7f22022-06-22 19:25:35 +00003163 mWindowInfosListenerInvoker
3164 ->windowInfosChanged(windowInfos, displayInfos,
3165 inputWindowCommands.windowInfosReportedListeners);
3166 } else {
3167 // If there are listeners but no changes to input windows, call the listeners
3168 // immediately.
3169 for (const auto& listener : inputWindowCommands.windowInfosReportedListeners) {
3170 if (IInterface::asBinder(listener)->isBinderAlive()) {
3171 listener->onWindowInfosReported();
3172 }
3173 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003174 }
3175 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3176 inputFlinger->setFocusedWindow(focusRequest);
3177 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003178 }});
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003179
Arthur Hung6cbb9752019-09-05 16:38:18 +08003180 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003181}
3182
Alec Mouricdf16792021-12-10 13:16:06 -08003183void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3184 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3185 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3186 if (!supportsDisplayBrightnessCommand) {
3187 return;
3188 }
3189
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003190 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003191 if (const auto brightness = display->getStagedBrightness(); brightness) {
3192 if (!needsComposite) {
3193 const status_t error =
3194 getHwComposer()
3195 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003196 display->getCompositionDisplay()
3197 ->getState()
3198 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003199 Hwc2::Composer::DisplayBrightnessOptions{
3200 .applyImmediately = true})
3201 .get();
3202
3203 ALOGE_IF(error != NO_ERROR,
3204 "Error setting display brightness for display %s: %d (%s)",
3205 display->getDebugName().c_str(), error, strerror(error));
3206 }
3207 display->persistBrightness(needsComposite);
3208 }
3209 }
3210}
3211
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003212void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3213 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003214 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3215
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003216 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003217 const auto layerStack = display->getLayerStack();
3218 const auto info = display->getInputInfo();
3219
3220 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003221 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003222 continue;
3223 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003224
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003225 // If the layer stack is mirrored on multiple displays, the first display that is configured
3226 // to receive input takes precedence.
3227 auto& otherInfo = it->second;
3228 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003229 ALOGW_IF(display->receivesInput(),
3230 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003231 layerStack.id);
3232 } else {
3233 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003234 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003235 }
Robert Carr720e5062018-07-30 17:45:14 -07003236
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003237 static size_t sNumWindowInfos = 0;
3238 outWindowInfos.reserve(sNumWindowInfos);
3239 sNumWindowInfos = 0;
3240
Robert Carr720e5062018-07-30 17:45:14 -07003241 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003242 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003243
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00003244 const auto opt = displayInputInfos.get(layer->getLayerStack(),
3245 [](const auto& info) -> Layer::InputDisplayArgs {
3246 return {&info.transform, info.isSecure};
3247 });
3248 outWindowInfos.push_back(layer->fillInputInfo(opt.value_or(Layer::InputDisplayArgs{})));
Robert Carr720e5062018-07-30 17:45:14 -07003249 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003250
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003251 sNumWindowInfos = outWindowInfos.size();
3252
3253 outDisplayInfos.reserve(displayInputInfos.size());
3254 for (const auto& [_, info] : displayInputInfos) {
3255 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003256 }
Robert Carr720e5062018-07-30 17:45:14 -07003257}
3258
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003259void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003260 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003261 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003262 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003263 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003264 }
3265 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003266
3267 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003268}
3269
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003270void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003271 // If this is called from the main thread mStateLock must be locked before
3272 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003273 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003274
3275 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003276
3277 const auto display = getDefaultDisplayDeviceLocked();
3278 if (!display || mBootStage != BootStage::FINISHED) {
3279 return;
3280 }
3281 ATRACE_CALL();
3282
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003283 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3284 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003285 return;
3286 }
3287
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003288 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003289}
3290
Ady Abraham62a0be22020-12-08 16:54:10 -08003291void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3292 PhysicalDisplayId displayId = [&]() {
3293 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3294 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3295 }();
3296
3297 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3298}
3299
Ady Abraham3efa3942021-06-24 19:01:25 -07003300void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003301 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003302 // If the scheduler is already initialized, this means that we received
3303 // a hotplug(connected) on the primary display. In that case we should
3304 // update the scheduler with the most recent display information.
3305 ALOGW("Scheduler already initialized, updating instead");
3306 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003307 return;
3308 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003309 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003310 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3311 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003312
Marin Shalamanova903d032020-12-29 20:35:13 +01003313 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003314 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003315
Dominik Laskowski068173d2021-08-11 17:22:59 -07003316 using Feature = scheduler::Feature;
3317 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003318
Dominik Laskowski068173d2021-08-11 17:22:59 -07003319 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3320 features |= Feature::kContentDetection;
3321 }
3322 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3323 features |= Feature::kTracePredictedVsync;
3324 }
3325 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003326 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003327 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003328 }
3329
Dominik Laskowski068173d2021-08-11 17:22:59 -07003330 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3331 static_cast<ISchedulerCallback&>(*this),
3332 features);
3333 {
3334 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003335 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003336 features |= Feature::kKernelIdleTimer;
3337 }
3338
3339 mScheduler->createVsyncSchedule(features);
3340 mScheduler->setRefreshRateConfigs(std::move(configs));
3341 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003342 setVsyncEnabled(false);
3343 mScheduler->startTimers();
3344
Ady Abraham9c53ee72020-07-22 21:16:18 -07003345 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003346 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003347 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003348 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003349 /*workDuration=*/configs.late.appWorkDuration,
3350 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003351 impl::EventThread::InterceptVSyncsCallback());
3352 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003353 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3354 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3355 /*readyDuration=*/configs.late.sfWorkDuration,
3356 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003357 mInterceptor->saveVSyncEvent(timestamp);
3358 });
3359
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003360 mScheduler->initVsync(mScheduler->getVsyncSchedule().getDispatch(),
3361 *mFrameTimeline->getTokenManager(), configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003362
3363 mRegionSamplingThread =
Ady Abrahamd11bade2022-08-01 16:18:03 -07003364 sp<RegionSamplingThread>::make(*this,
3365 RegionSamplingThread::EnvironmentTimingTunables());
3366 mFpsReporter = sp<FpsReporter>::make(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003367 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003368 // initialization, so that the EventThreads always contain a reference to a
3369 // prior configuration.
3370 //
3371 // This is a bit hacky, but this avoids a back-pointer into the main SF
3372 // classes from EventThread, and there should be no run-time binder cost
3373 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003374 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003375}
3376
Marin Shalamanov5801c942020-12-17 17:00:13 +01003377void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3378 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003379 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003380 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003381}
3382
Ady Abraham55fa7272020-09-30 19:19:27 -07003383void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3384 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003385 mScheduler->setDuration(mAppConnectionHandle,
3386 /*workDuration=*/config.appWorkDuration,
3387 /*readyDuration=*/config.sfWorkDuration);
3388 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003389 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3390 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003391 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003392}
3393
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003394void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003395 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003396
Lloyd Pique58e24a32019-08-01 15:50:14 -07003397 if (!mLayersPendingRemoval.isEmpty()) {
3398 // Notify removed layers now that they can't be drawn from
3399 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003400 // Ensure any buffers set to display on any children are released.
3401 if (l->isRemovedFromCurrentState()) {
3402 l->latchAndReleaseBuffer();
3403 }
3404
chaviw6852bff2022-04-19 17:35:11 -05003405 // If a layer has a parent, we allow it to out-live it's handle
3406 // with the idea that the parent holds a reference and will eventually
3407 // be cleaned up. However no one cleans up the top-level so we do so
3408 // here.
3409 if (l->isAtRoot()) {
3410 l->setIsAtRoot(false);
3411 mCurrentState.layersSortedByZ.remove(l);
3412 }
3413
Lloyd Pique58e24a32019-08-01 15:50:14 -07003414 // If the layer has been removed and has no parent, then it will not be reachable
3415 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3416 // ensure we can copy its current to drawing state.
3417 if (!l->getParent()) {
3418 mOffscreenLayers.emplace(l.get());
3419 }
3420 }
3421 mLayersPendingRemoval.clear();
3422 }
3423
Lloyd Pique58e24a32019-08-01 15:50:14 -07003424 mDrawingState = mCurrentState;
3425 // clear the "changed" flags in current state
3426 mCurrentState.colorMatrixChanged = false;
3427
Robert Carra70e91c2021-06-11 13:59:52 -07003428 if (mVisibleRegionsDirty) {
3429 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3430 rootLayer->commitChildList();
3431 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003432 }
Robert Carra70e91c2021-06-11 13:59:52 -07003433
Lloyd Pique58e24a32019-08-01 15:50:14 -07003434 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003435 if (mNumClones > 0) {
3436 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3437 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003438}
3439
chaviw74d90ad2019-04-26 14:45:26 -07003440void SurfaceFlinger::commitOffscreenLayers() {
3441 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003442 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003443 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3444 layer->doTransaction(0);
3445 layer->commitChildList();
3446 }
chaviw74d90ad2019-04-26 14:45:26 -07003447 });
3448 }
3449}
3450
Chia-I Wuab0c3192017-08-01 11:29:00 -07003451void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003452 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003453 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003454 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003455 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003456 }
3457 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003458}
3459
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003460bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003461 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003462
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003463 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003464
Mathias Agopian4fec8732012-06-29 14:12:52 -07003465 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003466 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003467 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003468
3469 // Store the set of layers that need updates. This set must not change as
3470 // buffers are being latched, as this could result in a deadlock.
3471 // Example: Two producers share the same command stream and:
3472 // 1.) Layer 0 is latched
3473 // 2.) Layer 0 gets a new frame
3474 // 2.) Layer 1 gets a new frame
3475 // 3.) Layer 1 is latched.
3476 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3477 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003478 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003479 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3480 const uint32_t flags = layer->doTransaction(0);
3481 if (flags & Layer::eVisibleRegion) {
3482 mVisibleRegionsDirty = true;
3483 }
3484 }
Robert Carrb552ff52021-06-11 13:35:54 -07003485
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003486 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003487 frameQueued = true;
Ady Abrahamd11bade2022-08-01 16:18:03 -07003488 mLayersWithQueuedFrames.emplace(sp<Layer>::fromExisting(layer));
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003489 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003490 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003491 }
Robert Carr2047fae2016-11-28 14:09:09 -08003492 });
Robert Carrb552ff52021-06-11 13:35:54 -07003493 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003494
chaviw49a108c2019-08-12 11:23:06 -07003495 // The client can continue submitting buffers for offscreen layers, but they will not
3496 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3497 // layers to ensure dequeueBuffer doesn't block indefinitely.
3498 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003499 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003500 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3501 }
3502
Lloyd Piquef2c79392018-12-20 16:23:33 -08003503 if (!mLayersWithQueuedFrames.empty()) {
3504 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3505 // writes to Layer current state. See also b/119481871
3506 Mutex::Autolock lock(mStateLock);
3507
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003508 for (const auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair397a0e32022-07-26 00:01:48 +00003509 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003510 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003511 newDataLatched = true;
3512 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003513 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003514 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003515 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003516
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003517 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003518
3519 // If we will need to wake up at some time in the future to deal with a
3520 // queued frame that shouldn't be displayed during this vsync period, wake
3521 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003522 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003523 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003524 }
3525
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003526 // enter boot animation on first buffer latch
3527 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3528 ALOGI("Enter boot animation");
3529 mBootStage = BootStage::BOOTANIMATION;
3530 }
3531
Robert Carr6a0382d2021-07-01 15:57:17 -07003532 if (mNumClones > 0) {
3533 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3534 }
chaviw74b03172019-08-19 11:09:03 -07003535
Dan Stoza6b9454d2014-11-07 16:00:59 -08003536 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003537 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003538}
3539
Robert Carrc0df3122019-04-11 13:18:21 -07003540status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003541 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003542 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003543 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003544 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003545 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003546 static_cast<void>(mScheduler->schedule([=] {
3547 ALOGE("Dumping random sampling of on-screen layers: ");
3548 mDrawingState.traverse([&](Layer *layer) {
3549 // Aim to dump about 200 layers to avoid totally trashing
3550 // logcat. On the other hand, if there really are 4096 layers
3551 // something has gone totally wrong its probably the most
3552 // useful information in logcat.
3553 if (rand() % 20 == 13) {
3554 ALOGE("Layer: %s", layer->getName().c_str());
3555 }
3556 });
3557 for (Layer* offscreenLayer : mOffscreenLayers) {
3558 if (rand() % 20 == 13) {
3559 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3560 }
3561 }
3562 }));
arthurhungdba591c2021-02-08 17:28:49 +08003563 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003564 }
3565
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003566 {
3567 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3568 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3569 }
arthurhungdba591c2021-02-08 17:28:49 +08003570
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003571 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003572 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003573 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003574 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003575 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003576 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003577 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003578 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003579
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003580 setTransactionFlags(eTransactionNeeded);
3581 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003582}
3583
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003584uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003585 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003586}
3587
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003588uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3589 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590}
3591
Dominik Laskowski94000c42022-03-17 12:55:14 -07003592void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003593 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003594 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003595
3596 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003597 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003598 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003599}
3600
Robert Carr79dc06a2022-02-22 15:28:59 -08003601int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003602 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003603 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003604 bool tryApplyUnsignaled) {
Vishnu Nair55e8f512022-07-20 04:10:32 +00003605 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Robert Carr79dc06a2022-02-22 15:28:59 -08003606 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003607 auto it = mPendingTransactionQueues.begin();
3608 while (it != mPendingTransactionQueues.end()) {
3609 auto& [applyToken, transactionQueue] = *it;
3610 while (!transactionQueue.empty()) {
Vishnu Nair55e8f512022-07-20 04:10:32 +00003611 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3612 // then we should have only one applyToken for processing.
3613 // so we can stop further transactions on this applyToken.
3614 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer &&
3615 !applyTokensWithUnsignaledTransactions.empty()) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003616 ATRACE_NAME("stopTransactionProcessing");
3617 break;
3618 }
3619
3620 auto& transaction = transactionQueue.front();
3621 const auto ready =
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003622 transactionIsReadyToBeApplied(transaction, transaction.frameTimelineInfo,
3623 transaction.isAutoTimestamp,
3624 TimePoint::fromNs(transaction.desiredPresentTime),
3625 transaction.originUid, transaction.states,
3626 bufferLayersReadyToPresent, transactions.size(),
3627 tryApplyUnsignaled);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003628 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3629 if (ready == TransactionReadiness::NotReady) {
3630 setTransactionFlags(eTransactionFlushNeeded);
3631 break;
3632 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003633 if (ready == TransactionReadiness::NotReadyBarrier) {
3634 transactionsPendingBarrier++;
3635 setTransactionFlags(eTransactionFlushNeeded);
3636 break;
3637 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003638 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003639 const bool frameNumberChanged = state.bufferData->flags.test(
3640 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003641 if (frameNumberChanged) {
3642 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3643 } else {
3644 // Barrier function only used for BBQ which always includes a frame number
3645 bufferLayersReadyToPresent[state.surface] =
3646 std::numeric_limits<uint64_t>::max();
3647 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003648 });
3649 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3650 if (appliedUnsignaled) {
3651 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3652 }
3653
3654 transactions.emplace_back(std::move(transaction));
3655 transactionQueue.pop();
Vishnu Nair60d902e2022-07-20 02:55:37 +00003656 mPendingTransactionCount--;
3657 ATRACE_INT("TransactionQueue", mPendingTransactionCount.load());
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003658 }
3659
3660 if (transactionQueue.empty()) {
3661 it = mPendingTransactionQueues.erase(it);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003662 } else {
3663 it = std::next(it, 1);
3664 }
3665 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003666 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003667}
3668
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003669bool SurfaceFlinger::flushTransactionQueues(VsyncId vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003670 // to prevent onHandleDestroyed from being called while the lock is held,
3671 // we must keep a copy of the transactions (specifically the composer
3672 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003673 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003674 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003675 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Valerie Haufce31b82019-04-30 16:41:14 -07003676 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003677 Mutex::Autolock _l(mStateLock);
3678 {
Vishnu Nair60d902e2022-07-20 02:55:37 +00003679 while (!mLocklessTransactionQueue.isEmpty()) {
3680 auto maybeTransaction = mLocklessTransactionQueue.pop();
3681 if (!maybeTransaction.has_value()) {
3682 break;
3683 }
3684 auto transaction = maybeTransaction.value();
Vishnu Nair55e8f512022-07-20 04:10:32 +00003685 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003686 }
Arthur Hung58144272021-01-16 03:43:53 +00003687
Robert Carr79dc06a2022-02-22 15:28:59 -08003688 // Transactions with a buffer pending on a barrier may be on a different applyToken
3689 // than the transaction which satisfies our barrier. In fact this is the exact use case
3690 // that the primitive is designed for. This means we may first process
3691 // the barrier dependent transaction, determine it ineligible to complete
3692 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3693 // The barrier dependent transaction was eligible to be presented in this frame
3694 // but we would have prevented it without case. To fix this we continually
3695 // loop through flushPendingTransactionQueues until we perform an iteration
3696 // where the number of transactionsPendingBarrier doesn't change. This way
3697 // we can continue to resolve dependency chains of barriers as far as possible.
Vishnu Nair55e8f512022-07-20 04:10:32 +00003698 int lastTransactionsPendingBarrier = 0;
3699 int transactionsPendingBarrier = 0;
3700 do {
Robert Carr79dc06a2022-02-22 15:28:59 -08003701 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3702 transactionsPendingBarrier =
Vishnu Nair55e8f512022-07-20 04:10:32 +00003703 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3704 /*tryApplyUnsignaled*/ false);
3705 } while (lastTransactionsPendingBarrier != transactionsPendingBarrier);
Robert Carr79dc06a2022-02-22 15:28:59 -08003706
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003707 // We collected all transactions that could apply without latching unsignaled buffers.
3708 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3709 // transactions that were not applied and try to apply them unsignaled.
3710 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
Vishnu Nair55e8f512022-07-20 04:10:32 +00003711 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3712 /*tryApplyUnsignaled*/ true);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003713 }
3714
Vishnu Nair7891e962021-11-11 12:07:21 -08003715 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003716 }
ramindani4d48f902021-09-20 21:07:45 +00003717 }
3718}
3719
Vishnu Nair7891e962021-11-11 12:07:21 -08003720bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003721 VsyncId vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003722 bool needsTraversal = false;
3723 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003724 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003725 needsTraversal |=
3726 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3727 transaction.displays, transaction.flags,
3728 transaction.inputWindowCommands,
3729 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3730 transaction.buffer, transaction.postTime,
3731 transaction.permissions, transaction.hasListenerCallbacks,
3732 transaction.listenerCallbacks, transaction.originPid,
3733 transaction.originUid, transaction.id);
3734 if (transaction.transactionCommittedSignal) {
3735 mTransactionCommittedSignals.emplace_back(
3736 std::move(transaction.transactionCommittedSignal));
3737 }
3738 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003739
Dominik Laskowski46471e62022-01-14 15:34:03 -08003740 if (mTransactionTracing) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003741 mTransactionTracing->addCommittedTransactions(transactions, vsyncId.value);
Vishnu Nair7891e962021-11-11 12:07:21 -08003742 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003743 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003744}
3745
3746bool SurfaceFlinger::transactionFlushNeeded() {
Vishnu Nair60d902e2022-07-20 02:55:37 +00003747 return !mPendingTransactionQueues.empty() || !mLocklessTransactionQueue.isEmpty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003748}
3749
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003750bool SurfaceFlinger::frameIsEarly(TimePoint expectedPresentTime, VsyncId vsyncId) const {
3751 const auto prediction =
3752 mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId.value);
3753 if (!prediction) {
Ady Abraham8db10102021-03-15 17:19:23 -07003754 return false;
3755 }
3756
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003757 const auto predictedPresentTime = TimePoint::fromNs(prediction->presentTime);
3758
3759 // The duration for which SF can delay a frame if it is considered early based on the
3760 // VsyncModulator::VsyncConfig::appWorkDuration.
3761 if (constexpr std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3762 std::chrono::abs(predictedPresentTime - expectedPresentTime) >= kEarlyLatchMaxThreshold) {
Ady Abraham8db10102021-03-15 17:19:23 -07003763 return false;
3764 }
3765
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003766 const Duration earlyLatchVsyncThreshold = mScheduler->getVsyncSchedule().period() / 2;
3767
3768 return predictedPresentTime >= expectedPresentTime &&
3769 predictedPresentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
Ady Abraham8db10102021-03-15 17:19:23 -07003770}
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003771
Ady Abraham9dada822022-02-03 10:26:59 -08003772bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003773 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003774 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3775 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3776 return false;
3777 }
Ady Abraham8db10102021-03-15 17:19:23 -07003778
Ady Abraham9dada822022-02-03 10:26:59 -08003779 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3780 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3781 return true;
3782 }
3783
3784 // We only want to latch unsignaled when a single layer is updated in this
3785 // transaction (i.e. not a blast sync transaction).
3786 if (numStates != 1) {
3787 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3788 return false;
3789 }
3790
Ady Abraham2739e832022-02-14 17:42:00 -08003791 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3792 if (totalTXapplied > 0) {
3793 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3794 __func__, totalTXapplied);
3795 return false;
3796 }
3797
3798 // We don't want to latch unsignaled if are in early / client composition
3799 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3800 // or window animations being slow.
3801 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3802 if (!isDefaultVsyncConfig) {
3803 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3804 __func__);
3805 return false;
3806 }
Ady Abraham9dada822022-02-03 10:26:59 -08003807 }
3808
3809 if (!layer->simpleBufferUpdate(state)) {
3810 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3811 return false;
3812 }
3813
3814 ALOGV("%s: true", __func__);
3815 return true;
3816}
3817
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003818auto SurfaceFlinger::transactionIsReadyToBeApplied(
3819 TransactionState& transaction, const FrameTimelineInfo& info, bool isAutoTimestamp,
3820 TimePoint desiredPresentTime, uid_t originUid, const Vector<ComposerState>& states,
3821 const std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>&
3822 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003823 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003824 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Marissa Wall17b4e452018-12-26 16:32:34 -08003825 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3826 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003827 if (!isAutoTimestamp && desiredPresentTime >= mExpectedPresentTime &&
3828 desiredPresentTime < mExpectedPresentTime + 1s) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003829 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003830 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003831 }
3832
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003833 if (!mScheduler->isVsyncValid(mExpectedPresentTime, originUid)) {
Ady Abraham5690bda2021-03-12 15:01:18 -08003834 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003835 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003836 }
3837
Ady Abraham8db10102021-03-15 17:19:23 -07003838 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3839 // present time of this transaction.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003840 if (isAutoTimestamp && frameIsEarly(mExpectedPresentTime, VsyncId{info.vsyncId})) {
Ady Abraham8db10102021-03-15 17:19:23 -07003841 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08003842 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07003843 }
3844
Ady Abraham9dada822022-02-03 10:26:59 -08003845 bool fenceUnsignaled = false;
Robert Carr4c1b6462021-12-21 10:30:50 -08003846 auto queueProcessTime = systemTime();
Marissa Wall713b63f2018-10-17 15:42:43 -07003847 for (const ComposerState& state : states) {
3848 const layer_state_t& s = state.state;
Robert Carr4c1b6462021-12-21 10:30:50 -08003849
Ady Abrahamf20c1922020-12-21 18:39:01 -08003850 sp<Layer> layer = nullptr;
3851 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07003852 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003853 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08003854 ALOGW("Transaction with buffer, but no Layer?");
3855 continue;
3856 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003857 if (!layer) {
3858 continue;
3859 }
Ady Abraham43752eb2021-03-04 16:24:25 -08003860
Robert Carr79dc06a2022-02-22 15:28:59 -08003861 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
3862 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
3863 const bool willApplyBarrierFrame =
3864 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
3865 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
3866 if (!willApplyBarrierFrame) {
3867 ATRACE_NAME("NotReadyBarrier");
3868 return TransactionReadiness::NotReadyBarrier;
3869 }
3870 }
3871
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003872 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08003873 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08003874 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
3875 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08003876
3877 const bool acquireFenceChanged = s.bufferData &&
3878 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
3879 s.bufferData->acquireFence;
3880 fenceUnsignaled = fenceUnsignaled ||
3881 (acquireFenceChanged &&
3882 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
3883
3884 if (fenceUnsignaled && !allowLatchUnsignaled) {
Robert Carr4c1b6462021-12-21 10:30:50 -08003885 if (!transaction.sentFenceTimeoutWarning &&
Vishnu Nair55e8f512022-07-20 04:10:32 +00003886 queueProcessTime - transaction.postTime > std::chrono::nanoseconds(4s).count()) {
Robert Carr4c1b6462021-12-21 10:30:50 -08003887 transaction.sentFenceTimeoutWarning = true;
3888 auto listener = s.bufferData->releaseBufferListener;
3889 if (listener) {
3890 listener->onTransactionQueueStalled();
3891 }
3892 }
3893
Ady Abraham9dada822022-02-03 10:26:59 -08003894 ATRACE_NAME("fence unsignaled");
3895 return TransactionReadiness::NotReady;
3896 }
3897
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003898 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08003899 // If backpressure is enabled and we already have a buffer to commit, keep the
3900 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08003901 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
3902 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08003903 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003904 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08003905 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08003906 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003907 }
3908 }
Ady Abraham9dada822022-02-03 10:26:59 -08003909 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07003910}
3911
arthurhungf1b7c7b2021-03-03 17:42:23 +08003912void SurfaceFlinger::queueTransaction(TransactionState& state) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003913 // Generate a CountDownLatch pending state if this is a synchronous transaction.
Patrick Williams641f7f22022-06-22 19:25:35 +00003914 if (state.flags & eSynchronous) {
3915 state.transactionCommittedSignal =
3916 std::make_shared<CountDownLatch>(CountDownLatch::eSyncTransaction);
arthurhungf1b7c7b2021-03-03 17:42:23 +08003917 }
3918
Vishnu Nair60d902e2022-07-20 02:55:37 +00003919 mLocklessTransactionQueue.push(state);
3920 mPendingTransactionCount++;
3921 ATRACE_INT("TransactionQueue", mPendingTransactionCount.load());
Ady Abrahame46243a2021-02-23 19:33:49 -08003922
Ady Abrahame46243a2021-02-23 19:33:49 -08003923 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07003924 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
3925 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08003926 return TransactionSchedule::Late;
3927 }(state.flags);
3928
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003929 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
3930
3931 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08003932}
3933
arthurhungf1b7c7b2021-03-03 17:42:23 +08003934void SurfaceFlinger::waitForSynchronousTransaction(
3935 const CountDownLatch& transactionCommittedSignal) {
3936 // applyTransactionState is called on the main SF thread. While a given process may wish
3937 // to wait on synchronous transactions, the main SF thread should apply the transaction and
3938 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08003939 if (!transactionCommittedSignal.wait_until(
3940 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003941 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08003942 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003943}
Ady Abrahame46243a2021-02-23 19:33:49 -08003944
Arthur Hung2274a312021-04-28 15:13:06 +00003945void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003946 for (auto it = mTransactionCommittedSignals.begin();
3947 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00003948 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003949 it = mTransactionCommittedSignals.erase(it);
3950 } else {
3951 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08003952 }
3953 }
3954}
3955
chaviw308ddba2020-08-11 16:23:51 -07003956status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10003957 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07003958 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
3959 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08003960 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00003961 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003962 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003963
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003964 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08003965 callingThreadHasUnscopedSurfaceFlingerAccess() ?
3966 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003967 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
3968 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08003969 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003970 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08003971 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003972 }
3973
Leon Scroggins9a20f722021-12-28 14:43:12 +00003974 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08003975 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00003976 }
3977
Robert Carrde6d7b42022-01-07 18:23:06 -08003978 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07003979 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
3980 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
3981 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08003982 }
3983
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003984 const int64_t postTime = systemTime();
3985
3986 IPCThreadState* ipc = IPCThreadState::self();
3987 const int originPid = ipc->getCallingPid();
3988 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08003989 TransactionState state{frameTimelineInfo, states,
3990 displays, flags,
3991 applyToken, inputWindowCommands,
3992 desiredPresentTime, isAutoTimestamp,
3993 uncacheBuffer, postTime,
3994 permissions, hasListenerCallbacks,
3995 listenerCallbacks, originPid,
3996 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07003997
3998 // Check for incoming buffer updates and increment the pending buffer count.
3999 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4000 mBufferCountTracker.increment(state.surface->localBinder());
4001 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004002
Dominik Laskowski46471e62022-01-14 15:34:03 -08004003 if (mTransactionTracing) {
4004 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004005 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004006 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004007
arthurhungf1b7c7b2021-03-03 17:42:23 +08004008 // Check the pending state to make sure the transaction is synchronous.
4009 if (state.transactionCommittedSignal) {
4010 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004011 }
4012
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004013 return NO_ERROR;
4014}
Marissa Wall713b63f2018-10-17 15:42:43 -07004015
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004016bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004017 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004018 const Vector<DisplayState>& displays, uint32_t flags,
4019 const InputWindowCommands& inputWindowCommands,
4020 const int64_t desiredPresentTime, bool isAutoTimestamp,
4021 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004022 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004023 bool hasListenerCallbacks,
4024 const std::vector<ListenerCallbacks>& listenerCallbacks,
4025 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004026 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004027 for (const DisplayState& display : displays) {
4028 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004029 }
4030
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004031 // start and end registration for listeners w/ no surface so they can get their callback. Note
4032 // that listeners with SurfaceControls will start registration during setClientStateLocked
4033 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004034 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004035 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004036 }
4037
Marissa Walle2ffb422018-10-12 11:33:52 -07004038 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004039 for (int i = 0; i < states.size(); i++) {
4040 ComposerState& state = states.editItemAt(i);
4041 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004042 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004043 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004044 if (const auto layer = fromHandle(state.state.surface).promote()) {
4045 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004046 mScheduler->recordLayerHistory(layer.get(),
4047 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004048 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004049 }
4050 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004051 }
4052
Marissa Walle2ffb422018-10-12 11:33:52 -07004053 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004054
Robert Carrde6d7b42022-01-07 18:23:06 -08004055 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004056 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4057 } else if (!inputWindowCommands.empty()) {
4058 ALOGE("Only privileged callers are allowed to send input commands.");
4059 }
chaviw273171b2018-12-26 11:46:30 -08004060
Marissa Wall947d34e2019-03-29 14:03:53 -07004061 if (uncacheBuffer.isValid()) {
4062 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004063 }
4064
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004065 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4066 // anyway. This can be used as a flush mechanism for previous async transactions.
4067 // Empty animation transaction can be used to simulate back-pressure, so also force a
4068 // transaction for empty animation transactions.
4069 if (transactionFlags == 0 &&
4070 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004071 transactionFlags = eTransactionNeeded;
4072 }
4073
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004074 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004075 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004076 if (mInterceptor->isEnabled()) {
4077 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004078 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004079 }
4080
Arthur Hung58144272021-01-16 03:43:53 +00004081 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4082 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4083 if (transactionFlags & eTraversalNeeded) {
4084 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004085 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004086 }
Arthur Hung58144272021-01-16 03:43:53 +00004087 if (transactionFlags) {
4088 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004089 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004090 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004091
4092 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004093}
4094
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004095uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4096 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4097 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004098
Mathias Agopiane57f2922012-08-09 16:29:12 -07004099 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004100 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4101
4102 const uint32_t what = s.what;
4103 if (what & DisplayState::eSurfaceChanged) {
4104 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4105 state.surface = s.surface;
4106 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004107 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004108 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004109 if (what & DisplayState::eLayerStackChanged) {
4110 if (state.layerStack != s.layerStack) {
4111 state.layerStack = s.layerStack;
4112 flags |= eDisplayTransactionNeeded;
4113 }
4114 }
Evan Rosky2239b372021-05-20 13:43:47 -07004115 if (what & DisplayState::eFlagsChanged) {
4116 if (state.flags != s.flags) {
4117 state.flags = s.flags;
4118 flags |= eDisplayTransactionNeeded;
4119 }
4120 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004121 if (what & DisplayState::eDisplayProjectionChanged) {
4122 if (state.orientation != s.orientation) {
4123 state.orientation = s.orientation;
4124 flags |= eDisplayTransactionNeeded;
4125 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004126 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4127 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004128 flags |= eDisplayTransactionNeeded;
4129 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004130 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4131 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004132 flags |= eDisplayTransactionNeeded;
4133 }
4134 }
4135 if (what & DisplayState::eDisplaySizeChanged) {
4136 if (state.width != s.width) {
4137 state.width = s.width;
4138 flags |= eDisplayTransactionNeeded;
4139 }
4140 if (state.height != s.height) {
4141 state.height = s.height;
4142 flags |= eDisplayTransactionNeeded;
4143 }
4144 }
4145
Mathias Agopiane57f2922012-08-09 16:29:12 -07004146 return flags;
4147}
4148
Steven Thomasd4071902020-03-24 16:02:53 -07004149bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004150 IPCThreadState* ipc = IPCThreadState::self();
4151 const int pid = ipc->getCallingPid();
4152 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004153 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004154 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4155 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004156 return false;
4157 }
4158 return true;
4159}
4160
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004161uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004162 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004163 int64_t desiredPresentTime, bool isAutoTimestamp,
4164 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004165 layer_state_t& s = composerState.state;
4166 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004167
4168 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004169 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004170 // Starts a registration but separates the callback ids according to callback type. This
4171 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004172 // note that startRegistration will not re-register if the listener has
4173 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004174
4175 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4176 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004177 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004178 }
4179
4180 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4181 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004182 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004183 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004184 }
4185
arthurhungdba591c2021-02-08 17:28:49 +08004186 const uint64_t what = s.what;
4187 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004188 sp<Layer> layer = nullptr;
4189 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004190 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004191 } else {
4192 // The client may provide us a null handle. Treat it as if the layer was removed.
4193 ALOGW("Attempt to set client state with a null layer handle");
4194 }
chaviw8b3871a2017-11-01 17:41:01 -07004195 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004196 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004197 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Ady Abrahamd11bade2022-08-01 16:18:03 -07004198 sp<CallbackHandle>::make(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004199 }
chaviw8b3871a2017-11-01 17:41:01 -07004200 return 0;
4201 }
4202
Valerie Hau871d6352020-01-29 08:44:02 -08004203 // Only set by BLAST adapter layers
4204 if (what & layer_state_t::eProducerDisconnect) {
4205 layer->onDisconnect();
4206 }
4207
chaviw8b3871a2017-11-01 17:41:01 -07004208 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004209 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004210 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004211 }
chaviw8b3871a2017-11-01 17:41:01 -07004212 }
4213 if (what & layer_state_t::eLayerChanged) {
4214 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004215 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004216 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004217 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004218 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004219 mCurrentState.layersSortedByZ.removeAt(idx);
4220 mCurrentState.layersSortedByZ.add(layer);
4221 // we need traversal (state changed)
4222 // AND transaction (list changed)
4223 flags |= eTransactionNeeded|eTraversalNeeded;
4224 }
chaviw8b3871a2017-11-01 17:41:01 -07004225 } else {
4226 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004227 flags |= eTransactionNeeded|eTraversalNeeded;
4228 }
4229 }
chaviw8b3871a2017-11-01 17:41:01 -07004230 }
4231 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004232 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004233 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004234 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4235 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004236 if (p == nullptr) {
4237 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004238 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004239 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004240 mCurrentState.layersSortedByZ.removeAt(idx);
4241 mCurrentState.layersSortedByZ.add(layer);
4242 // we need traversal (state changed)
4243 // AND transaction (list changed)
4244 flags |= eTransactionNeeded|eTraversalNeeded;
4245 }
4246 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004247 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004248 flags |= eTransactionNeeded|eTraversalNeeded;
4249 }
chaviw8b3871a2017-11-01 17:41:01 -07004250 }
4251 }
4252 if (what & layer_state_t::eSizeChanged) {
4253 if (layer->setSize(s.w, s.h)) {
4254 flags |= eTraversalNeeded;
4255 }
4256 }
4257 if (what & layer_state_t::eAlphaChanged) {
4258 if (layer->setAlpha(s.alpha))
4259 flags |= eTraversalNeeded;
4260 }
4261 if (what & layer_state_t::eColorChanged) {
4262 if (layer->setColor(s.color))
4263 flags |= eTraversalNeeded;
4264 }
Peiyong Lind3788632018-09-18 16:01:31 -07004265 if (what & layer_state_t::eColorTransformChanged) {
4266 if (layer->setColorTransform(s.colorTransform)) {
4267 flags |= eTraversalNeeded;
4268 }
4269 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004270 if (what & layer_state_t::eBackgroundColorChanged) {
4271 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4272 flags |= eTraversalNeeded;
4273 }
4274 }
chaviw8b3871a2017-11-01 17:41:01 -07004275 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004276 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004277 }
4278 if (what & layer_state_t::eTransparentRegionChanged) {
4279 if (layer->setTransparentRegionHint(s.transparentRegion))
4280 flags |= eTraversalNeeded;
4281 }
4282 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004283 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004284 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004285 if (what & layer_state_t::eCornerRadiusChanged) {
4286 if (layer->setCornerRadius(s.cornerRadius))
4287 flags |= eTraversalNeeded;
4288 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004289 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004290 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4291 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004292 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004293 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4294 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004295 if (what & layer_state_t::eRenderBorderChanged) {
Tianhao Yao10cea3c2022-03-30 01:37:22 +00004296 if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00004297 flags |= eTraversalNeeded;
4298 }
4299 }
chaviw8b3871a2017-11-01 17:41:01 -07004300 if (what & layer_state_t::eLayerStackChanged) {
4301 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4302 // We only allow setting layer stacks for top level layers,
4303 // everything else inherits layer stack from its parent.
4304 if (layer->hasParent()) {
4305 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004306 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004307 } else if (idx < 0) {
4308 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004309 "that also does not appear in the top level layer list. Something"
4310 " has gone wrong.",
4311 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004312 } else if (layer->setLayerStack(s.layerStack)) {
4313 mCurrentState.layersSortedByZ.removeAt(idx);
4314 mCurrentState.layersSortedByZ.add(layer);
4315 // we need traversal (state changed)
4316 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004317 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004318 }
4319 }
Marissa Wall61c58622018-07-18 10:12:20 -07004320 if (what & layer_state_t::eTransformChanged) {
4321 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4322 }
4323 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4324 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4325 flags |= eTraversalNeeded;
4326 }
4327 if (what & layer_state_t::eCropChanged) {
4328 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4329 }
Marissa Wall61c58622018-07-18 10:12:20 -07004330 if (what & layer_state_t::eDataspaceChanged) {
4331 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4332 }
4333 if (what & layer_state_t::eHdrMetadataChanged) {
4334 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4335 }
4336 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4337 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4338 }
4339 if (what & layer_state_t::eApiChanged) {
4340 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4341 }
4342 if (what & layer_state_t::eSidebandStreamChanged) {
4343 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4344 }
Robert Carr720e5062018-07-30 17:45:14 -07004345 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004346 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4347 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004348 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004349 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004350 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004351 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004352
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004353 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4354 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004355 // The transaction will be received on the Task layer and needs to be applied to all
4356 // child layers. Child layers that are added at a later point will obtain the game mode
4357 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004358 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004359 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004360
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004361 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4362 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004363 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4364 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4365 flags |= eTraversalNeeded;
4366 }
4367 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004368 if (what & layer_state_t::eShadowRadiusChanged) {
4369 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4370 }
Andy Labrada096227e2022-06-15 16:58:11 +00004371 if (what & layer_state_t::eDefaultFrameRateCompatibilityChanged) {
4372 const auto compatibility =
4373 Layer::FrameRate::convertCompatibility(s.defaultFrameRateCompatibility);
4374
4375 if (layer->setDefaultFrameRateCompatibility(compatibility)) {
4376 flags |= eTraversalNeeded;
4377 }
4378 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004379 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004380 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004381 flags |= eTraversalNeeded;
4382 }
4383 }
Steven Thomas3172e202020-01-06 19:25:30 -08004384 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004385 const auto compatibility =
4386 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4387 const auto strategy =
4388 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004389
Robert Carrde6d7b42022-01-07 18:23:06 -08004390 if (layer->setFrameRate(
4391 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4392 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004393 }
Steven Thomas3172e202020-01-06 19:25:30 -08004394 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004395 if (what & layer_state_t::eFixedTransformHintChanged) {
4396 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4397 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4398 }
4399 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004400 if (what & layer_state_t::eAutoRefreshChanged) {
4401 layer->setAutoRefresh(s.autoRefresh);
4402 }
Sally Qi421ffb02022-03-21 19:41:33 -07004403 if (what & layer_state_t::eDimmingEnabledChanged) {
4404 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4405 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004406 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004407 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4408 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004409 }
4410 }
John Reckcdb4ed72021-02-04 13:39:33 -05004411 if (what & layer_state_t::eStretchChanged) {
4412 if (layer->setStretchEffect(s.stretchEffect)) {
4413 flags |= eTraversalNeeded;
4414 }
4415 }
chaviwf3f40fe2021-04-27 15:54:02 -05004416 if (what & layer_state_t::eBufferCropChanged) {
4417 if (layer->setBufferCrop(s.bufferCrop)) {
4418 flags |= eTraversalNeeded;
4419 }
4420 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004421 if (what & layer_state_t::eDestinationFrameChanged) {
4422 if (layer->setDestinationFrame(s.destinationFrame)) {
4423 flags |= eTraversalNeeded;
4424 }
4425 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004426 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004427 if (layer->setDropInputMode(s.dropInputMode)) {
4428 flags |= eTraversalNeeded;
Arthur Hung9ed43392022-05-27 06:31:57 +00004429 mUpdateInputInfo = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004430 }
4431 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004432 // This has to happen after we reparent children because when we reparent to null we remove
4433 // child layers from current state and remove its relative z. If the children are reparented in
4434 // the same transaction, then we have to make sure we reparent the children first so we do not
4435 // lose its relative z order.
4436 if (what & layer_state_t::eReparent) {
4437 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004438 auto parentHandle = (s.parentSurfaceControlForChild)
4439 ? s.parentSurfaceControlForChild->getHandle()
4440 : nullptr;
4441 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004442 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004443 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004444 mCurrentState.layersSortedByZ.remove(layer);
4445 }
4446 flags |= eTransactionNeeded | eTraversalNeeded;
4447 }
4448 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004449 std::vector<sp<CallbackHandle>> callbackHandles;
4450 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4451 for (auto& [listener, callbackIds] : filteredListeners) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07004452 callbackHandles.emplace_back(
4453 sp<CallbackHandle>::make(listener, callbackIds, s.surface));
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004454 }
4455 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004456
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004457 if (what & layer_state_t::eBufferChanged) {
4458 std::shared_ptr<renderengine::ExternalTexture> buffer =
4459 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4460 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4461 dequeueBufferTimestamp, frameTimelineInfo)) {
4462 flags |= eTraversalNeeded;
4463 }
Ady Abraham8db10102021-03-15 17:19:23 -07004464 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4465 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004466 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004467
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004468 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004469 // Do not put anything that updates layer state or modifies flags after
4470 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004471 return flags;
4472}
4473
chaviw273171b2018-12-26 11:46:30 -08004474uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004475 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004476 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004477}
4478
Vishnu Nair84125ac2021-12-02 08:47:48 -08004479status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4480 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4481 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004482 if (!mirrorFromHandle) {
4483 return NAME_NOT_FOUND;
4484 }
4485
4486 sp<Layer> mirrorLayer;
4487 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004488 {
4489 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004490 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004491 if (!mirrorFrom) {
4492 return NAME_NOT_FOUND;
4493 }
Vishnu Nairb21272e2022-07-01 22:47:33 +00004494 LayerCreationArgs mirrorArgs = args;
4495 mirrorArgs.flags |= ISurfaceComposerClient::eNoColorFill;
4496 status_t result = createEffectLayer(mirrorArgs, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004497 if (result != NO_ERROR) {
4498 return result;
4499 }
4500
Robert Carr6a0382d2021-07-01 15:57:17 -07004501 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004502 }
4503
Ady Abraham9f0a4002020-10-05 15:47:26 -07004504 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004505 if (mTransactionTracing) {
4506 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4507 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004508 }
4509 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004510 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004511}
4512
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00004513status_t SurfaceFlinger::mirrorDisplay(DisplayId displayId, const LayerCreationArgs& args,
4514 sp<IBinder>* outHandle, int32_t* outLayerId) {
4515 IPCThreadState* ipc = IPCThreadState::self();
4516 const int uid = ipc->getCallingUid();
4517 if (uid != AID_ROOT && uid != AID_GRAPHICS && uid != AID_SYSTEM && uid != AID_SHELL) {
4518 ALOGE("Permission denied when trying to mirror display");
4519 return PERMISSION_DENIED;
4520 }
4521
4522 ui::LayerStack layerStack;
4523 sp<Layer> rootMirrorLayer;
4524 status_t result = 0;
4525
4526 {
4527 Mutex::Autolock lock(mStateLock);
4528
4529 const auto display = getDisplayDeviceLocked(displayId);
4530 if (!display) {
4531 return NAME_NOT_FOUND;
4532 }
4533
4534 layerStack = display->getLayerStack();
4535 LayerCreationArgs mirrorArgs = args;
4536 mirrorArgs.flags |= ISurfaceComposerClient::eNoColorFill;
4537 result = createEffectLayer(mirrorArgs, outHandle, &rootMirrorLayer);
4538 *outLayerId = rootMirrorLayer->sequence;
4539 result |= addClientLayer(args.client, *outHandle, rootMirrorLayer /* layer */,
4540 nullptr /* parent */, true /* addToRoot */,
4541 nullptr /* outTransformHint */);
4542 }
4543
4544 if (result != NO_ERROR) {
4545 return result;
4546 }
4547
4548 if (mTransactionTracing) {
4549 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), *outLayerId, args.name,
4550 args.flags, -1 /* parentId */);
4551 }
4552
4553 {
4554 std::scoped_lock<std::mutex> lock(mMirrorDisplayLock);
4555 mMirrorDisplays.emplace_back(layerStack, *outHandle, args.client);
4556 }
4557
4558 setTransactionFlags(eTransactionFlushNeeded);
4559 return NO_ERROR;
4560}
4561
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004562status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004563 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4564 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004565 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4566 "Expected only one of parentLayer or parentHandle to be non-null. "
4567 "Programmer error?");
4568
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004569 status_t result = NO_ERROR;
4570
4571 sp<Layer> layer;
4572
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004573 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004574 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004575 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004576 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004577 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4578 if (pendingBufferCounter) {
4579 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004580 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004581 pendingBufferCounter);
4582 }
4583 } break;
Vishnu Nair29810f72022-07-01 16:38:41 +00004584 case ISurfaceComposerClient::eFXSurfaceContainer:
4585 args.flags |= ISurfaceComposerClient::eNoColorFill;
4586 FMT_FALLTHROUGH;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004587 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004588 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004589 break;
4590 default:
4591 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004592 break;
4593 }
4594
Dan Stoza7d89d062015-04-30 13:29:25 -07004595 if (result != NO_ERROR) {
4596 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004597 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004598
Vishnu Nair858a3b42022-01-12 20:42:28 -08004599 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004600 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4601 if (parentHandle != nullptr && parent == nullptr) {
4602 ALOGE("Invalid parent handle %p.", parentHandle.get());
4603 addToRoot = false;
4604 }
4605 if (parentLayer != nullptr) {
4606 addToRoot = false;
4607 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004608
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004609 int parentId = -1;
4610 // We can safely promote the layer in binder thread because we have a strong reference
4611 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4612 sp<Layer> parentSp = parent.promote();
4613 if (parentSp != nullptr) {
4614 parentId = parentSp->getSequence();
4615 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004616 if (mTransactionTracing) {
4617 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4618 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004619 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004620
Vishnu Nair047fb332021-12-09 09:54:36 -08004621 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4622 if (result != NO_ERROR) {
4623 return result;
4624 }
4625
Ady Abraham9f0a4002020-10-05 15:47:26 -07004626 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004627 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004628}
4629
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004630status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004631 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004632 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004633 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004634 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004635 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004636}
4637
Vishnu Nair84125ac2021-12-02 08:47:48 -08004638status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004639 sp<Layer>* outLayer) {
4640 *outLayer = getFactory().createEffectLayer(args);
4641 *handle = (*outLayer)->getHandle();
4642 return NO_ERROR;
4643}
4644
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004645void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004646 mLayersPendingRemoval.add(layer);
4647 mLayersRemoved = true;
4648 setTransactionFlags(eTransactionNeeded);
4649}
4650
Vishnu Nairf9096652021-07-20 18:49:42 -07004651void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004652 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004653 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004654 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004655 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004656 if (mTransactionTracing) {
4657 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004658 }
Rob Carr4bba3702018-10-08 21:53:30 +00004659}
4660
Mathias Agopianb60314a2012-04-10 22:09:54 -07004661// ---------------------------------------------------------------------------
4662
Andy McFadden13a082e2012-08-24 10:16:42 -07004663void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004664 const auto display = getDefaultDisplayDeviceLocked();
4665 if (!display) return;
4666
4667 const sp<IBinder> token = display->getDisplayToken().promote();
4668 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004669
Jesse Hall01e29052013-02-19 16:13:35 -08004670 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004671 Vector<ComposerState> state;
4672 Vector<DisplayState> displays;
4673 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004674 d.what = DisplayState::eDisplayProjectionChanged |
4675 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004676 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004677 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004678 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004679 d.orientedDisplaySpaceRect.makeInvalid();
4680 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004681 d.width = 0;
4682 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004683 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004684
Vishnu Nair9a69a042021-06-18 13:19:49 -07004685 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004686
4687 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004688 // It should be on the main thread, apply it directly.
4689 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004690 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004691 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004692
Peiyong Lin65248e02020-04-18 21:15:07 -07004693 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski66296b22022-07-12 08:20:36 -07004694
Ady Abraham1273ac12021-08-26 17:31:53 -07004695 mActiveDisplayTransformHint = display->getTransformHint();
Andy McFadden13a082e2012-08-24 10:16:42 -07004696}
4697
4698void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004699 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004700 static_cast<void>(
4701 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004702}
4703
Peiyong Lin65248e02020-04-18 21:15:07 -07004704void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004705 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004706 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004707 return;
4708 }
4709
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004710 const auto displayId = display->getPhysicalId();
4711 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004712
Peiyong Lin65248e02020-04-18 21:15:07 -07004713 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004714 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004715 return;
4716 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004717
Ady Abraham4f960d12021-10-13 16:59:49 -07004718 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4719 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4720 activeDisplay->isPoweredOn()) {
4721 ALOGW("Trying to change power mode on non active display while the active display is ON");
4722 }
4723
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004724 display->setPowerMode(mode);
4725
Lloyd Pique4dccc412018-01-22 17:21:36 -08004726 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004727 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004728 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004729 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004730 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004731 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004732 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004733 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004734 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004735 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4736 // We can merge the syscall later.
4737 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4738 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4739 }
Martin Liu4a322352020-03-24 21:30:38 +08004740 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4741 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4742 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004743 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004744 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004745 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004746 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004747 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004748 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004749
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004750 mVisibleRegionsDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004751 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004752 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004753 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004754 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4755 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004756 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004757 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4758 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4759 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004760 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004761 mScheduler->disableHardwareVsync(true);
4762 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004763 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004764
Ady Abraham27c70212019-06-11 10:52:26 -07004765 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004766 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004767
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004768 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004769 mVisibleRegionsDirty = true;
4770 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004771 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004772 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004773 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004774 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Yifei Zhangf0bd62e2021-06-16 15:27:05 -07004775 ALOGI("Force repainting for DOZE_SUSPEND -> DOZE or ON.");
4776 mVisibleRegionsDirty = true;
4777 scheduleRepaint();
Ana Krulecc2870422019-01-29 19:00:58 -08004778 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004779 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004780 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004781 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004782 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004783 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004784 mScheduler->disableHardwareVsync(true);
4785 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004786 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004787 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004788 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004789 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004790 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004791 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004792
Ady Abrahamadc914c2021-10-13 17:04:27 -07004793 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004794 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004795 mRefreshRateStats->setPowerMode(mode);
Rachel Lee6a9731d2022-06-06 17:08:14 -07004796 mScheduler->setDisplayPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004797 }
4798
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004799 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004800}
4801
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004802void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004803 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004804 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004805 if (!display) {
4806 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4807 displayToken.get());
4808 } else if (display->isVirtual()) {
4809 ALOGW("Attempt to set power mode %d for virtual display", mode);
4810 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004811 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004812 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004813 });
4814
4815 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004816}
4817
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004818status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004819 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004820
Mathias Agopianbd115332013-04-18 16:41:04 -07004821 IPCThreadState* ipc = IPCThreadState::self();
4822 const int pid = ipc->getCallingPid();
4823 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004824
Mathias Agopianbd115332013-04-18 16:41:04 -07004825 if ((uid != AID_SHELL) &&
4826 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004827 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4828 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004829 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004830 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004831 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004832 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004833 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004834 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004835 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004836 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4837 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4838 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004839 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004840 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004841 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004842 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004843 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Ady Abraham5ad28d62022-08-11 11:26:57 -07004844 {"--hwclayers"s, dumper(&SurfaceFlinger::dumpHwcLayersMinidumpLocked)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004845 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004846
Dominik Laskowskic2867142019-01-21 11:33:38 -08004847 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004848
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004849 bool dumpLayers = true;
4850 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004851 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004852 if (!lock.locked()) {
4853 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4854 strerror(-lock.status), lock.status);
4855 }
4856
4857 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4858 (it->second)(args, asProto, result);
4859 dumpLayers = false;
4860 } else if (!asProto) {
4861 dumpAllLocked(args, result);
4862 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004863 }
4864
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004865 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004866 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05004867 LayersTraceProto* layersTrace = traceFileProto.add_entry();
4868 LayersProto layersProto = dumpProtoFromMainThread();
4869 layersTrace->mutable_layers()->Swap(&layersProto);
4870 dumpDisplayProto(*layersTrace);
4871
Dominik Laskowski46470112019-08-02 13:13:11 -07004872 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05004873 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07004874 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004875 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05004876 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07004877 result.append(LayerProtoParser::layerTreeToString(layerTree));
4878 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004879 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004880 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004881 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004882 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004883 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004884 return NO_ERROR;
4885}
4886
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004887status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08004888 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004889 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004890 if (mTransactionTracing) {
4891 mTransactionTracing->writeToFile();
4892 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004893 }
4894
4895 return doDump(fd, DumpArgs(), asProto);
4896}
4897
Dominik Laskowskic2867142019-01-21 11:33:38 -08004898void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004899 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004900 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004901}
4902
Dominik Laskowskic2867142019-01-21 11:33:38 -08004903void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07004904 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Dominik Laskowski66296b22022-07-12 08:20:36 -07004905 if (args.size() < 2) return;
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004906
Dominik Laskowski66296b22022-07-12 08:20:36 -07004907 const auto name = String8(args[1]);
4908 mCurrentState.traverseInZOrder([&](Layer* layer) {
4909 if (layer->getName() == name.string()) {
4910 layer->dumpFrameStats(result);
4911 }
4912 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004913}
4914
Dominik Laskowskic2867142019-01-21 11:33:38 -08004915void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004916 const bool clearAll = args.size() < 2;
4917 const auto name = clearAll ? String8() : String8(args[1]);
4918
Edgar Arriaga844fa672020-01-16 14:21:42 -08004919 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004920 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004921 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004922 }
Robert Carr2047fae2016-11-28 14:09:09 -08004923 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004924}
4925
Dominik Laskowskic2867142019-01-21 11:33:38 -08004926void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4927 mTimeStats->parseArgs(asProto, args, result);
4928}
4929
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004930void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
4931 mFrameTimeline->parseArgs(args, result);
4932}
4933
Dominik Laskowski8792c112022-07-12 09:03:39 -07004934void SurfaceFlinger::logFrameStats(TimePoint now) {
Dominik Laskowski8792c112022-07-12 09:03:39 -07004935 static TimePoint sTimestamp = now;
4936 if (now - sTimestamp < 30min) return;
4937 sTimestamp = now;
4938
4939 ATRACE_CALL();
Dominik Laskowski66296b22022-07-12 08:20:36 -07004940 mDrawingState.traverse([&](Layer* layer) { layer->logFrameStats(); });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004941}
4942
Yiwei Zhang5434a782018-12-05 18:06:32 -08004943void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004944 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004945
Yiwei Zhang5434a782018-12-05 18:06:32 -08004946 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4947 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08004948 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
4949 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004950 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4951 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4952 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004953 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004954}
4955
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004956void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004957 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004958
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004959 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004960 result.append("\n");
4961
Ady Abraham8287e852020-08-12 14:44:58 -07004962 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004963 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004964 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07004965 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004966
Marin Shalamanova7fe3042021-01-29 21:02:08 +01004967 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
4968 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004969
Ana Krulecc2870422019-01-29 19:00:58 -08004970 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07004971 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07004972 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
4973 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004974}
4975
Dan Stoza269dc4d2021-01-15 15:07:43 -08004976void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
4977 for (const auto& [token, display] : mDisplays) {
4978 const auto compositionDisplay = display->getCompositionDisplay();
4979 compositionDisplay->dumpPlannerInfo(args, result);
4980 }
4981}
4982
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004983void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
4984 for (const auto& [token, display] : mDisplays) {
4985 display->getCompositionDisplay()->dump(result);
4986 result += '\n';
4987 }
4988}
4989
4990void SurfaceFlinger::dumpDisplays(std::string& result) const {
4991 for (const auto& [token, display] : mDisplays) {
4992 display->dump(result);
4993 result += '\n';
4994 }
4995}
4996
Yiwei Zhang5434a782018-12-05 18:06:32 -08004997void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004998 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004999 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005000 if (!displayId) {
5001 continue;
5002 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005003 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005004 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005005 continue;
5006 }
5007
Yiwei Zhang5434a782018-12-05 18:06:32 -08005008 StringAppendF(&result,
5009 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5010 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005011 uint8_t port;
5012 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005013 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005014 result.append("no identification data\n");
5015 continue;
5016 }
5017
5018 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005019 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005020 continue;
5021 }
5022
5023 const auto edid = parseEdid(data);
5024 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005025 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005026 continue;
5027 }
5028
Yiwei Zhang5434a782018-12-05 18:06:32 -08005029 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005030 result.append(edid->displayName.data(), edid->displayName.length());
5031 result.append("\"\n");
5032 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005033}
5034
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005035void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5036 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005037 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005038 uint8_t port;
5039 DisplayIdentificationData data;
5040
5041 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5042 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5043 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5044 }
5045}
5046
Yiwei Zhang5434a782018-12-05 18:06:32 -08005047void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005048 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005049 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5050 StringAppendF(&result, "DisplayColorSetting: %s\n",
5051 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005052
5053 // TODO: print out if wide-color mode is active or not
5054
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005055 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005056 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005057 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005058 continue;
5059 }
5060
Yiwei Zhang5434a782018-12-05 18:06:32 -08005061 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005062 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005063 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005064 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005065 }
5066
Lloyd Pique32cbe282018-10-19 13:09:22 -07005067 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005068 StringAppendF(&result, " Current color mode: %s (%d)\n",
5069 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005070 }
5071 result.append("\n");
5072}
5073
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005074LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005075 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005076 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005077 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005078 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005079
chaviw1d044282017-09-27 12:19:28 -07005080 return layersProto;
5081}
5082
chaviw0a398992021-08-13 10:13:01 -05005083void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005084 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005085 DisplayProto* displayProto = layersTraceProto.add_displays();
5086 displayProto->set_id(display->getId().value);
5087 displayProto->set_name(display->getDisplayName());
5088 displayProto->set_layer_stack(display->getLayerStack().id);
5089 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5090 [&]() { return displayProto->mutable_size(); });
5091 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5092 return displayProto->mutable_layer_stack_space_rect();
5093 });
5094 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5095 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005096 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005097 }
5098}
5099
Alec Mouri6b9e9912020-01-21 10:50:24 -08005100void SurfaceFlinger::dumpHwc(std::string& result) const {
5101 getHwComposer().dump(result);
5102}
5103
Vishnu Nair0f085c62019-08-30 08:49:12 -07005104void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5105 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5106 // it.
5107 LayerProto* rootProto = layersProto.add_layers();
5108 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5109 rootProto->set_id(offscreenRootLayerId);
5110 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005111 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005112
5113 for (Layer* offscreenLayer : mOffscreenLayers) {
5114 // Add layer as child of the fake root
5115 rootProto->add_children(offscreenLayer->sequence);
5116
5117 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005118 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005119 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005120 }
5121}
5122
Vishnu Nair8406fd72019-07-30 11:29:31 -07005123LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005124 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005125}
5126
Vishnu Nair0f085c62019-08-30 08:49:12 -07005127void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005128 auto future = mScheduler->schedule([this] {
5129 std::string result;
5130 for (Layer* offscreenLayer : mOffscreenLayers) {
5131 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5132 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5133 }
5134 return result;
5135 });
5136
Vishnu Nair0f085c62019-08-30 08:49:12 -07005137 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005138 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005139}
5140
Ady Abraham5ad28d62022-08-11 11:26:57 -07005141void SurfaceFlinger::dumpHwcLayersMinidumpLocked(std::string& result) const {
5142 for (const auto& [token, display] : mDisplays) {
5143 const auto displayId = HalDisplayId::tryCast(display->getId());
5144 if (!displayId) {
5145 continue;
5146 }
5147
5148 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5149 (isDisplayActiveLocked(display) ? "active" : "inactive"));
5150 Layer::miniDumpHeader(result);
5151
5152 const DisplayDevice& ref = *display;
5153 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
5154 result.append("\n");
5155 }
5156}
5157
Dominik Laskowskic2867142019-01-21 11:33:38 -08005158void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5159 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005160 Colorizer colorizer(colorize);
5161
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005162 // figure out if we're stuck somewhere
5163 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005164 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005165 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5166
5167 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005168 * Dump library configuration.
5169 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005170
5171 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005172 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005173 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005174 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005175 result.append("\n");
5176
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005177 result.append("\nDisplay identification data:\n");
5178 dumpDisplayIdentificationData(result);
5179
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005180 result.append("\nWide-Color information:\n");
5181 dumpWideColorInfo(result);
5182
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005183 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005184 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005185 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005186 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005187 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005188
Andy McFadden41d67d72014-04-25 16:58:34 -07005189 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005190 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005191 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005192 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005193 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005194
Alec Mouri40189b02019-03-05 15:07:54 -08005195 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5196 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5197 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005198
Andy McFadden4803b742012-09-24 19:07:20 -07005199 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005200 * Dump the visible layer list
5201 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005202 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005203 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005204 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005205
Chia-I Wu2f884132018-09-13 15:17:58 -07005206 {
Lloyd Pique207def92019-02-28 16:09:52 -08005207 StringAppendF(&result, "Composition layers\n");
5208 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005209 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005210 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005211
5212 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5213 layer->getDebugName() ? layer->getDebugName()
5214 : "<unknown>");
5215 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005216 });
5217 }
5218
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005219 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005220 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005221 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005222 dumpDisplays(result);
5223 dumpCompositionDisplays(result);
5224 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005225
5226 mCompositionEngine->dump(result);
5227
5228 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005229 * Dump SurfaceFlinger global state
5230 */
5231
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005232 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005233 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005234 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005235
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005236 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005237
Robert Carrbeba6f02021-02-10 21:06:27 -08005238 result.append("ClientCache state:\n");
5239 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005240 DebugEGLImageTracker::getInstance()->dump(result);
5241
Dominik Laskowski075d3172018-05-24 15:50:06 -07005242 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005243 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5244 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005245 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5246 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005247 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005248 StringAppendF(&result,
5249 " transaction-flags : %08x\n"
5250 " gpu_to_cpu_unsupported : %d\n",
5251 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005252
Marin Shalamanov045b7002021-01-07 16:56:24 +01005253 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005254 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005255 if (const auto activeMode = display->getActiveMode()) {
5256 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005257
5258 const auto dpi = activeMode->getDpi();
5259 xDpi = base::StringPrintf("%.2f", dpi.x);
5260 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005261 } else {
5262 fps = "unknown";
5263 xDpi = "unknown";
5264 yDpi = "unknown";
5265 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005266 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005267 " refresh-rate : %s\n"
5268 " x-dpi : %s\n"
5269 " y-dpi : %s\n",
5270 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005271 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005272
Yiwei Zhang5434a782018-12-05 18:06:32 -08005273 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005274
Dan Stozae22aec72016-08-01 13:20:59 -07005275 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005276 * Tracing state
5277 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005278 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005279
5280 result.append("\nTransaction tracing: ");
5281 if (mTransactionTracing) {
5282 result.append("enabled\n");
5283 mTransactionTracing->dump(result);
5284 } else {
5285 result.append("disabled\n");
5286 }
5287 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005288
Ady Abraham5ad28d62022-08-11 11:26:57 -07005289 dumpHwcLayersMinidumpLocked(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005290
Ady Abraham2790e9f2021-04-28 13:14:20 -07005291 {
5292 DumpArgs plannerArgs;
5293 plannerArgs.add(); // first argument is ignored
5294 plannerArgs.add(String16("--layers"));
5295 dumpPlannerInfo(plannerArgs, result);
5296 }
5297
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005298 /*
5299 * Dump HWComposer state
5300 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005301 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005302 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005303 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005304 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005305 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005306 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005307
5308 /*
5309 * Dump gralloc state
5310 */
5311 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5312 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005313
rnleea2ecd832021-07-29 13:58:30 -07005314 /*
5315 * Dump flag/property manager state
5316 */
Robert Carr9b623c32022-03-21 15:55:22 -07005317 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005318
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005319 result.append(mTimeStats->miniDump());
5320 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005321}
5322
chaviw17ac24b2021-01-28 18:50:05 -08005323mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5324 if (saturation == 1) {
5325 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005326 }
5327
chaviw17ac24b2021-01-28 18:50:05 -08005328 float3 luminance{0.213f, 0.715f, 0.072f};
5329 luminance *= 1.0f - saturation;
5330 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5331 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5332 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5333 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5334 return saturationMatrix;
5335}
5336
5337void SurfaceFlinger::updateColorMatrixLocked() {
5338 mat4 colorMatrix =
5339 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5340
Chia-I Wu28f320b2018-05-03 11:02:56 -07005341 if (mCurrentState.colorMatrix != colorMatrix) {
5342 mCurrentState.colorMatrix = colorMatrix;
5343 mCurrentState.colorMatrixChanged = true;
5344 setTransactionFlags(eTransactionNeeded);
5345 }
5346}
5347
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005348status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005349#pragma clang diagnostic push
5350#pragma clang diagnostic error "-Wswitch-enum"
5351 switch (static_cast<ISurfaceComposerTag>(code)) {
5352 // These methods should at minimum make sure that the client requested
5353 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005354 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005355 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005356 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005357 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005358 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5359 // permission dynamically. Don't use the permission cache for this check.
5360 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005361 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005362 IPCThreadState* ipc = IPCThreadState::self();
5363 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5364 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005365 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005366 }
Robert Carr1db73f62016-12-21 12:58:51 -08005367 return OK;
5368 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005369 // The following calls are currently used by clients that do not
5370 // request necessary permissions. However, they do not expose any secret
5371 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005372 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005373 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005374 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005375 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005376 // Calling setTransactionState is safe, because you need to have been
5377 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005378 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005379 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005380 return OK;
5381 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005382 case BOOT_FINISHED:
5383 // Used by apps to hook Choreographer to SurfaceFlinger.
5384 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005385 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005386 case CREATE_DISPLAY:
5387 case DESTROY_DISPLAY:
5388 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5389 case GET_PHYSICAL_DISPLAY_IDS:
5390 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005391 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005392 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005393 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005394 case GET_DISPLAY_STATE:
5395 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005396 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005397 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005398 case GET_DISPLAY_NATIVE_PRIMARIES:
5399 case SET_ACTIVE_COLOR_MODE:
5400 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005401 case CLEAR_BOOT_DISPLAY_MODE:
5402 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5403 case SET_AUTO_LOW_LATENCY_MODE:
5404 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005405 case CAPTURE_LAYERS:
5406 case CAPTURE_DISPLAY:
5407 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005408 case CLEAR_ANIMATION_FRAME_STATS:
5409 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005410 case OVERRIDE_HDR_TYPES:
5411 case ON_PULL_ATOM:
5412 case ENABLE_VSYNC_INJECTIONS:
5413 case INJECT_VSYNC:
5414 case GET_LAYER_DEBUG_INFO:
5415 case GET_COLOR_MANAGEMENT:
5416 case GET_COMPOSITION_PREFERENCE:
5417 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5418 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005419 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005420 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005421 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005422 case ADD_REGION_SAMPLING_LISTENER:
5423 case REMOVE_REGION_SAMPLING_LISTENER:
5424 case ADD_FPS_LISTENER:
5425 case REMOVE_FPS_LISTENER:
5426 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5427 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5428 case ADD_WINDOW_INFOS_LISTENER:
5429 case REMOVE_WINDOW_INFOS_LISTENER:
5430 case SET_DESIRED_DISPLAY_MODE_SPECS:
5431 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005432 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5433 case SET_DISPLAY_BRIGHTNESS:
5434 case ADD_HDR_LAYER_INFO_LISTENER:
5435 case REMOVE_HDR_LAYER_INFO_LISTENER:
5436 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005437 case SET_GLOBAL_SHADOW_SETTINGS:
5438 case GET_DISPLAY_DECORATION_SUPPORT:
5439 case SET_FRAME_RATE:
5440 case SET_OVERRIDE_FRAME_RATE:
5441 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005442 case ADD_TRANSACTION_TRACE_LISTENER:
5443 case GET_GPU_CONTEXT_PRIORITY:
5444 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005445 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005446 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005447 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005448
5449 // These codes are used for the IBinder protocol to either interrogate the recipient
5450 // side of the transaction for its canonical interface descriptor or to dump its state.
5451 // We let them pass by default.
5452 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5453 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5454 code == IBinder::SYSPROPS_TRANSACTION) {
5455 return OK;
5456 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005457 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005458 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005459 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005460 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5461 return OK;
5462 }
5463 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5464 return PERMISSION_DENIED;
5465#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005466}
5467
Ana Krulec13be8ad2018-08-21 02:43:56 +00005468status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5469 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005470 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5471 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005472 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005473
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005474 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5475 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005476 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005477 IPCThreadState* ipc = IPCThreadState::self();
5478 const int uid = ipc->getCallingUid();
5479 if (CC_UNLIKELY(uid != AID_SYSTEM
5480 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005481 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005482 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005483 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005484 return PERMISSION_DENIED;
5485 }
5486 int n;
5487 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005488 case 1000: // Unused.
5489 case 1001:
5490 return NAME_NOT_FOUND;
5491 case 1002: // Toggle flashing on surface damage.
5492 if (const int delay = data.readInt32(); delay > 0) {
5493 mDebugFlashDelay = delay;
5494 } else {
5495 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5496 }
5497 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005498 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005499 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005500 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005501 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005502 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005503 case 1005: { // Force commit ahead of next VSYNC.
5504 Mutex::Autolock lock(mStateLock);
5505 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5506 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005507 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005508 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005509 case 1007: // Unused.
5510 return NAME_NOT_FOUND;
5511 case 1008: // Toggle forced GPU composition.
5512 mDebugDisableHWC = data.readInt32() != 0;
5513 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005514 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005515 case 1009: // Toggle use of transform hint.
5516 mDebugDisableTransformHint = data.readInt32() != 0;
5517 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005518 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005519 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005520 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005521 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005522 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005523 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005524 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005525 return NO_ERROR;
Dominik Laskowski8792c112022-07-12 09:03:39 -07005526 case 1013: // Unused.
5527 return NAME_NOT_FOUND;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005528 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005529 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005530 // daltonize
5531 n = data.readInt32();
5532 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005533 case 1:
5534 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5535 break;
5536 case 2:
5537 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5538 break;
5539 case 3:
5540 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5541 break;
5542 default:
5543 mDaltonizer.setType(ColorBlindnessType::None);
5544 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005545 }
5546 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005547 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005548 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005549 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005550 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005551
5552 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005553 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005554 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005555 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005556 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005557 // apply a color matrix
5558 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005559 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005560 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005561 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005562 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005563 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005564 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005565 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005566 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005567 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005568 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005569
5570 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5571 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005572 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005573 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5574 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5575 }
5576
Chia-I Wu28f320b2018-05-03 11:02:56 -07005577 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005578 return NO_ERROR;
5579 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005580 case 1016: { // Unused.
5581 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005582 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005583 case 1017: {
5584 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005585 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005586 return NO_ERROR;
5587 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005588 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005589 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005590 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005591 return NO_ERROR;
5592 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005593 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005594 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005595 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005596 return NO_ERROR;
5597 }
Irvel468051e2016-06-13 16:44:44 -07005598 case 1020: { // Layer updates interceptor
5599 n = data.readInt32();
5600 if (n) {
5601 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005602 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005603 }
5604 else{
5605 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005606 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005607 }
5608 return NO_ERROR;
5609 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005610 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005611 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005612 static_cast<void>(
5613 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005614 return NO_ERROR;
5615 }
Romain Guy0147a172017-06-01 13:53:56 -07005616 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005617 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005618 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005619
Chia-I Wu28f320b2018-05-03 11:02:56 -07005620 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005621 return NO_ERROR;
5622 }
Romain Guy54f154a2017-10-24 21:40:32 +01005623 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005624 int32_t colorMode;
5625
Chia-I Wu0d711262018-05-21 15:19:35 -07005626 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005627 if (data.readInt32(&colorMode) == NO_ERROR) {
5628 mForceColorMode = static_cast<ColorMode>(colorMode);
5629 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005630 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005631 return NO_ERROR;
5632 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005633 // Deprecate, use 1030 to check whether the device is color managed.
5634 case 1024: {
5635 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005636 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005637 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005638 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005639 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005640 if (n == 1) {
5641 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005642 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005643 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005644 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005645 int64_t startingTime =
5646 (fixedStartingTime) ? fixedStartingTime : systemTime();
5647 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005648 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Pablo Gamitob8775792022-06-10 15:02:42 +00005649 mLayerTracing.notify(true /* visibleRegionDirty */,
Dominik Laskowski08fbd852022-07-14 08:53:42 -07005650 startingTime, mLastCommittedVsyncId.value);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005651 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005652 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005653 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005654 } else if (n == 2) {
5655 std::string filename = std::string(data.readCString());
5656 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5657 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005658 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005659 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005660 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005661 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005662 mTracingEnabledChanged = tracingEnabledChanged;
5663 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005664 return NO_ERROR;
5665 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005666 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005667 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005668 return NO_ERROR;
5669 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005670 // Is a DisplayColorSetting supported?
5671 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005672 const auto display = getDefaultDisplayDevice();
5673 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005674 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005675 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005676
5677 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5678 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005679 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005680 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005681 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005682 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005683 reply->writeBool(true);
5684 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005685 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005686 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005687 break;
5688 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005689 reply->writeBool(
5690 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005691 break;
5692 }
5693 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005694 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005695 case 1028: { // Unused.
5696 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005697 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005698 // Set buffer size for SF tracing (value in KB)
5699 case 1029: {
5700 n = data.readInt32();
5701 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5702 ALOGW("Invalid buffer size: %d KB", n);
5703 reply->writeInt32(BAD_VALUE);
5704 return BAD_VALUE;
5705 }
5706
5707 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005708 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005709 reply->writeInt32(NO_ERROR);
5710 return NO_ERROR;
5711 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005712 // Is device color managed?
5713 case 1030: {
5714 reply->writeBool(useColorManagement);
5715 return NO_ERROR;
5716 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005717 // Override default composition data space
5718 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5719 // && adb shell stop zygote && adb shell start zygote
5720 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5721 // adb shell stop zygote && adb shell start zygote
5722 case 1031: {
5723 Mutex::Autolock _l(mStateLock);
5724 n = data.readInt32();
5725 if (n) {
5726 n = data.readInt32();
5727 if (n) {
5728 Dataspace dataspace = static_cast<Dataspace>(n);
5729 if (!validateCompositionDataspace(dataspace)) {
5730 return BAD_VALUE;
5731 }
5732 mDefaultCompositionDataspace = dataspace;
5733 }
5734 n = data.readInt32();
5735 if (n) {
5736 Dataspace dataspace = static_cast<Dataspace>(n);
5737 if (!validateCompositionDataspace(dataspace)) {
5738 return BAD_VALUE;
5739 }
5740 mWideColorGamutCompositionDataspace = dataspace;
5741 }
5742 } else {
5743 // restore composition data space.
5744 mDefaultCompositionDataspace = defaultCompositionDataspace;
5745 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5746 }
5747 return NO_ERROR;
5748 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005749 // Set trace flags
5750 case 1033: {
5751 n = data.readUint32();
5752 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005753 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005754 reply->writeInt32(NO_ERROR);
5755 return NO_ERROR;
5756 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005757 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005758 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005759 switch (n = data.readInt32()) {
5760 case 0:
5761 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005762 FTL_FAKE_GUARD(mStateLock,
5763 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005764 break;
5765 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005766 reply->writeBool(
5767 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005768 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005769 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005770 });
5771
5772 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005773 return NO_ERROR;
5774 }
Ady Abraham34392f72019-04-10 11:29:27 -07005775 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005776 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005777
Dominik Laskowskif1833852021-03-23 15:06:50 -07005778 const auto display = [&]() -> sp<IBinder> {
5779 uint64_t value;
5780 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005781 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005782 }
5783
Dominik Laskowskif1833852021-03-23 15:06:50 -07005784 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5785 return getPhysicalDisplayToken(*id);
5786 }
5787
5788 ALOGE("Invalid physical display ID");
5789 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005790 }();
5791
Shiyong Li2bcece92021-08-30 20:38:50 +00005792 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005793 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005794 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5795 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005796 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005797 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5798 // manager frame rate policy a new policy which allows switching between all refresh
5799 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005800 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005801 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005802 return mScheduler
5803 ->schedule([this] {
5804 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005805 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005806
Dominik Laskowski756b7892021-08-04 12:53:59 -07005807 // This is a little racy, but not in a way that hurts anything. As
5808 // we grab the defaultMode from the display manager policy, we could
5809 // be setting a new display manager policy, leaving us using a stale
5810 // defaultMode. The defaultMode doesn't matter for the override
5811 // policy though, since we set allowGroupSwitching to true, so it's
5812 // not a problem.
5813 scheduler::RefreshRateConfigs::Policy overridePolicy;
5814 overridePolicy.defaultMode = display->refreshRateConfigs()
5815 .getDisplayManagerPolicy()
5816 .defaultMode;
5817 overridePolicy.allowGroupSwitching = true;
5818 constexpr bool kOverridePolicy = true;
5819 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5820 kOverridePolicy);
5821 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005822 .get();
5823 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07005824 return mScheduler
5825 ->schedule([this] {
5826 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005827 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07005828 constexpr bool kOverridePolicy = true;
5829 return setDesiredDisplayModeSpecsInternal(display, {},
5830 kOverridePolicy);
5831 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005832 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07005833 }
Ady Abraham07e54702020-04-16 15:05:37 -07005834 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02005835 // Inject a hotplug connected event for the primary display. This will deallocate and
5836 // reallocate the display state including framebuffers.
5837 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07005838 const hal::HWDisplayId hwcId =
5839 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
5840
5841 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02005842 return NO_ERROR;
5843 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07005844 // Modify the max number of display frames stored within FrameTimeline
5845 case 1038: {
5846 n = data.readInt32();
5847 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
5848 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
5849 return BAD_VALUE;
5850 }
5851 if (n == 0) {
5852 // restore to default
5853 mFrameTimeline->reset();
5854 return NO_ERROR;
5855 }
5856 mFrameTimeline->setMaxDisplayFrames(n);
5857 return NO_ERROR;
5858 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07005859 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07005860 PhysicalDisplayId displayId = [&]() {
5861 Mutex::Autolock lock(mStateLock);
5862 return getDefaultDisplayDeviceLocked()->getPhysicalId();
5863 }();
5864
5865 auto inUid = static_cast<uid_t>(data.readInt32());
5866 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08005867 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
5868 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07005869 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08005870 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005871 // Toggle caching feature
5872 // First argument is an int32 - nonzero enables caching and zero disables caching
5873 // Second argument is an optional uint64 - if present, then limits enabling/disabling
5874 // caching to a particular physical display
5875 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005876 auto future = mScheduler->schedule([&] {
5877 n = data.readInt32();
5878 std::optional<PhysicalDisplayId> inputId = std::nullopt;
5879 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
5880 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
5881 if (!inputId || getPhysicalDisplayToken(*inputId)) {
5882 ALOGE("No display with id: %" PRIu64, inputDisplayId);
5883 return NAME_NOT_FOUND;
5884 }
5885 }
5886 {
5887 Mutex::Autolock lock(mStateLock);
5888 mLayerCachingEnabled = n != 0;
5889 for (const auto& [_, display] : mDisplays) {
5890 if (!inputId || *inputId == display->getPhysicalId()) {
5891 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07005892 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005893 }
5894 }
5895 return OK;
5896 });
Alec Mouricdd722b2021-05-19 14:29:05 -07005897
Dominik Laskowski756b7892021-08-04 12:53:59 -07005898 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07005899 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005900 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005901 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005902 return NO_ERROR;
5903 }
Vishnu Nair7891e962021-11-11 12:07:21 -08005904 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08005905 if (mTransactionTracing) {
5906 if (data.readInt32()) {
5907 // Transaction tracing is always running but allow the user to temporarily
5908 // increase the buffer when actively debugging.
5909 mTransactionTracing->setBufferSize(
5910 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
5911 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005912 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005913 mTransactionTracing->setBufferSize(
5914 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005915 }
Vishnu Nair7891e962021-11-11 12:07:21 -08005916 }
5917 reply->writeInt32(NO_ERROR);
5918 return NO_ERROR;
5919 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005920 case 1042: { // Write layers trace or transaction trace to file
5921 if (mTransactionTracing) {
5922 mTransactionTracing->writeToFile();
5923 }
5924 if (mLayerTracingEnabled) {
5925 mLayerTracing.writeToFile();
5926 }
5927 reply->writeInt32(NO_ERROR);
5928 return NO_ERROR;
5929 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005930 }
5931 }
5932 return err;
5933}
5934
Ady Abrahama09852a2020-02-20 14:23:42 -08005935void SurfaceFlinger::kernelTimerChanged(bool expired) {
5936 static bool updateOverlay =
5937 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005938 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005939
5940 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005941 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07005942 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005943 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07005944 if (!display) {
5945 ALOGW("%s: default display is null", __func__);
5946 return;
5947 }
Adrian Salidoa942af82022-02-17 19:22:31 -08005948 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07005949
5950 const auto desiredActiveMode = display->getDesiredActiveMode();
5951 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
5952 ? std::make_optional(desiredActiveMode->mode->getId())
5953 : std::nullopt;
5954
5955 const bool timerExpired = mKernelIdleTimerEnabled && expired;
5956
Ady Abraham1b11bc62021-06-03 19:51:19 -07005957 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005958 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08005959 }
5960 }));
5961}
5962
ramindani32cf0602022-03-02 02:30:29 +00005963std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
5964SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
5965 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
5966 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
5967 const auto timeout = getIdleTimerTimeout(displayId);
5968 if (isKernelIdleTimerHwcSupported) {
5969 if (const auto id = PhysicalDisplayId::tryCast(displayId);
5970 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
5971 // In order to decide if we can use the HWC api for idle timer
5972 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
5973 // without relying on hasDisplayCapability.
5974 // hasDisplayCapability relies on DisplayCapabilities
5975 // which are updated after we set the PowerMode::ON.
5976 // DISPLAY_IDLE_TIMER is a display driver property
5977 // and is available before the PowerMode::ON
5978 return {KernelIdleTimerController::HwcApi, timeout};
5979 }
5980 return {std::nullopt, timeout};
5981 }
5982 if (getKernelIdleTimerSyspropConfig(displayId)) {
5983 return {KernelIdleTimerController::Sysprop, timeout};
5984 }
5985
5986 return {std::nullopt, timeout};
5987}
5988
5989void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
5990 KernelIdleTimerController controller,
5991 PhysicalDisplayId displayId) {
5992 switch (controller) {
5993 case KernelIdleTimerController::HwcApi: {
5994 getHwComposer().setIdleTimerEnabled(displayId, timeout);
5995 break;
5996 }
5997 case KernelIdleTimerController::Sysprop: {
5998 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
5999 break;
6000 }
6001 }
6002}
6003
Ana Krulecb9afd792020-06-11 13:16:15 -07006004void SurfaceFlinger::toggleKernelIdleTimer() {
6005 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6006
Ady Abraham3efa3942021-06-24 19:01:25 -07006007 const auto display = getDefaultDisplayDeviceLocked();
6008 if (!display) {
6009 ALOGW("%s: default display is null", __func__);
6010 return;
6011 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006012
Ady Abrahame9316b72021-09-24 17:04:36 -07006013 // If the support for kernel idle timer is disabled for the active display,
6014 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006015 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6016 display->refreshRateConfigs().kernelIdleTimerController();
6017 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006018 return;
6019 }
6020
Ady Abraham3efa3942021-06-24 19:01:25 -07006021 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006022
Ana Krulecb9afd792020-06-11 13:16:15 -07006023 switch (action) {
6024 case KernelIdleTimerAction::TurnOff:
6025 if (mKernelIdleTimerEnabled) {
6026 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006027 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6028 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6029 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006030 mKernelIdleTimerEnabled = false;
6031 }
6032 break;
6033 case KernelIdleTimerAction::TurnOn:
6034 if (!mKernelIdleTimerEnabled) {
6035 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006036 const std::chrono::milliseconds timeout =
6037 display->refreshRateConfigs().getIdleTimerTimeout();
6038 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6039 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006040 mKernelIdleTimerEnabled = true;
6041 }
6042 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006043 }
6044}
6045
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006046// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6047class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006048public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006049 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6050 ~WindowDisconnector() {
6051 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006052 }
6053
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006054private:
6055 ANativeWindow* mWindow;
6056 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006057};
6058
chaviw93df2ea2019-04-30 16:45:12 -07006059static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6060 switch (colorMode) {
6061 case ColorMode::DISPLAY_P3:
6062 case ColorMode::BT2100_PQ:
6063 case ColorMode::BT2100_HLG:
6064 case ColorMode::DISPLAY_BT2020:
6065 return Dataspace::DISPLAY_P3;
6066 default:
6067 return Dataspace::V0_SRGB;
6068 }
6069}
6070
chaviwf5bb97b2021-04-28 15:35:37 -05006071static bool hasCaptureBlackoutContentPermission() {
6072 IPCThreadState* ipc = IPCThreadState::self();
6073 const int pid = ipc->getCallingPid();
6074 const int uid = ipc->getCallingUid();
6075 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6076 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6077}
6078
chaviw4b9d5e12020-08-04 18:30:35 -07006079static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6080 IPCThreadState* ipc = IPCThreadState::self();
6081 const int pid = ipc->getCallingPid();
6082 const int uid = ipc->getCallingUid();
6083 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6084 return OK;
6085 }
6086
6087 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6088 // itself, we allow it to continue.
6089 if (captureArgs.uid == uid) {
6090 return OK;
6091 }
6092
6093 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6094 return PERMISSION_DENIED;
6095}
6096
Peiyong Lin05cc0112020-10-14 16:16:37 -07006097status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6098 static constexpr int kFifoPriority = 2;
6099 static constexpr int kOtherPriority = 0;
6100
6101 struct sched_param param = {0};
6102 int sched_policy;
6103 if (enabled) {
6104 sched_policy = SCHED_FIFO;
6105 param.sched_priority = kFifoPriority;
6106 } else {
6107 sched_policy = SCHED_OTHER;
6108 param.sched_priority = kOtherPriority;
6109 }
6110
6111 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6112 return -errno;
6113 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006114
6115 return NO_ERROR;
6116}
6117
6118status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6119 static const unsigned int kUclampMin =
6120 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6121
6122 if (!kUclampMin) {
6123 // uclamp.min set to 0 (default), skip setting
6124 return NO_ERROR;
6125 }
6126
6127 // Currently, there is no wrapper in bionic: b/183240349.
6128 struct sched_attr {
6129 uint32_t size;
6130 uint32_t sched_policy;
6131 uint64_t sched_flags;
6132 int32_t sched_nice;
6133 uint32_t sched_priority;
6134 uint64_t sched_runtime;
6135 uint64_t sched_deadline;
6136 uint64_t sched_period;
6137 uint32_t sched_util_min;
6138 uint32_t sched_util_max;
6139 };
6140
6141 sched_attr attr = {};
6142 attr.size = sizeof(attr);
6143
6144 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6145 attr.sched_util_min = enabled ? kUclampMin : 0;
6146 attr.sched_util_max = 1024;
6147
6148 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6149 return -errno;
6150 }
6151
Peiyong Lin05cc0112020-10-14 16:16:37 -07006152 return NO_ERROR;
6153}
6154
chaviwd2432892020-07-24 17:42:39 -07006155status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006156 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006157 ATRACE_CALL();
6158
chaviw4b9d5e12020-08-04 18:30:35 -07006159 status_t validate = validateScreenshotPermissions(args);
6160 if (validate != OK) {
6161 return validate;
6162 }
6163
chaviwd2432892020-07-24 17:42:39 -07006164 if (!args.displayToken) return BAD_VALUE;
6165
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006166 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006167 ui::LayerStack layerStack;
6168 ui::Size reqSize(args.width, args.height);
6169 ui::Dataspace dataspace;
6170 {
6171 Mutex::Autolock lock(mStateLock);
6172 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6173 if (!display) return NAME_NOT_FOUND;
6174 displayWeak = display;
6175 layerStack = display->getLayerStack();
6176
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006177 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006178 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006179 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006180 }
6181
arthurhung79e81aa2020-08-28 00:09:19 +08006182 // The dataspace is depended on the color mode of display, that could use non-native mode
6183 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6184 // and failed if display is not in native mode. This provide a way to force using native
6185 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006186 dataspace = args.dataspace;
6187 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006188 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6189 dataspace = pickDataspaceFromColorMode(colorMode);
6190 }
chaviwd2432892020-07-24 17:42:39 -07006191 }
6192
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006193 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006194 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006195 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006196 });
6197
chaviw4b9d5e12020-08-04 18:30:35 -07006198 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6199 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006200 };
chaviw03900772020-08-18 12:34:51 -07006201
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006202 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6203 args.pixelFormat, args.allowProtected, args.grayscale,
6204 captureListener);
6205 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006206}
6207
Dominik Laskowskif1833852021-03-23 15:06:50 -07006208status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006209 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006210 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006211 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006212 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006213 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006214 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006215 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006216
Dominik Laskowskif1833852021-03-23 15:06:50 -07006217 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006218 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006219 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006220 }
6221
chaviw93df2ea2019-04-30 16:45:12 -07006222 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006223 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006224 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006225
chaviw426b5c02020-07-27 11:20:15 -07006226 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006227 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6228 }
6229
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006230 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006231 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006232 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006233 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006234 });
chaviw93df2ea2019-04-30 16:45:12 -07006235
Marin Shalamanov1c434292020-06-12 01:47:29 +02006236 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006237 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006238 };
6239
Sally Qi59a9f502021-10-12 18:53:23 +00006240 if (captureListener == nullptr) {
6241 ALOGE("capture screen must provide a capture listener callback");
6242 return BAD_VALUE;
6243 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006244
6245 constexpr bool kAllowProtected = false;
6246 constexpr bool kGrayscale = false;
6247
6248 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6249 ui::PixelFormat::RGBA_8888, kAllowProtected, kGrayscale,
6250 captureListener);
6251 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006252}
6253
chaviw3efadb12020-07-27 10:07:15 -07006254status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006255 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006256 ATRACE_CALL();
6257
chaviw4b9d5e12020-08-04 18:30:35 -07006258 status_t validate = validateScreenshotPermissions(args);
6259 if (validate != OK) {
6260 return validate;
6261 }
6262
Marin Shalamanov1c434292020-06-12 01:47:29 +02006263 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006264 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006265 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006266 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006267 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006268
6269 // Call this before holding mStateLock to avoid any deadlocking.
6270 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6271
Robert Carrc0df3122019-04-11 13:18:21 -07006272 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006273 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006274
Vishnu Nairf9096652021-07-20 18:49:42 -07006275 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006276 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006277 ALOGE("captureLayers called with an invalid or removed parent");
6278 return NAME_NOT_FOUND;
6279 }
6280
chaviwf5bb97b2021-04-28 15:35:37 -05006281 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006282 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006283 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6284 return PERMISSION_DENIED;
6285 }
6286
Robert Carr6a160312021-05-17 12:08:20 -07006287 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006288 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006289 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006290 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006291 }
6292
chaviw3efadb12020-07-27 10:07:15 -07006293 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006294 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006295 crop.bottom = parentSourceBounds.getHeight();
6296 }
6297
chaviw17ac24b2021-01-28 18:50:05 -08006298 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006299 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6300 // crop was not specified, or an invalid frame scale was provided.
6301 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006302 }
chaviw17ac24b2021-01-28 18:50:05 -08006303 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006304
chaviw3efadb12020-07-27 10:07:15 -07006305 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006306 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006307 if (excludeLayer != nullptr) {
6308 excludeLayers.emplace(excludeLayer);
6309 } else {
6310 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6311 return NAME_NOT_FOUND;
6312 }
6313 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006314
arthurhung79e81aa2020-08-28 00:09:19 +08006315 // The dataspace is depended on the color mode of display, that could use non-native mode
6316 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6317 // and failed if display is not in native mode. This provide a way to force using native
6318 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006319 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006320 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006321
Chia-I Wu20261cb2018-08-23 12:55:44 -07006322 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006323 if (reqSize.width <= 0 || reqSize.height <= 0) {
6324 ALOGW("Failed to captureLayes: crop or scale too small");
6325 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006326 }
6327
chaviw79468ab2021-10-27 11:11:24 -05006328 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006329 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006330 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006331 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006332 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006333 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006334 });
6335
chaviw03900772020-08-18 12:34:51 -07006336 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006337 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6338 if (!layer->isVisible()) {
6339 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006340 } else if (args.childrenOnly && layer == parent.get()) {
6341 return;
6342 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006343 return;
chaviwa76b2712017-09-20 12:02:26 -07006344 }
Robert Carr866455f2019-04-02 16:28:26 -07006345
Ady Abrahamd11bade2022-08-01 16:18:03 -07006346 auto p = sp<Layer>::fromExisting(layer);
Robert Carr866455f2019-04-02 16:28:26 -07006347 while (p != nullptr) {
6348 if (excludeLayers.count(p) != 0) {
6349 return;
6350 }
6351 p = p->getParent();
6352 }
6353
chaviwa76b2712017-09-20 12:02:26 -07006354 visitor(layer);
6355 });
6356 };
Robert Carr108b2c72019-04-02 16:32:58 -07006357
Sally Qi59a9f502021-10-12 18:53:23 +00006358 if (captureListener == nullptr) {
6359 ALOGE("capture screen must provide a capture listener callback");
6360 return BAD_VALUE;
6361 }
6362
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006363 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6364 args.pixelFormat, args.allowProtected, args.grayscale,
6365 captureListener);
6366 return fenceStatus(future.get());
chaviwa76b2712017-09-20 12:02:26 -07006367}
6368
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006369ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Sally Qi59a9f502021-10-12 18:53:23 +00006370 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6371 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6372 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006373 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006374
Garfield Tan9c9c1912021-07-19 12:02:16 -07006375 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6376 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6377 ") that exceeds render target size limit.",
6378 bufferSize.getWidth(), bufferSize.getHeight());
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006379 return ftl::yield<FenceResult>(base::unexpected(BAD_VALUE)).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006380 }
6381
Peiyong Lin05cc0112020-10-14 16:16:37 -07006382 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6383 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6384 // A protected layer has no implication on whether it's secure, which is explicitly set by
6385 // application to avoid being screenshot or drawn via unsecure display.
6386 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6387 bool hasProtectedLayer = false;
6388 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006389 auto future = mScheduler->schedule([=]() {
6390 bool protectedLayerFound = false;
6391 traverseLayers([&](Layer* layer) {
6392 protectedLayerFound =
6393 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6394 });
6395 return protectedLayerFound;
6396 });
6397 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006398 }
6399
Richard Liucbcb8952020-04-08 10:51:55 +00006400 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6401 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006402 (hasProtectedLayer && allowProtected && supportsProtected
6403 ? GRALLOC_USAGE_PROTECTED
6404 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006405 sp<GraphicBuffer> buffer =
6406 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6407 static_cast<android_pixel_format>(reqPixelFormat),
6408 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006409
6410 const status_t bufferStatus = buffer->initCheck();
Alec Mourid8f17c52022-07-21 18:43:10 +00006411 if (bufferStatus != OK) {
6412 // Animations may end up being really janky, but don't crash here.
6413 // Otherwise an irreponsible process may cause an SF crash by allocating
6414 // too much.
6415 ALOGE("%s: Buffer failed to allocate: %d", __func__, bufferStatus);
6416 return ftl::yield<FenceResult>(base::unexpected(bufferStatus)).share();
6417 }
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006418 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6419 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6420 renderengine::impl::ExternalTexture::Usage::
6421 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006422 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006423 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006424}
6425
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006426ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006427 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6428 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6429 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006430 ATRACE_CALL();
6431
chaviwf5bb97b2021-04-28 15:35:37 -05006432 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006433
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006434 auto future = mScheduler->schedule([=, renderAreaFuture = std::move(renderAreaFuture)]() mutable
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006435 -> ftl::SharedFuture<FenceResult> {
chaviw03900772020-08-18 12:34:51 -07006436 ScreenCaptureResults captureResults;
6437 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6438 if (!renderArea) {
6439 ALOGW("Skipping screen capture because of invalid render area.");
6440 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006441 captureListener->onScreenCaptureCompleted(captureResults);
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006442 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
chaviw03900772020-08-18 12:34:51 -07006443 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006444
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006445 ftl::SharedFuture<FenceResult> renderFuture;
chaviw03900772020-08-18 12:34:51 -07006446 renderArea->render([&] {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006447 renderFuture =
6448 renderScreenImpl(*renderArea, traverseLayers, buffer, canCaptureBlackoutContent,
6449 regionSampling, grayscale, captureResults);
chaviw03900772020-08-18 12:34:51 -07006450 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006451
6452 if (captureListener) {
Dominik Laskowskifb3beed2022-07-07 07:34:38 -07006453 // Defer blocking on renderFuture back to the Binder thread.
6454 return ftl::Future(std::move(renderFuture))
6455 .then([captureListener, captureResults = std::move(captureResults)](
6456 FenceResult fenceResult) mutable -> FenceResult {
6457 // TODO(b/232535621): Change ScreenCaptureResults to store a FenceResult.
6458 captureResults.result = fenceStatus(fenceResult);
6459 captureResults.fence = std::move(fenceResult).value_or(Fence::NO_FENCE);
6460 captureListener->onScreenCaptureCompleted(captureResults);
6461 return base::unexpected(NO_ERROR);
6462 })
6463 .share();
Sally Qi59a9f502021-10-12 18:53:23 +00006464 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006465 return renderFuture;
Sally Qi59a9f502021-10-12 18:53:23 +00006466 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006467
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006468 // Flatten nested futures.
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006469 auto chain = ftl::Future(std::move(future)).then([](ftl::SharedFuture<FenceResult> future) {
6470 return future;
6471 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006472
6473 return chain.share();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006474}
6475
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006476ftl::SharedFuture<FenceResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006477 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006478 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6479 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6480 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006481 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006482
chaviw426b5c02020-07-27 11:20:15 -07006483 traverseLayers([&](Layer* layer) {
6484 captureResults.capturedSecureLayers =
6485 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6486 });
6487
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006488 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006489
chaviw426b5c02020-07-27 11:20:15 -07006490 // We allow the system server to take screenshots of secure layers for
6491 // use in situations like the Screen-rotation animation and place
6492 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006493 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006494 ALOGW("FB is protected: PERMISSION_DENIED");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006495 return ftl::yield<FenceResult>(base::unexpected(PERMISSION_DENIED)).share();
chaviw426b5c02020-07-27 11:20:15 -07006496 }
6497
Alec Mouria90a5702021-04-16 16:36:21 +00006498 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006499 auto dataspace = renderArea.getReqDataSpace();
6500 auto parent = renderArea.getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00006501 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07006502 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
6503 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
6504
Robert Carr12a3b9b2022-03-10 09:55:29 -08006505 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6506 Mutex::Autolock lock(mStateLock);
6507 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6508 return display.getLayerStack() == layerStack;
6509 });
6510 if (!display) {
6511 // If the layer is not on a display, use the dataspace for the default display.
6512 display = getDefaultDisplayDeviceLocked();
6513 }
6514
6515 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6516 dataspace = pickDataspaceFromColorMode(colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00006517 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07006518 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
6519 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08006520 }
6521 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006522
chaviwa76b2712017-09-20 12:02:26 -07006523 const auto reqWidth = renderArea.getReqWidth();
6524 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006525 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006526 const auto transform = renderArea.getTransform();
6527 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006528 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006529
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006530 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006531 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006532
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006533 // assume that bounds are never offset, and that they are the same as the
6534 // buffer bounds.
6535 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006536 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006537 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006538
Robert Carr12a3b9b2022-03-10 09:55:29 -08006539 clientCompositionDisplay.outputDataspace = dataspace;
Sally Qie258f092022-05-19 15:24:12 -07006540 clientCompositionDisplay.currentLuminanceNits = displayBrightnessNits;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006541 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006542 clientCompositionDisplay.renderIntent =
6543 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006544
chaviw17ac24b2021-01-28 18:50:05 -08006545 const float colorSaturation = grayscale ? 0 : 1;
6546 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6547
chaviw50da5042018-04-09 13:49:37 -07006548 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006549
Vishnu Nair9b079a22020-01-21 14:36:08 -08006550 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006551 fillLayer.source.buffer.buffer = nullptr;
6552 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006553 fillLayer.geometry.boundaries =
6554 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006555 fillLayer.alpha = half(alpha);
6556 clientCompositionLayers.push_back(fillLayer);
6557
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006558 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006559 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006560 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006561 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006562 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006563
Lloyd Piquef16688f2019-02-19 17:47:57 -08006564 Region clip(renderArea.getBounds());
6565 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6566 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006567 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006568 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006569 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006570 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006571 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006572 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006573 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006574 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006575 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6576 BlurSetting::Disabled
6577 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6578 BlurSetting::Enabled,
Sally Qidb653012022-05-04 13:12:22 -07006579 isHdrLayer(layer) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006580
Lloyd Piquef16688f2019-02-19 17:47:57 -08006581 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006582 std::vector<compositionengine::LayerFE::LayerSettings> results =
6583 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006584 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006585 for (auto& settings : results) {
6586 settings.geometry.positionTransform =
6587 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006588 // There's no need to process blurs when we're executing region sampling,
6589 // we're just trying to understand what we're drawing, and doing so without
6590 // blurs is already a pretty good approximation.
6591 if (regionSampling) {
6592 settings.backgroundBlurRadius = 0;
6593 }
Sally Qidb653012022-05-04 13:12:22 -07006594 captureResults.capturedHdrLayers |= isHdrLayer(layer);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006595 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006596
Yichi Chen40773d92020-04-01 10:10:18 +08006597 clientCompositionLayers.insert(clientCompositionLayers.end(),
6598 std::make_move_iterator(results.begin()),
6599 std::make_move_iterator(results.end()));
6600 renderedLayers.push_back(layer);
6601 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006602
chaviwa76b2712017-09-20 12:02:26 -07006603 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006604
Sally Qi59a9f502021-10-12 18:53:23 +00006605 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6606 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006607 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006608 std::back_inserter(clientRenderEngineLayers),
6609 [](compositionengine::LayerFE::LayerSettings& settings)
6610 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006611
Alec Mouri6338c9d2019-02-07 16:57:51 -08006612 // Use an empty fence for the buffer fence, since we just created the buffer so
6613 // there is no need for synchronization with the GPU.
6614 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006615 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006616
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006617 constexpr bool kUseFramebufferCache = false;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006618 auto chain =
6619 ftl::Future(getRenderEngine().drawLayers(clientCompositionDisplay,
6620 clientRenderEngineLayers, buffer,
6621 kUseFramebufferCache, std::move(bufferFence)))
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006622 .then(&toFenceResult);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006623
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006624 const auto future = chain.share();
Sally Qi59a9f502021-10-12 18:53:23 +00006625 for (auto* layer : renderedLayers) {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006626 layer->onLayerDisplayed(future);
Yichi Chen40773d92020-04-01 10:10:18 +08006627 }
Ady Abraham99599942021-01-27 20:27:23 -08006628
Peiyong Lin05cc0112020-10-14 16:16:37 -07006629 // Always switch back to unprotected context.
6630 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006631
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006632 return future;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006633}
6634
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006635// ---------------------------------------------------------------------------
6636
Edgar Arriaga844fa672020-01-16 14:21:42 -08006637void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6638 layersSortedByZ.traverse(visitor);
6639}
6640
Dan Stoza412903f2017-04-27 13:42:17 -07006641void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6642 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006643}
6644
Dan Stoza412903f2017-04-27 13:42:17 -07006645void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6646 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006647}
6648
chaviw4b9d5e12020-08-04 18:30:35 -07006649void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006650 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006651 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006652 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006653 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006654 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006655 continue;
6656 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006657 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006658 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006659 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006660 return;
6661 }
chaviwa76b2712017-09-20 12:02:26 -07006662 if (!layer->isVisible()) {
6663 return;
6664 }
chaviw4b9d5e12020-08-04 18:30:35 -07006665 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6666 return;
6667 }
chaviwa76b2712017-09-20 12:02:26 -07006668 visitor(layer);
6669 });
6670 }
6671}
6672
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006673status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006674 const sp<DisplayDevice>& display,
6675 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006676 Mutex::Autolock lock(mStateLock);
6677
Ady Abrahamfb853662021-04-09 11:46:40 -07006678 if (mDebugDisplayModeSetByBackdoor) {
6679 // ignore this request as mode is overridden by backdoor
6680 return NO_ERROR;
6681 }
6682
Ady Abrahama92a5682022-06-07 23:35:38 +00006683 const status_t setPolicyResult = display->setRefreshRatePolicy(policy, overridePolicy);
Ady Abraham3efa3942021-06-24 19:01:25 -07006684 if (setPolicyResult < 0) {
6685 return BAD_VALUE;
6686 }
6687 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6688 return NO_ERROR;
6689 }
6690
Ady Abraham3efa3942021-06-24 19:01:25 -07006691 scheduler::RefreshRateConfigs::Policy currentPolicy =
6692 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006693
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006694 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006695
Ana Krulecb9afd792020-06-11 13:16:15 -07006696 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6697 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006698 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006699 if (isDisplayActiveLocked(display)) {
6700 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6701 toggleKernelIdleTimer();
6702 } else {
6703 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6704 }
Ady Abraham838de062019-02-04 10:24:03 -08006705
Ady Abraham690f4612021-07-01 23:24:03 -07006706 const DisplayModePtr preferredDisplayMode = [&] {
6707 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6708 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6709 return schedulerMode;
6710 }
6711
6712 return display->getMode(currentPolicy.defaultMode);
6713 }();
6714
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006715 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006716 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006717
Ady Abraham690f4612021-07-01 23:24:03 -07006718 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006719 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006720 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006721 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006722 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006723 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006724 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006725 }
6726
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006727 return NO_ERROR;
6728}
6729
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006730status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6731 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6732 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6733 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006734 ATRACE_CALL();
6735
6736 if (!displayToken) {
6737 return BAD_VALUE;
6738 }
6739
Dominik Laskowski756b7892021-08-04 12:53:59 -07006740 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006741 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006742 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006743 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006744 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006745 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006746 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006747 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006748 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006749 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006750 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006751 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006752 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006753 {Fps::fromValue(primaryRefreshRateMin),
6754 Fps::fromValue(primaryRefreshRateMax)},
6755 {Fps::fromValue(appRequestRefreshRateMin),
6756 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006757 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006758
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006759 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006760 }
6761 });
6762
6763 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006764}
6765
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006766status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6767 ui::DisplayModeId* outDefaultMode,
6768 bool* outAllowGroupSwitching,
6769 float* outPrimaryRefreshRateMin,
6770 float* outPrimaryRefreshRateMax,
6771 float* outAppRequestRefreshRateMin,
6772 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006773 ATRACE_CALL();
6774
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006775 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006776 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006777 return BAD_VALUE;
6778 }
6779
6780 Mutex::Autolock lock(mStateLock);
6781 const auto display = getDisplayDeviceLocked(displayToken);
6782 if (!display) {
6783 return NAME_NOT_FOUND;
6784 }
6785
Ady Abraham3efa3942021-06-24 19:01:25 -07006786 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006787 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006788 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006789
6790 scheduler::RefreshRateConfigs::Policy policy =
6791 display->refreshRateConfigs().getDisplayManagerPolicy();
6792 *outDefaultMode = policy.defaultMode.value();
6793 *outAllowGroupSwitching = policy.allowGroupSwitching;
6794 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6795 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6796 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6797 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6798 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006799}
6800
Vishnu Nairf9096652021-07-20 18:49:42 -07006801wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6802 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006803}
6804
Dominik Laskowski75848362019-11-11 17:57:20 -08006805void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006806 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006807 if (!layer->isRemovedFromCurrentState()) {
6808 mScheduler->registerLayer(layer);
6809 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006810}
6811
6812void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6813 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006814 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006815 if (!layer->isRemovedFromCurrentState()) {
6816 mScheduler->deregisterLayer(layer);
6817 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08006818 if (mTransactionTracing) {
6819 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08006820 }
Valerie Hauc5686802019-11-22 14:18:09 -08006821}
6822
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006823void SurfaceFlinger::onLayerUpdate() {
6824 scheduleCommit(FrameHint::kActive);
6825}
6826
Valerie Hauc5686802019-11-22 14:18:09 -08006827// WARNING: ONLY CALL THIS FROM LAYER DTOR
6828// Here we add children in the current state to offscreen layers and remove the
6829// layer itself from the offscreen layer list. Since
6830// this is the dtor, it is safe to access the current state. This keeps us
6831// from dangling children layers such that they are not reachable from the
6832// Drawing state nor the offscreen layer list
6833// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07006834void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08006835 for (auto& child : layer->getCurrentChildren()) {
6836 mOffscreenLayers.emplace(child.get());
6837 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006838 mOffscreenLayers.erase(layer);
6839}
6840
Robert Carr867be372021-06-29 17:36:02 -07006841void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6842 mOffscreenLayers.erase(layer);
6843}
6844
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006845status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6846 float lightPosY, float lightPosZ,
6847 float lightRadius) {
6848 Mutex::Autolock _l(mStateLock);
6849 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6850 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6851 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6852 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6853 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6854
6855 // these values are overridden when calculating the shadow settings for a layer.
6856 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6857 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006858 return NO_ERROR;
6859}
6860
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006861const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6862 const {
6863 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6864 // on the work to remove the table in that bug rather than adding more to
6865 // it.
6866 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08006867 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
6868 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006869 };
6870 return genericLayerMetadataKeyMap;
6871}
6872
Andy Yu2ae6b6b2021-11-18 14:51:06 -08006873status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
6874 PhysicalDisplayId displayId = [&]() {
6875 Mutex::Autolock lock(mStateLock);
6876 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6877 }();
6878
6879 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
6880 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
6881 return NO_ERROR;
6882}
6883
Dominik Laskowski20134642020-04-20 22:36:44 -07006884void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07006885 for (const auto& [ignored, display] : mDisplays) {
6886 if (display->isInternal()) {
6887 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07006888 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07006889 }
Dominik Laskowski20134642020-04-20 22:36:44 -07006890}
6891
Pablo Gamito6ee484d2020-07-30 14:26:28 +00006892status_t SurfaceFlinger::addTransactionTraceListener(
6893 const sp<gui::ITransactionTraceListener>& listener) {
6894 if (!listener) {
6895 return BAD_VALUE;
6896 }
6897
6898 mInterceptor->addTransactionTraceListener(listener);
6899
6900 return NO_ERROR;
6901}
6902
Huihong Luo02186fb2022-02-23 14:21:54 -08006903int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08006904 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08006905}
6906
Ady Abraham899dcdb2021-06-15 16:56:21 -07006907int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
6908 std::chrono::nanoseconds presentLatency) {
6909 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
6910 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08006911 pipelineDepth++;
6912 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07006913 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08006914}
6915
Ady Abraham899dcdb2021-06-15 16:56:21 -07006916status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006917 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006918
6919 if (!getHwComposer().isHeadless()) {
6920 if (const auto display = getDefaultDisplayDevice()) {
6921 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07006922 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006923 }
6924
6925 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08006926 return NO_ERROR;
6927}
6928
rnleeed20fa42021-08-10 18:00:03 -07006929uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006930 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07006931
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006932 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
6933 refreshRate = *frameRateOverride;
6934 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006935 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006936 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07006937 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006938 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006939
Ady Abraham899dcdb2021-06-15 16:56:21 -07006940 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
6941}
6942
6943int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
6944 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
6945 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
6946 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
6947}
6948
Dominik Laskowski08fbd852022-07-14 08:53:42 -07006949void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state, VsyncId vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08006950 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08006951 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08006952 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
6953 return;
arthurhungdba591c2021-02-08 17:28:49 +08006954 }
6955
6956 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08006957 bool addToRoot = state.addToRoot;
6958 if (state.initialParent != nullptr) {
6959 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08006960 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08006961 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07006962 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08006963 }
arthurhungdba591c2021-02-08 17:28:49 +08006964 }
6965
Garfield Tand712ad32021-10-27 13:44:22 -07006966 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07006967 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08006968 mCurrentState.layersSortedByZ.add(layer);
6969 } else if (parent == nullptr) {
6970 layer->onRemovedFromCurrentState();
6971 } else if (parent->isRemovedFromCurrentState()) {
6972 parent->addChild(layer);
6973 layer->onRemovedFromCurrentState();
6974 } else {
6975 parent->addChild(layer);
6976 }
6977
Ady Abraham1273ac12021-08-26 17:31:53 -07006978 layer->updateTransformHint(mActiveDisplayTransformHint);
Vishnu Nair286f4f92022-06-08 16:37:39 -07006979 if (mTransactionTracing) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07006980 mTransactionTracing->onLayerAddedToDrawingState(layer->getSequence(), vsyncId.value);
Vishnu Nair286f4f92022-06-08 16:37:39 -07006981 }
Arthur Hung23e07502021-10-15 11:58:19 +00006982 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08006983}
Ady Abraham562c2712021-05-07 15:10:42 -07006984
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006985void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07006986 if (!mLumaSampling || !mRegionSamplingThread) {
6987 return;
6988 }
6989
Dominik Laskowski756b7892021-08-04 12:53:59 -07006990 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07006991}
6992
Ady Abrahamed3290f2021-05-17 15:12:14 -07006993void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
6994 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
6995 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
6996}
6997
6998void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
6999 ATRACE_CALL();
7000
Ady Abrahamdb036a82021-07-16 14:18:34 -07007001 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7002 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7003 }
7004
Ady Abrahamed3290f2021-05-17 15:12:14 -07007005 if (!activeDisplay) {
7006 ALOGE("%s: activeDisplay is null", __func__);
7007 return;
7008 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007009 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007010 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007011 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007012 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007013 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007014 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007015 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007016
7017 // Update the kernel timer for the current active display, since the policy
7018 // for this display might have changed when it was not the active display.
7019 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007020}
7021
chaviw60c9d3e2021-06-04 12:52:17 -05007022status_t SurfaceFlinger::addWindowInfosListener(
7023 const sp<IWindowInfosListener>& windowInfosListener) const {
7024 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7025 return NO_ERROR;
7026}
7027
7028status_t SurfaceFlinger::removeWindowInfosListener(
7029 const sp<IWindowInfosListener>& windowInfosListener) const {
7030 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7031 return NO_ERROR;
7032}
7033
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007034std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7035 const BufferData& bufferData, const char* layerName) const {
7036 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7037 bool bufferSizeExceedsLimit = false;
7038 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7039 if (cacheIdChanged && bufferData.buffer != nullptr) {
7040 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7041 bufferData.buffer->getHeight());
7042 if (!bufferSizeExceedsLimit) {
7043 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7044 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7045 }
7046 } else if (cacheIdChanged) {
7047 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7048 } else if (bufferData.buffer != nullptr) {
7049 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7050 bufferData.buffer->getHeight());
7051 if (!bufferSizeExceedsLimit) {
7052 buffer = std::make_shared<
7053 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7054 renderengine::impl::ExternalTexture::
7055 Usage::READABLE);
7056 }
7057 }
7058 ALOGE_IF(bufferSizeExceedsLimit,
7059 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7060 "limit.",
7061 layerName);
7062 return buffer;
7063}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007064
Dominik Laskowski08fbd852022-07-14 08:53:42 -07007065bool SurfaceFlinger::commitMirrorDisplays(VsyncId vsyncId) {
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00007066 std::vector<MirrorDisplayState> mirrorDisplays;
7067 {
7068 std::scoped_lock<std::mutex> lock(mMirrorDisplayLock);
7069 mirrorDisplays = std::move(mMirrorDisplays);
7070 mMirrorDisplays.clear();
7071 if (mirrorDisplays.size() == 0) {
7072 return false;
7073 }
7074 }
7075
7076 sp<IBinder> unused;
7077 for (const auto& mirrorDisplay : mirrorDisplays) {
7078 // Set mirror layer's default layer stack to -1 so it doesn't end up rendered on a display
7079 // accidentally.
7080 sp<Layer> rootMirrorLayer = Layer::fromHandle(mirrorDisplay.rootHandle).promote();
7081 rootMirrorLayer->setLayerStack(ui::LayerStack::fromValue(-1));
7082 for (const auto& layer : mDrawingState.layersSortedByZ) {
7083 if (layer->getLayerStack() != mirrorDisplay.layerStack ||
7084 layer->isInternalDisplayOverlay()) {
7085 continue;
7086 }
7087
7088 LayerCreationArgs mirrorArgs(this, mirrorDisplay.client, "MirrorLayerParent",
7089 ISurfaceComposerClient::eNoColorFill,
7090 gui::LayerMetadata());
7091 sp<Layer> childMirror;
7092 createEffectLayer(mirrorArgs, &unused, &childMirror);
7093 childMirror->setClonedChild(layer->createClone());
7094 if (mTransactionTracing) {
7095 mTransactionTracing->onLayerAddedToDrawingState(childMirror->getSequence(),
Dominik Laskowski08fbd852022-07-14 08:53:42 -07007096 vsyncId.value);
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00007097 }
7098 childMirror->reparent(mirrorDisplay.rootHandle);
7099 }
7100 }
7101 return true;
7102}
7103
Dominik Laskowski08fbd852022-07-14 08:53:42 -07007104bool SurfaceFlinger::commitCreatedLayers(VsyncId vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007105 std::vector<LayerCreatedState> createdLayers;
7106 {
7107 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7108 createdLayers = std::move(mCreatedLayers);
7109 mCreatedLayers.clear();
7110 if (createdLayers.size() == 0) {
7111 return false;
7112 }
7113 }
7114
7115 Mutex::Autolock _l(mStateLock);
7116 for (const auto& createdLayer : createdLayers) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07007117 handleLayerCreatedLocked(createdLayer, vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007118 }
7119 createdLayers.clear();
7120 mLayersAdded = true;
7121 return true;
7122}
Huihong Luof5029222021-12-16 14:33:46 -08007123
7124// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007125
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007126binder::Status SurfaceComposerAIDL::bootFinished() {
7127 status_t status = checkAccessPermission();
7128 if (status != OK) {
7129 return binderStatusFromStatusT(status);
7130 }
7131 mFlinger->bootFinished();
7132 return binder::Status::ok();
7133}
7134
7135binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7136 VsyncSource vsyncSource, EventRegistration eventRegistration,
7137 sp<IDisplayEventConnection>* outConnection) {
7138 sp<IDisplayEventConnection> conn =
7139 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration);
7140 if (conn == nullptr) {
7141 *outConnection = nullptr;
7142 return binderStatusFromStatusT(BAD_VALUE);
7143 } else {
7144 *outConnection = conn;
7145 return binder::Status::ok();
7146 }
7147}
7148
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007149binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07007150 const sp<Client> client = sp<Client>::make(mFlinger);
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007151 if (client->initCheck() == NO_ERROR) {
7152 *outClient = client;
7153 return binder::Status::ok();
7154 } else {
7155 *outClient = nullptr;
7156 return binderStatusFromStatusT(BAD_VALUE);
7157 }
7158}
7159
Huihong Luo07e72362022-02-14 14:26:04 -08007160binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7161 sp<IBinder>* outDisplay) {
7162 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007163 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007164 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007165 }
Huihong Luo37396db2022-02-15 10:43:00 -08007166 String8 displayName8 = String8::format("%s", displayName.c_str());
7167 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7168 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007169}
7170
7171binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7172 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007173 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007174 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007175 }
Huihong Luo37396db2022-02-15 10:43:00 -08007176 mFlinger->destroyDisplay(display);
7177 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007178}
7179
7180binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7181 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7182 std::vector<int64_t> displayIds;
7183 displayIds.reserve(physicalDisplayIds.size());
7184 for (auto item : physicalDisplayIds) {
7185 displayIds.push_back(static_cast<int64_t>(item.value));
7186 }
7187 *outDisplayIds = displayIds;
7188 return binder::Status::ok();
7189}
7190
Huihong Luo07e72362022-02-14 14:26:04 -08007191binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7192 sp<IBinder>* outDisplay) {
7193 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7194 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7195 return binder::Status::ok();
7196}
7197
Huihong Luo37396db2022-02-15 10:43:00 -08007198binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7199 status_t status = checkAccessPermission();
7200 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007201 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007202 }
7203 mFlinger->setPowerMode(display, mode);
7204 return binder::Status::ok();
7205}
7206
Huihong Luo0a81aa32022-02-22 16:02:36 -08007207binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7208 std::vector<FrameEvent>* outSupported) {
7209 status_t status;
7210 if (!outSupported) {
7211 status = UNEXPECTED_NULL;
7212 } else {
7213 outSupported->clear();
7214 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7215 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007216 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007217}
7218
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007219binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7220 gui::DisplayStatInfo* outStatInfo) {
7221 DisplayStatInfo statInfo;
7222 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7223 if (status == NO_ERROR) {
7224 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7225 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7226 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007227 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007228}
7229
7230binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7231 gui::DisplayState* outState) {
7232 ui::DisplayState state;
7233 status_t status = mFlinger->getDisplayState(display, &state);
7234 if (status == NO_ERROR) {
7235 outState->layerStack = state.layerStack.id;
7236 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7237 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7238 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7239 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007240 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007241}
7242
Huihong Luoa79ddf42022-02-17 00:01:38 -08007243binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7244 gui::StaticDisplayInfo* outInfo) {
7245 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7246 ui::StaticDisplayInfo info;
7247 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7248 if (status == NO_ERROR) {
7249 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7250 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7251 outInfo->density = info.density;
7252 outInfo->secure = info.secure;
7253 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7254
7255 gui::DeviceProductInfo dinfo;
7256 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7257 dinfo.name = std::move(dpi->name);
7258 dinfo.manufacturerPnpId =
7259 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7260 dinfo.productId = dpi->productId;
Kriti Dang1de958d2022-05-30 15:26:58 +02007261 dinfo.relativeAddress =
7262 std::vector<uint8_t>(dpi->relativeAddress.begin(), dpi->relativeAddress.end());
Huihong Luoa79ddf42022-02-17 00:01:38 -08007263 if (const auto* model =
7264 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7265 gui::DeviceProductInfo::ModelYear modelYear;
7266 modelYear.year = model->year;
7267 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7268 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7269 &dpi->manufactureOrModelDate)) {
7270 gui::DeviceProductInfo::ManufactureYear date;
7271 date.modelYear.year = manufacture->year;
7272 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7273 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7274 &dpi->manufactureOrModelDate)) {
7275 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7276 date.manufactureYear.modelYear.year = manufacture->year;
7277 date.week = manufacture->week;
7278 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7279 }
7280
7281 outInfo->deviceProductInfo = dinfo;
7282 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007283 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007284}
7285
Huihong Luo38603fd2022-02-21 14:32:54 -08007286binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7287 gui::DynamicDisplayInfo* outInfo) {
7288 ui::DynamicDisplayInfo info;
7289 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7290 if (status == NO_ERROR) {
7291 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7292 outInfo->supportedDisplayModes.clear();
7293 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7294 for (const auto& mode : info.supportedDisplayModes) {
7295 gui::DisplayMode outMode;
7296 outMode.id = mode.id;
7297 outMode.resolution.width = mode.resolution.width;
7298 outMode.resolution.height = mode.resolution.height;
7299 outMode.xDpi = mode.xDpi;
7300 outMode.yDpi = mode.yDpi;
7301 outMode.refreshRate = mode.refreshRate;
7302 outMode.appVsyncOffset = mode.appVsyncOffset;
7303 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7304 outMode.presentationDeadline = mode.presentationDeadline;
7305 outMode.group = mode.group;
7306 outInfo->supportedDisplayModes.push_back(outMode);
7307 }
7308
7309 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7310
7311 outInfo->supportedColorModes.clear();
7312 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7313 for (const auto& cmode : info.supportedColorModes) {
7314 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7315 }
7316
7317 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7318
7319 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7320 hdrCapabilities.supportedHdrTypes.clear();
7321 hdrCapabilities.supportedHdrTypes.reserve(
7322 info.hdrCapabilities.getSupportedHdrTypes().size());
7323 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7324 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7325 }
7326 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7327 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7328 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7329
7330 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7331 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7332 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7333 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007334 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007335}
7336
Huihong Luoca3d9a42022-02-22 11:07:34 -08007337binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7338 gui::DisplayPrimaries* outPrimaries) {
7339 ui::DisplayPrimaries primaries;
7340 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7341 if (status == NO_ERROR) {
7342 outPrimaries->red.X = primaries.red.X;
7343 outPrimaries->red.Y = primaries.red.Y;
7344 outPrimaries->red.Z = primaries.red.Z;
7345
7346 outPrimaries->green.X = primaries.green.X;
7347 outPrimaries->green.Y = primaries.green.Y;
7348 outPrimaries->green.Z = primaries.green.Z;
7349
7350 outPrimaries->blue.X = primaries.blue.X;
7351 outPrimaries->blue.Y = primaries.blue.Y;
7352 outPrimaries->blue.Z = primaries.blue.Z;
7353
7354 outPrimaries->white.X = primaries.white.X;
7355 outPrimaries->white.Y = primaries.white.Y;
7356 outPrimaries->white.Z = primaries.white.Z;
7357 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007358 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007359}
7360
7361binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7362 status_t status = checkAccessPermission();
7363 if (status == OK) {
7364 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7365 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007366 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007367}
7368
7369binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7370 int displayModeId) {
7371 status_t status = checkAccessPermission();
7372 if (status == OK) {
7373 status = mFlinger->setBootDisplayMode(display,
7374 static_cast<ui::DisplayModeId>(displayModeId));
7375 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007376 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007377}
7378
Huihong Luo37396db2022-02-15 10:43:00 -08007379binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7380 status_t status = checkAccessPermission();
7381 if (status == OK) {
7382 status = mFlinger->clearBootDisplayMode(display);
7383 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007384 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007385}
7386
7387binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7388 status_t status = checkAccessPermission();
7389 if (status == OK) {
7390 status = mFlinger->getBootDisplayModeSupport(outMode);
7391 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007392 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007393}
7394
7395binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7396 status_t status = checkAccessPermission();
7397 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007398 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007399 }
7400 mFlinger->setAutoLowLatencyMode(display, on);
7401 return binder::Status::ok();
7402}
7403
7404binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7405 status_t status = checkAccessPermission();
7406 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007407 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007408 }
7409 mFlinger->setGameContentType(display, on);
7410 return binder::Status::ok();
7411}
7412
Huihong Luof5029222021-12-16 14:33:46 -08007413binder::Status SurfaceComposerAIDL::captureDisplay(
7414 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7415 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007416 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007417}
7418
7419binder::Status SurfaceComposerAIDL::captureDisplayById(
7420 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7421 status_t status;
7422 IPCThreadState* ipc = IPCThreadState::self();
7423 const int uid = ipc->getCallingUid();
7424 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7425 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7426 status = mFlinger->captureDisplay(*id, captureListener);
7427 } else {
7428 status = PERMISSION_DENIED;
7429 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007430 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007431}
7432
7433binder::Status SurfaceComposerAIDL::captureLayers(
7434 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7435 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007436 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007437}
7438
Huihong Luo05539a12022-02-23 10:29:40 -08007439binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7440 const std::vector<int32_t>& hdrTypes) {
7441 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7442 // permission dynamically. Don't use the permission cache for this check.
7443 status_t status = checkAccessPermission(false);
7444 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007445 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007446 }
7447
7448 std::vector<ui::Hdr> hdrTypesVector;
7449 for (int32_t i : hdrTypes) {
7450 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7451 }
7452 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007453 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007454}
7455
7456binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7457 status_t status;
7458 const int uid = IPCThreadState::self()->getCallingUid();
7459 if (uid != AID_SYSTEM) {
7460 status = PERMISSION_DENIED;
7461 } else {
7462 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7463 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007464 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007465}
7466
7467binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7468 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007469 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007470 }
7471
7472 status_t status = checkAccessPermission();
7473 if (status == OK) {
7474 status = mFlinger->enableVSyncInjections(enable);
7475 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007476 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007477}
7478
7479binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7480 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007481 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007482 }
7483
7484 status_t status = checkAccessPermission();
7485 if (status == OK) {
7486 status = mFlinger->injectVSync(when);
7487 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007488 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007489}
7490
7491binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7492 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007493 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007494 }
7495
7496 IPCThreadState* ipc = IPCThreadState::self();
7497 const int pid = ipc->getCallingPid();
7498 const int uid = ipc->getCallingUid();
7499 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7500 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007501 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007502 }
7503 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007504 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007505}
7506
7507binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7508 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007509 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007510}
7511
7512binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7513 ui::Dataspace dataspace;
7514 ui::PixelFormat pixelFormat;
7515 ui::Dataspace wideColorGamutDataspace;
7516 ui::PixelFormat wideColorGamutPixelFormat;
7517 status_t status =
7518 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7519 &wideColorGamutPixelFormat);
7520 if (status == NO_ERROR) {
7521 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7522 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7523 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7524 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7525 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007526 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007527}
7528
7529binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7530 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7531 status_t status = checkAccessPermission();
7532 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007533 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007534 }
7535
7536 ui::PixelFormat format;
7537 ui::Dataspace dataspace;
7538 uint8_t componentMask;
7539 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7540 &componentMask);
7541 if (status == NO_ERROR) {
7542 outAttrs->format = static_cast<int32_t>(format);
7543 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7544 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7545 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007546 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007547}
7548
7549binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7550 bool enable,
7551 int8_t componentMask,
7552 int64_t maxFrames) {
7553 status_t status = checkAccessPermission();
7554 if (status == OK) {
7555 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7556 static_cast<uint8_t>(componentMask),
7557 static_cast<uint64_t>(maxFrames));
7558 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007559 return binderStatusFromStatusT(status);
7560}
7561
7562binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7563 int64_t maxFrames, int64_t timestamp,
7564 gui::DisplayedFrameStats* outStats) {
7565 if (!outStats) {
7566 return binderStatusFromStatusT(BAD_VALUE);
7567 }
7568
7569 status_t status = checkAccessPermission();
7570 if (status != OK) {
7571 return binderStatusFromStatusT(status);
7572 }
7573
7574 DisplayedFrameStats stats;
7575 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7576 static_cast<uint64_t>(timestamp), &stats);
7577 if (status == NO_ERROR) {
7578 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7579 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7580 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7581 for (const auto& s : stats.component_0_sample) {
7582 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7583 }
7584 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7585 for (const auto& s : stats.component_1_sample) {
7586 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7587 }
7588 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7589 for (const auto& s : stats.component_2_sample) {
7590 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7591 }
7592 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7593 for (const auto& s : stats.component_3_sample) {
7594 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7595 }
7596 }
7597 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007598}
7599
7600binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7601 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007602 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007603}
7604
Huihong Luo37396db2022-02-15 10:43:00 -08007605binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7606 bool* outIsWideColorDisplay) {
7607 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007608 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007609}
7610
Huihong Luo02186fb2022-02-23 14:21:54 -08007611binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7612 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7613 const sp<gui::IRegionSamplingListener>& listener) {
7614 status_t status = checkReadFrameBufferPermission();
7615 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007616 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007617 }
7618 android::Rect rect;
7619 rect.left = samplingArea.left;
7620 rect.top = samplingArea.top;
7621 rect.right = samplingArea.right;
7622 rect.bottom = samplingArea.bottom;
7623 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007624 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007625}
7626
7627binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7628 const sp<gui::IRegionSamplingListener>& listener) {
7629 status_t status = checkReadFrameBufferPermission();
7630 if (status == OK) {
7631 status = mFlinger->removeRegionSamplingListener(listener);
7632 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007633 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007634}
7635
7636binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7637 const sp<gui::IFpsListener>& listener) {
7638 status_t status = checkReadFrameBufferPermission();
7639 if (status == OK) {
7640 status = mFlinger->addFpsListener(taskId, listener);
7641 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007642 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007643}
7644
7645binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7646 status_t status = checkReadFrameBufferPermission();
7647 if (status == OK) {
7648 status = mFlinger->removeFpsListener(listener);
7649 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007650 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007651}
7652
7653binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7654 const sp<gui::ITunnelModeEnabledListener>& listener) {
7655 status_t status = checkAccessPermission();
7656 if (status == OK) {
7657 status = mFlinger->addTunnelModeEnabledListener(listener);
7658 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007659 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007660}
7661
7662binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7663 const sp<gui::ITunnelModeEnabledListener>& listener) {
7664 status_t status = checkAccessPermission();
7665 if (status == OK) {
7666 status = mFlinger->removeTunnelModeEnabledListener(listener);
7667 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007668 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007669}
7670
7671binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7672 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7673 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7674 float appRequestRefreshRateMax) {
7675 status_t status = checkAccessPermission();
7676 if (status == OK) {
7677 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7678 static_cast<ui::DisplayModeId>(defaultMode),
7679 allowGroupSwitching, primaryRefreshRateMin,
7680 primaryRefreshRateMax,
7681 appRequestRefreshRateMin,
7682 appRequestRefreshRateMax);
7683 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007684 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007685}
7686
7687binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7688 gui::DisplayModeSpecs* outSpecs) {
7689 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007690 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007691 }
7692
7693 status_t status = checkAccessPermission();
7694 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007695 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007696 }
7697
7698 ui::DisplayModeId displayModeId;
7699 bool allowGroupSwitching;
7700 float primaryRefreshRateMin;
7701 float primaryRefreshRateMax;
7702 float appRequestRefreshRateMin;
7703 float appRequestRefreshRateMax;
7704 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7705 &allowGroupSwitching, &primaryRefreshRateMin,
7706 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7707 &appRequestRefreshRateMax);
7708 if (status == NO_ERROR) {
7709 outSpecs->defaultMode = displayModeId;
7710 outSpecs->allowGroupSwitching = allowGroupSwitching;
7711 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7712 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7713 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7714 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7715 }
7716
Huihong Luo3bdef862022-03-03 11:57:19 -08007717 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007718}
7719
Huihong Luo37396db2022-02-15 10:43:00 -08007720binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7721 bool* outSupport) {
7722 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007723 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007724}
7725
7726binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7727 const gui::DisplayBrightness& brightness) {
7728 status_t status = checkControlDisplayBrightnessPermission();
7729 if (status == OK) {
7730 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7731 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007732 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007733}
7734
7735binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7736 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7737 status_t status = checkControlDisplayBrightnessPermission();
7738 if (status == OK) {
7739 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7740 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007741 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007742}
7743
7744binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7745 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7746 status_t status = checkControlDisplayBrightnessPermission();
7747 if (status == OK) {
7748 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7749 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007750 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007751}
7752
7753binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7754 status_t status = checkAccessPermission();
7755 if (status == OK) {
7756 status = mFlinger->notifyPowerBoost(boostId);
7757 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007758 return binderStatusFromStatusT(status);
7759}
7760
7761binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7762 const gui::Color& spotColor,
7763 float lightPosY, float lightPosZ,
7764 float lightRadius) {
7765 status_t status = checkAccessPermission();
7766 if (status != OK) {
7767 return binderStatusFromStatusT(status);
7768 }
7769
7770 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7771 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7772 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7773 lightPosZ, lightRadius);
7774 return binderStatusFromStatusT(status);
7775}
7776
7777binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7778 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7779 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7780 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7781 if (status != NO_ERROR) {
7782 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7783 return binderStatusFromStatusT(status);
7784 }
7785
7786 if (!support || !support.has_value()) {
7787 outSupport->reset();
7788 } else {
7789 outSupport->emplace();
7790 outSupport->value().format = static_cast<int32_t>(support->format);
7791 outSupport->value().alphaInterpretation =
7792 static_cast<int32_t>(support->alphaInterpretation);
7793 }
7794
7795 return binder::Status::ok();
7796}
7797
7798binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
7799 status_t status;
7800 const int c_uid = IPCThreadState::self()->getCallingUid();
7801 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
7802 status = mFlinger->setOverrideFrameRate(uid, frameRate);
7803 } else {
7804 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
7805 status = PERMISSION_DENIED;
7806 }
7807 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007808}
7809
Huihong Luo02186fb2022-02-23 14:21:54 -08007810binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
7811 const sp<gui::ITransactionTraceListener>& listener) {
7812 status_t status;
7813 IPCThreadState* ipc = IPCThreadState::self();
7814 const int uid = ipc->getCallingUid();
7815 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7816 status = mFlinger->addTransactionTraceListener(listener);
7817 } else {
7818 status = PERMISSION_DENIED;
7819 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007820 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007821}
7822
7823binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
7824 *outPriority = mFlinger->getGpuContextPriority();
7825 return binder::Status::ok();
7826}
7827
7828binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
7829 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007830 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007831}
7832
7833binder::Status SurfaceComposerAIDL::addWindowInfosListener(
7834 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7835 status_t status;
7836 const int uid = IPCThreadState::self()->getCallingUid();
7837 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7838 status = mFlinger->addWindowInfosListener(windowInfosListener);
7839 } else {
7840 status = PERMISSION_DENIED;
7841 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007842 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007843}
7844
7845binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
7846 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7847 status_t status;
7848 const int uid = IPCThreadState::self()->getCallingUid();
7849 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7850 status = mFlinger->removeWindowInfosListener(windowInfosListener);
7851 } else {
7852 status = PERMISSION_DENIED;
7853 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007854 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007855}
7856
Huihong Luo07e72362022-02-14 14:26:04 -08007857status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
7858 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
7859 IPCThreadState* ipc = IPCThreadState::self();
7860 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
7861 ipc->getCallingUid());
7862 return PERMISSION_DENIED;
7863 }
7864 return OK;
7865}
7866
Huihong Luo37396db2022-02-15 10:43:00 -08007867status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
7868 IPCThreadState* ipc = IPCThreadState::self();
7869 const int pid = ipc->getCallingPid();
7870 const int uid = ipc->getCallingUid();
7871 if ((uid != AID_GRAPHICS) &&
7872 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
7873 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
7874 return PERMISSION_DENIED;
7875 }
7876 return OK;
7877}
7878
Huihong Luo02186fb2022-02-23 14:21:54 -08007879status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
7880 IPCThreadState* ipc = IPCThreadState::self();
7881 const int pid = ipc->getCallingPid();
7882 const int uid = ipc->getCallingUid();
7883 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
7884 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
7885 return PERMISSION_DENIED;
7886 }
7887 return OK;
7888}
7889
Dominik Laskowski9dab3432019-03-27 13:21:10 -07007890} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07007891
Mathias Agopian3f844832013-08-07 21:24:32 -07007892#if defined(__gl_h_)
7893#error "don't include gl/gl.h in this file"
7894#endif
7895
7896#if defined(__gl2_h_)
7897#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08007898#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08007899
7900// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01007901#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"