blob: 31037926d459a877191770e70bdcc41599564e56 [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.
Dominik Laskowskif11728a2022-07-28 13:07:42 -0700766void SurfaceFlinger::init() FTL_FAKE_GUARD(kMainThreadContext) {
Mathias Agopiana4912602012-07-12 14:25:33 -0700767 ALOGI( "SurfaceFlinger's main thread ready to run. "
768 "Initializing graphics H/W...");
Dominik Laskowskif11728a2022-07-28 13:07:42 -0700769 Mutex::Autolock lock(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.
Dominik Laskowskif11728a2022-07-28 13:07:42 -0700809 LOG_ALWAYS_FATAL_IF(!configureLocked(),
810 "Initial display configuration failed: HWC did not hotplug");
811 processDisplayChangesLocked();
812
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700813 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif11728a2022-07-28 13:07:42 -0700814 LOG_ALWAYS_FATAL_IF(!display, "Failed to configure the primary display");
815 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getPhysicalId()),
816 "Primary display is disconnected");
Jesse Hall692c7232012-11-08 15:41:56 -0800817
Mathias Agopian92a979a2012-08-02 18:32:23 -0700818 // initialize our drawing state
819 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700820
Andy McFadden13a082e2012-08-24 10:16:42 -0700821 // set initial conditions (e.g. unblank default device)
822 initializeDisplays();
823
Xiang Wang839fe5b2022-04-04 17:39:38 +0000824 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700825
Steven Thomas137d4bc2019-07-25 16:55:14 -0700826 char primeShaderCache[PROPERTY_VALUE_MAX];
827 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
828 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700829 if (setSchedFifo(false) != NO_ERROR) {
830 ALOGW("Can't set SCHED_OTHER for primeCache");
831 }
832
833 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
834
835 if (setSchedFifo(true) != NO_ERROR) {
836 ALOGW("Can't set SCHED_OTHER for primeCache");
837 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700838 }
Dan Stoza4e637772016-07-28 13:31:51 -0700839
Ady Abrahamed3290f2021-05-17 15:12:14 -0700840 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400841
Wei Wangf9b05ee2017-07-19 20:59:39 -0700842 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700843
844 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800845 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700846 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700847
848 if (mStartPropertySetThread->Start() != NO_ERROR) {
849 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800850 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800851
Dan Stoza9e56aa02015-11-02 13:00:03 -0800852 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700853}
854
Romain Guy11d63f42017-07-20 12:47:14 -0700855void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700856 Mutex::Autolock _l(mStateLock);
857
Romain Guy11d63f42017-07-20 12:47:14 -0700858 char value[PROPERTY_VALUE_MAX];
859
860 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800861 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700862 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800863 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100864
865 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700866 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800867
868 property_get("persist.sys.sf.color_mode", value, "0");
869 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700870}
871
Mathias Agopiana67e4182012-06-19 17:26:12 -0700872void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800873 // Start boot animation service by setting a property mailbox
874 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700875 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800876 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700877 if (mStartPropertySetThread->join() != NO_ERROR) {
878 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800879 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700880}
881
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800882// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800883
Brian Anderson6b376712017-04-04 10:51:39 -0700884status_t SurfaceFlinger::getSupportedFrameTimestamps(
885 std::vector<FrameEvent>* outSupported) const {
886 *outSupported = {
887 FrameEvent::REQUESTED_PRESENT,
888 FrameEvent::ACQUIRE,
889 FrameEvent::LATCH,
890 FrameEvent::FIRST_REFRESH_START,
891 FrameEvent::LAST_REFRESH_START,
892 FrameEvent::GPU_COMPOSITION_DONE,
893 FrameEvent::DEQUEUE_READY,
894 FrameEvent::RELEASE,
895 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800896
897 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
898
Ady Abrahamde549d42022-01-26 19:19:17 -0800899 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700900 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
901 }
902 return NO_ERROR;
903}
904
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800905status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
906 if (!displayToken || !state) {
907 return BAD_VALUE;
908 }
909
910 Mutex::Autolock lock(mStateLock);
911
912 const auto display = getDisplayDeviceLocked(displayToken);
913 if (!display) {
914 return NAME_NOT_FOUND;
915 }
916
917 state->layerStack = display->getLayerStack();
918 state->orientation = display->getOrientation();
919
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200920 const Rect layerStackRect = display->getLayerStackSpaceRect();
921 state->layerStackSpaceRect =
922 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800923
924 return NO_ERROR;
925}
926
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100927status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
928 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800929 if (!displayToken || !info) {
930 return BAD_VALUE;
931 }
932
933 Mutex::Autolock lock(mStateLock);
934
935 const auto display = getDisplayDeviceLocked(displayToken);
936 if (!display) {
937 return NAME_NOT_FOUND;
938 }
939
Dominik Laskowski55c85402020-01-21 16:25:47 -0800940 if (const auto connectionType = display->getConnectionType())
941 info->connectionType = *connectionType;
942 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800943 return INVALID_OPERATION;
944 }
945
946 if (mEmulatedDisplayDensity) {
947 info->density = mEmulatedDisplayDensity;
948 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100949 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800950 ? mInternalDisplayDensity
951 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800952 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700953 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800954
955 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200956 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000957 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800958
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800959 return NO_ERROR;
960}
961
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100962status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
963 ui::DynamicDisplayInfo* info) {
964 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700965 return BAD_VALUE;
966 }
967
Dominik Laskowski22488f62019-03-28 09:53:04 -0700968 Mutex::Autolock lock(mStateLock);
969
Marin Shalamanov5801c942020-12-17 17:00:13 +0100970 const auto display = getDisplayDeviceLocked(displayToken);
971 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700972 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700973 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700974
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700975 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
976 if (!displayId) {
977 return INVALID_OPERATION;
978 }
979
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800980 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700981
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100982 const auto& supportedModes = display->getSupportedModes();
983 info->supportedDisplayModes.clear();
984 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800985
986 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100987 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800988 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700989
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800990 auto [width, height] = mode->getResolution();
991 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700992
ramindani06e518e2022-03-14 18:47:53 +0000993 if (const auto physicalOrientation = display->getPhysicalOrientation();
994 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800995 std::swap(width, height);
996 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700997 }
998
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100999 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -08001000
Huan Songf7eeb102022-03-28 11:02:38 -07001001 outMode.xDpi = xDpi;
1002 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001003
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001004 const nsecs_t period = mode->getVsyncPeriod();
1005 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001006
Ady Abraham8287e852020-08-12 14:44:58 -07001007 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001008 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001009 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1010 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1011 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001012
Andy McFadden91b2ca82014-06-13 14:04:23 -07001013 // This is how far in advance a buffer must be queued for
1014 // presentation at a given time. If you want a buffer to appear
1015 // on the screen at time N, you must submit the buffer before
1016 // (N - presentationDeadline).
1017 //
1018 // Normally it's one full refresh period (to give SF a chance to
1019 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001020 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001021 // composer or panel must be accounted for here.
1022 //
1023 // We add an additional 1ms to allow for processing time and
1024 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001025 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001026
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001027 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001028 }
1029
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001030 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001031 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001032 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001033
Marin Shalamanovb173f752021-02-16 19:38:36 +01001034 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001035 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001036 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001037 info->gameContentTypeSupported =
1038 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001039
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001040 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001041
1042 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001043 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1044 if (const auto modeId = display->translateModeId(*hwcId)) {
1045 info->preferredBootDisplayMode = modeId->value();
1046 }
1047 }
1048 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001049
Dan Stoza7f7da322014-05-02 15:26:25 -07001050 return NO_ERROR;
1051}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001052
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001053status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* outStats) {
1054 if (!outStats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001055 return BAD_VALUE;
1056 }
1057
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001058 const auto& schedule = mScheduler->getVsyncSchedule();
Matt Buckley2fa85012022-08-30 22:38:45 +00001059 outStats->vsyncTime = schedule.vsyncDeadlineAfter(TimePoint::now()).ns();
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001060 outStats->vsyncPeriod = schedule.period().ns();
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001061 return NO_ERROR;
1062}
1063
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001064void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001065 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001066
1067 if (!info.mode) {
1068 ALOGW("requested display mode is null");
1069 return;
1070 }
1071 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001072 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001073 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001074 return;
1075 }
1076
Ady Abraham690f4612021-07-01 23:24:03 -07001077 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001078 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001079
Alec Mouri754c98a2019-03-18 18:53:42 -07001080 // Start receiving vsync samples now, so that we can detect a period
1081 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001082 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001083 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001084 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001085 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001086
Ady Abraham690f4612021-07-01 23:24:03 -07001087 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001088 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001089 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001090}
1091
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001092status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001093 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001094
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001095 if (!displayToken) {
1096 return BAD_VALUE;
1097 }
Ady Abraham838de062019-02-04 10:24:03 -08001098
Dominik Laskowski756b7892021-08-04 12:53:59 -07001099 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001100 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001101 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001102 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001103 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001104 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001105 }
1106
1107 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001108 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001109 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001110 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001111
1112 const auto mode = display->getMode(DisplayModeId{modeId});
1113 if (!mode) {
1114 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1115 return BAD_VALUE;
1116 }
1117
1118 const auto fps = mode->getFps();
1119 // Keep the old switching type.
1120 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001121 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001122 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1123 allowGroupSwitching,
1124 {fps, fps}};
1125 constexpr bool kOverridePolicy = false;
1126
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001127 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001128 });
1129
1130 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001131}
1132
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001133void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001134 ATRACE_CALL();
1135
Dominik Laskowski22488f62019-03-28 09:53:04 -07001136 const auto display = getDefaultDisplayDeviceLocked();
1137 if (!display) {
1138 return;
1139 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001140
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001141 const auto upcomingModeInfo =
1142 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1143
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001144 if (!upcomingModeInfo.mode) {
1145 // There is no pending mode change. This can happen if the active
1146 // display changed and the mode change happened on a different display.
1147 return;
1148 }
1149
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001150 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001151 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1152 // We need to generate new sequenceId in order to recreate the display (and this
1153 // way the framebuffer).
1154 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001155 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001156 processDisplayChangesLocked();
1157
1158 // processDisplayChangesLocked will update all necessary components so we're done here.
1159 return;
1160 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001161
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001162 // We just created this display so we can call even if we are not on the main thread.
1163 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001164 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001165
Ady Abraham690f4612021-07-01 23:24:03 -07001166 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001167 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001168 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001169
Dominik Laskowski068173d2021-08-11 17:22:59 -07001170 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001171 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001172 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001173}
1174
Ady Abraham690f4612021-07-01 23:24:03 -07001175void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1176 display->clearDesiredActiveModeState();
1177 if (isDisplayActiveLocked(display)) {
1178 mScheduler->setModeChangePending(false);
1179 }
Ady Abraham53852a52019-05-28 18:07:44 -07001180}
1181
Ady Abraham690f4612021-07-01 23:24:03 -07001182void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1183 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1184 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001185 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001186 updatePhaseConfiguration(refreshRate);
1187}
1188
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001189void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001190 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001191
Marin Shalamanovdd594312021-11-09 16:37:37 +01001192 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1193
Ady Abraham690f4612021-07-01 23:24:03 -07001194 for (const auto& iter : mDisplays) {
1195 const auto& display = iter.second;
1196 if (!display || !display->isInternal()) {
1197 continue;
1198 }
1199
1200 // Store the local variable to release the lock.
1201 const auto desiredActiveMode = display->getDesiredActiveMode();
1202 if (!desiredActiveMode) {
1203 // No desired active mode pending to be applied
1204 continue;
1205 }
1206
1207 if (!isDisplayActiveLocked(display)) {
1208 // display is no longer the active display, so abort the mode change
1209 clearDesiredActiveModeState(display);
1210 continue;
1211 }
1212
1213 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1214 if (!desiredMode) {
1215 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1216 desiredActiveMode->mode->getId().value());
1217 clearDesiredActiveModeState(display);
1218 continue;
1219 }
1220
1221 const auto refreshRate = desiredMode->getFps();
1222 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1223 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1224 to_string(display->getId()).c_str());
1225
1226 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001227 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001228 desiredActiveModeChangeDone(display);
1229 continue;
1230 }
1231
1232 // Desired active mode was set, it is different than the mode currently in use, however
1233 // allowed modes might have changed by the time we process the refresh.
1234 // Make sure the desired mode is still allowed
1235 const auto displayModeAllowed =
1236 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1237 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001238 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001239 continue;
1240 }
1241
1242 // TODO(b/142753666) use constrains
1243 hal::VsyncPeriodChangeConstraints constraints;
1244 constraints.desiredTimeNanos = systemTime();
1245 constraints.seamlessRequired = false;
1246 hal::VsyncPeriodChangeTimeline outTimeline;
1247
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001248 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1249 display->initiateModeChange(*desiredActiveMode,
1250 constraints, &outTimeline));
1251
Ady Abraham690f4612021-07-01 23:24:03 -07001252 if (status != NO_ERROR) {
1253 // initiateModeChange may fail if a hotplug event is just about
1254 // to be sent. We just log the error in this case.
1255 ALOGW("initiateModeChange failed: %d", status);
1256 continue;
1257 }
1258 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1259
Marin Shalamanovdd594312021-11-09 16:37:37 +01001260 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001261 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001262 mSetActiveModePending = true;
1263 } else {
1264 // Updating the internal state should be done outside the loop,
1265 // because it can recreate a DisplayDevice and modify mDisplays
1266 // which will invalidate the iterator.
1267 displayToUpdateImmediately = display->getPhysicalId();
1268 }
1269 }
1270
1271 if (displayToUpdateImmediately) {
1272 updateInternalStateWithChangedMode();
1273
1274 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1275 const auto desiredActiveMode = display->getDesiredActiveMode();
1276 if (desiredActiveMode &&
1277 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1278 desiredActiveModeChangeDone(display);
1279 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001280 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001281}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001282
Alec Mouridea1ac52021-06-23 18:12:18 -07001283void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001284 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001285 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001286 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001287 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001288 for (const auto& [_, display] : mDisplays) {
1289 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001290 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001291 }
1292 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001293 });
1294
1295 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001296}
1297
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001298std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1299 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001300
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001301 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001302 // filter out all wide color modes. The typical reason why this happens is that the
1303 // hardware is not good enough to support GPU composition of wide color, and thus the
1304 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001305 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1306 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001307 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1308 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001309 }
Michael Wright28f24d02016-07-12 13:30:53 -07001310
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001311 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001312}
1313
Daniel Solomon42d04562019-01-20 21:03:19 -08001314status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001315 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001316 if (!displayToken) {
1317 return BAD_VALUE;
1318 }
1319
Dominik Laskowski3c363242022-04-07 10:44:12 -07001320 Mutex::Autolock lock(mStateLock);
1321
1322 const auto display = getDisplayDeviceLocked(displayToken);
1323 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001324 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001325 }
1326
Dominik Laskowski3c363242022-04-07 10:44:12 -07001327 const auto connectionType = display->getConnectionType();
1328 if (connectionType != ui::DisplayConnectionType::Internal) {
1329 return INVALID_OPERATION;
1330 }
1331
1332 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1333 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001334 return NO_ERROR;
1335}
1336
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001337status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001338 if (!displayToken) {
1339 return BAD_VALUE;
1340 }
1341
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001342 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001343 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001344 if (!display) {
1345 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1346 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001347 return NAME_NOT_FOUND;
1348 }
1349
1350 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001351 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1352 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001353 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001354 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001355
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001356 const auto modes = getDisplayColorModes(*display);
1357 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1358
1359 if (mode < ColorMode::NATIVE || !exists) {
1360 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1361 decodeColorMode(mode).c_str(), mode, displayToken.get());
1362 return BAD_VALUE;
1363 }
1364
1365 display->getCompositionDisplay()->setColorProfile(
1366 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1367
1368 return NO_ERROR;
1369 });
1370
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001371 // TODO(b/195698395): Propagate error.
1372 future.wait();
1373 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001374}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001375
Kriti Dang7defaf32021-11-15 11:55:43 +01001376status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001377 auto future = mScheduler->schedule(
1378 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1379
1380 *outSupport = future.get();
1381 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001382}
1383
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001384status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1385 ui::DisplayModeId modeId) {
1386 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001387 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001388 const auto display = getDisplayDeviceLocked(displayToken);
1389 if (!display) {
1390 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1391 return NAME_NOT_FOUND;
1392 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001393
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001394 if (display->isVirtual()) {
1395 ALOGE("%s: Invalid operation on virtual display", whence);
1396 return INVALID_OPERATION;
1397 }
1398
1399 const auto displayId = display->getPhysicalId();
1400 const auto mode = display->getMode(DisplayModeId{modeId});
1401 if (!mode) {
1402 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1403 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001404 return BAD_VALUE;
1405 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001406
1407 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001408 });
1409 return future.get();
1410}
1411
1412status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001413 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001414 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001415 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1416 return getHwComposer().clearBootDisplayMode(*displayId);
1417 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001418 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001419 return BAD_VALUE;
1420 }
1421 });
1422 return future.get();
1423}
1424
Galia Peycheva5492cb52019-10-30 14:13:16 +01001425void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001426 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001427 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001428 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1429 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1430 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001431 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001432 }
1433 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001434}
1435
Galia Peycheva5492cb52019-10-30 14:13:16 +01001436void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001437 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001438 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001439 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001440 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001441 getHwComposer().setContentType(*displayId, type);
1442 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001443 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001444 }
1445 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001446}
1447
Kriti Dang49ad4132021-01-08 11:49:56 +01001448status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1449 const std::vector<ui::Hdr>& hdrTypes) {
1450 Mutex::Autolock lock(mStateLock);
1451
1452 auto display = getDisplayDeviceLocked(displayToken);
1453 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001454 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001455 return NAME_NOT_FOUND;
1456 }
1457
1458 display->overrideHdrTypes(hdrTypes);
1459 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1460 return NO_ERROR;
1461}
1462
Tej Singhe2751772021-04-06 22:05:29 -07001463status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1464 *success = mTimeStats->onPullAtom(atomId, pulledData);
1465 return NO_ERROR;
1466}
1467
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001468status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1469 ui::PixelFormat* outFormat,
1470 ui::Dataspace* outDataspace,
1471 uint8_t* outComponentMask) const {
1472 if (!outFormat || !outDataspace || !outComponentMask) {
1473 return BAD_VALUE;
1474 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001475
1476 Mutex::Autolock lock(mStateLock);
1477
1478 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1479 if (!displayId) {
1480 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001481 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001482
1483 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001484 outDataspace, outComponentMask);
1485}
1486
Kevin DuBois74e53772018-11-19 10:52:38 -08001487status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1488 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001489 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001490 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001491 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001492 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1493 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1494 componentMask, maxFrames);
1495 } else {
1496 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1497 return NAME_NOT_FOUND;
1498 }
1499 });
1500
1501 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001502}
1503
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001504status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1505 uint64_t maxFrames, uint64_t timestamp,
1506 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001507 Mutex::Autolock lock(mStateLock);
1508
1509 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1510 if (!displayId) {
1511 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001512 }
1513
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001514 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001515}
1516
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001517status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1518 if (!outSupported) {
1519 return BAD_VALUE;
1520 }
1521 *outSupported = getRenderEngine().supportsProtectedContent();
1522 return NO_ERROR;
1523}
1524
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001525status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1526 bool* outIsWideColorDisplay) const {
1527 if (!displayToken || !outIsWideColorDisplay) {
1528 return BAD_VALUE;
1529 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001530
1531 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001532 const auto display = getDisplayDeviceLocked(displayToken);
1533 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001534 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001535 }
Peiyong Linff84a152019-05-17 18:36:19 -07001536
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001537 *outIsWideColorDisplay =
1538 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001539 return NO_ERROR;
1540}
1541
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001542status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001543 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001544 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001545
Dominik Laskowski6505f792019-09-18 11:10:05 -07001546 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001547 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001548 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001549 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001550
Dominik Laskowski756b7892021-08-04 12:53:59 -07001551 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001552 return NO_ERROR;
1553}
1554
1555status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001556 Mutex::Autolock lock(mStateLock);
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001557 const nsecs_t expectedPresentTime = calculateExpectedPresentTime(TimePoint::fromNs(when)).ns();
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001558 const nsecs_t deadlineTimestamp = expectedPresentTime;
1559 return mScheduler->injectVSync(when, expectedPresentTime, deadlineTimestamp) ? NO_ERROR
1560 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001561}
1562
Huihong Luo05539a12022-02-23 10:29:40 -08001563status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001564 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001565 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001566 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001567 mDrawingState.traverseInZOrder([&](Layer* layer) {
1568 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1569 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001570 });
1571
1572 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001573 return NO_ERROR;
1574}
1575
Peiyong Linc6780972018-10-28 15:24:08 -07001576status_t SurfaceFlinger::getCompositionPreference(
1577 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1578 Dataspace* outWideColorGamutDataspace,
1579 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001580 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001581 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001582 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001583 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001584 return NO_ERROR;
1585}
1586
Dan Stozaec460082018-12-17 15:35:09 -08001587status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1588 const sp<IBinder>& stopLayerHandle,
1589 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001590 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001591 return BAD_VALUE;
1592 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001593
1594 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1595 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001596 return NO_ERROR;
1597}
1598
Dan Stozaec460082018-12-17 15:35:09 -08001599status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001600 if (!listener) {
1601 return BAD_VALUE;
1602 }
Dan Stozaec460082018-12-17 15:35:09 -08001603 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001604 return NO_ERROR;
1605}
Dan Gittik57e63c52019-01-18 16:37:54 +00001606
Alec Mouria9a68a62021-03-04 19:14:50 -08001607status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001608 if (!listener) {
1609 return BAD_VALUE;
1610 }
1611
Alec Mouria9a68a62021-03-04 19:14:50 -08001612 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001613 return NO_ERROR;
1614}
1615
1616status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1617 if (!listener) {
1618 return BAD_VALUE;
1619 }
1620 mFpsReporter->removeListener(listener);
1621 return NO_ERROR;
1622}
1623
Galia Peycheva8f04b302021-04-27 13:25:38 +02001624status_t SurfaceFlinger::addTunnelModeEnabledListener(
1625 const sp<gui::ITunnelModeEnabledListener>& listener) {
1626 if (!listener) {
1627 return BAD_VALUE;
1628 }
1629
1630 mTunnelModeEnabledReporter->addListener(listener);
1631 return NO_ERROR;
1632}
1633
1634status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1635 const sp<gui::ITunnelModeEnabledListener>& listener) {
1636 if (!listener) {
1637 return BAD_VALUE;
1638 }
1639
1640 mTunnelModeEnabledReporter->removeListener(listener);
1641 return NO_ERROR;
1642}
1643
Dan Gittik57e63c52019-01-18 16:37:54 +00001644status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1645 bool* outSupport) const {
1646 if (!displayToken || !outSupport) {
1647 return BAD_VALUE;
1648 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001649
1650 Mutex::Autolock lock(mStateLock);
1651
Dan Gittik57e63c52019-01-18 16:37:54 +00001652 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1653 if (!displayId) {
1654 return NAME_NOT_FOUND;
1655 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001656 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001657 return NO_ERROR;
1658}
1659
Alec Mouricdf16792021-12-10 13:16:06 -08001660bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1661 bool hasHdrLayers = false;
1662 mDrawingState.traverse([&,
1663 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1664 hasHdrLayers |= (layer->isVisible() &&
1665 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1666 isHdrDataspace(layer->getDataSpace()));
1667 });
1668 return hasHdrLayers;
1669}
1670
John Reck22be6962021-03-10 12:59:54 -05001671status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1672 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001673 if (!displayToken) {
1674 return BAD_VALUE;
1675 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001676
Dominik Laskowski756b7892021-08-04 12:53:59 -07001677 const char* const whence = __func__;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001678 return ftl::Future(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001679 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001680 const bool supportsDisplayBrightnessCommand =
1681 getHwComposer().getComposer()->isSupported(
1682 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1683 // If we support applying display brightness as a command, then we also support
1684 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001685 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001686 auto compositionDisplay = display->getCompositionDisplay();
1687 float currentDimmingRatio =
1688 compositionDisplay->editState().sdrWhitePointNits /
1689 compositionDisplay->editState().displayBrightnessNits;
1690 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1691 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001692 FTL_FAKE_GUARD(kMainThreadContext,
1693 display->stageBrightness(brightness.displayBrightness));
1694
Alec Mouri6da0e272022-02-07 12:45:57 -08001695 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1696 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001697 scheduleComposite(FrameHint::kNone);
1698 } else {
1699 scheduleCommit(FrameHint::kNone);
1700 }
1701 return ftl::yield<status_t>(OK);
1702 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001703 return getHwComposer()
1704 .setDisplayBrightness(display->getPhysicalId(),
1705 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001706 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001707 Hwc2::Composer::DisplayBrightnessOptions{
1708 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001709 }
Alec Mouricdf16792021-12-10 13:16:06 -08001710
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001711 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001712 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001713 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001714 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001715 }))
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001716 .then([](ftl::Future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001717 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001718}
1719
John Reck88270902021-03-18 11:27:35 -04001720status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1721 const sp<gui::IHdrLayerInfoListener>& listener) {
1722 if (!displayToken) {
1723 return BAD_VALUE;
1724 }
1725
1726 Mutex::Autolock lock(mStateLock);
1727
1728 const auto display = getDisplayDeviceLocked(displayToken);
1729 if (!display) {
1730 return NAME_NOT_FOUND;
1731 }
1732 const auto displayId = display->getId();
1733 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1734 if (!hdrInfoReporter) {
1735 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1736 }
1737 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001738
1739
1740 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001741 return OK;
1742}
1743
1744status_t SurfaceFlinger::removeHdrLayerInfoListener(
1745 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1746 if (!displayToken) {
1747 return BAD_VALUE;
1748 }
1749
1750 Mutex::Autolock lock(mStateLock);
1751
1752 const auto display = getDisplayDeviceLocked(displayToken);
1753 if (!display) {
1754 return NAME_NOT_FOUND;
1755 }
1756 const auto displayId = display->getId();
1757 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1758 if (hdrInfoReporter) {
1759 hdrInfoReporter->removeListener(listener);
1760 }
1761 return OK;
1762}
1763
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001764status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001765 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001766 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001767
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001768 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001769 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001770 }
1771
1772 return NO_ERROR;
1773}
1774
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001775status_t SurfaceFlinger::getDisplayDecorationSupport(
1776 const sp<IBinder>& displayToken,
1777 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001778 if (!displayToken || !outSupport) {
1779 return BAD_VALUE;
1780 }
1781
1782 Mutex::Autolock lock(mStateLock);
1783
1784 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1785 if (!displayId) {
1786 return NAME_NOT_FOUND;
1787 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001788 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001789 return NO_ERROR;
1790}
1791
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001792// ----------------------------------------------------------------------------
1793
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001794sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001795 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001796 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001797 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1798 ? mSfConnectionHandle
1799 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001800
Ady Abraham62f216c2020-10-13 19:07:23 -07001801 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001802}
1803
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001804void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001805 if (hint == FrameHint::kActive) {
1806 mScheduler->resetIdleTimer();
1807 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001808 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001809 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001810}
1811
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001812void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1813 mMustComposite = true;
1814 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001815}
1816
1817void SurfaceFlinger::scheduleRepaint() {
1818 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001819 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001820}
1821
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001822void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001823 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001824}
1825
Ady Abraham2492a022020-07-24 11:09:55 -07001826nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001827 if (const auto display = getDefaultDisplayDeviceLocked()) {
1828 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001829 }
1830
Marin Shalamanov045b7002021-01-07 16:56:24 +01001831 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001832}
1833
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001834void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1835 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001836 const std::string tracePeriod = [vsyncPeriod]() {
1837 if (ATRACE_ENABLED() && vsyncPeriod) {
1838 std::stringstream ss;
1839 ss << "(" << *vsyncPeriod << ")";
1840 return ss.str();
1841 }
1842 return std::string();
1843 }();
1844 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001845
Steven Thomas3cfac282017-02-06 12:29:30 -08001846 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001847 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1848 if (displayId) {
1849 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1850 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001851 display->onVsync(timestamp);
1852 }
1853
Dominik Laskowski075d3172018-05-24 15:50:06 -07001854 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001855 return;
1856 }
1857
Ady Abrahame1166472021-07-15 10:56:06 -07001858 const bool isActiveDisplay =
1859 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1860 if (!isActiveDisplay) {
1861 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001862 return;
1863 }
1864
Alec Mourif8e689c2019-05-20 18:32:22 -07001865 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001866 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001867 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001868 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001869 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001870}
1871
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001872void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1873 hal::Connection connection) {
Dominik Laskowskif11728a2022-07-28 13:07:42 -07001874 {
1875 std::lock_guard<std::mutex> lock(mHotplugMutex);
1876 mPendingHotplugEvents.push_back(HotplugEvent{hwcDisplayId, connection});
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001877 }
1878
Dominik Laskowskif11728a2022-07-28 13:07:42 -07001879 if (mScheduler) {
1880 mScheduler->scheduleConfigure();
1881 }
Mathias Agopian86303202012-07-24 22:46:10 -07001882}
1883
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001884void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1885 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001886 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001887 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001888
1889 if (timeline.refreshRequired) {
1890 scheduleComposite(FrameHint::kNone);
1891 }
Ady Abraham7159f572019-10-11 11:10:18 -07001892}
1893
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001894void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001895 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001896 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1897}
1898
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001899void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001900 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001901 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001902}
1903
Yichi Chen3401b562022-01-17 15:42:35 +08001904void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001905 ATRACE_CALL();
1906 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001907}
1908
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001909void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001910 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001911
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001912 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001913 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001914 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001915
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001916 if (const auto display = getDefaultDisplayDeviceLocked();
1917 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001918 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001919 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001920 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001921}
1922
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001923auto SurfaceFlinger::getPreviousPresentFence(TimePoint frameTime, Period vsyncPeriod)
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001924 -> const FenceTimePtr& {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001925 const bool isTwoVsyncsAhead = mExpectedPresentTime - frameTime > vsyncPeriod;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001926 const size_t i = static_cast<size_t>(isTwoVsyncsAhead);
1927 return mPreviousPresentFences[i].fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001928}
1929
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001930bool SurfaceFlinger::isFencePending(const FenceTimePtr& fence, int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001931 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001932 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001933 return false;
1934 }
1935
Dan Stoza59083052020-04-28 10:13:20 -07001936 const status_t status = fence->wait(graceTimeMs);
1937 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1938 // which calls wait(0) again internally
1939 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001940}
1941
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001942TimePoint SurfaceFlinger::calculateExpectedPresentTime(TimePoint frameTime) const {
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001943 const auto& schedule = mScheduler->getVsyncSchedule();
Alec Mouri6d414b52020-03-17 11:18:05 -07001944
Dominik Laskowski08fbd852022-07-14 08:53:42 -07001945 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(frameTime);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001946 if (mVsyncModulator->getVsyncConfig().sfOffset > 0) {
1947 return vsyncDeadline;
Alec Mouri6d414b52020-03-17 11:18:05 -07001948 }
1949
Dominik Laskowski5d164f22022-07-07 07:56:07 -07001950 // Inflate the expected present time if we're targeting the next vsync.
1951 return vsyncDeadline + schedule.period();
Alec Mouriaa614192019-06-06 13:28:34 -07001952}
1953
Dominik Laskowskif11728a2022-07-28 13:07:42 -07001954void SurfaceFlinger::configure() FTL_FAKE_GUARD(kMainThreadContext) {
1955 Mutex::Autolock lock(mStateLock);
1956 if (configureLocked()) {
1957 setTransactionFlags(eDisplayTransactionNeeded);
1958 }
1959}
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,
Matt Buckley2fa85012022-08-30 22:38:45 +00001975 ticks<std::milli, float>(mExpectedPresentTime - TimePoint::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 Buckley2fa85012022-08-30 22:38:45 +00002062 const Period vsyncPeriod = Period::fromNs(display->getActiveMode()->getVsyncPeriod());
2063 mPowerAdvisor->setCommitStart(frameTime);
2064 mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime);
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002065
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
Matt Buckley2fa85012022-08-30 22:38:45 +00002070 mPowerAdvisor->setFrameDelay(frameDelay);
2071 mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration);
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 Buckley2fa85012022-08-30 22:38:45 +00002231 mPowerAdvisor->setSfPresentTiming(TimePoint::fromNs(mPreviousPresentFences[0]
2232 .fenceTime->getSignalTime()),
2233 TimePoint::now());
Matt Buckley50c44062022-01-17 20:48:10 +00002234 if (mPowerHintSessionMode.late) {
2235 mPowerAdvisor->sendActualWorkDuration();
2236 }
2237 }
2238
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002239 if (mScheduler->onPostComposition(presentTime)) {
2240 scheduleComposite(FrameHint::kNone);
2241 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002242
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002243 postComposition();
2244
Midas Chien50f52e22020-09-26 17:57:42 +08002245 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002246
Vishnu Nair9cf89262022-02-26 09:17:49 -08002247 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2248 TimeStats::ClientCompositionRecord clientCompositionRecord;
2249 for (const auto& [_, display] : displays) {
2250 const auto& state = display->getCompositionDisplay()->getState();
2251 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2252 mHadDeviceComposition |= state.usesDeviceComposition;
2253 mReusedClientComposition |= state.reusedClientComposition;
2254 clientCompositionRecord.predicted |=
2255 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2256 clientCompositionRecord.predictionSucceeded |=
2257 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002258 }
2259
Vishnu Nair9cf89262022-02-26 09:17:49 -08002260 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2261 clientCompositionRecord.reused = mReusedClientComposition;
2262 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2263 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2264
Yichi Chen28dee2c2020-07-06 21:24:14 +08002265 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002266 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2267 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002268
David Sodman7e4ae112018-02-09 15:02:28 -08002269 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002270 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002271 // This will block and should only be used for debugging.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07002272 mLayerTracing.notify(mVisibleRegionsDirty, frameTime.ns(), vsyncId.value);
Vishnu Nairdf529052019-06-07 14:53:14 -07002273 }
Robert Carr167bdde2021-07-28 11:26:51 -07002274
2275 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002276 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002277
2278 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002279 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002280 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002281
Matt Buckley50c44062022-01-17 20:48:10 +00002282 if (mPowerHintSessionEnabled) {
Matt Buckley2fa85012022-08-30 22:38:45 +00002283 mPowerAdvisor->setCompositeEnd(TimePoint::now());
Matt Buckleyef51fba2021-10-12 19:30:12 +00002284 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002285}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002286
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002287void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002288 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002289
Vishnu Nair4351ad52019-02-11 14:13:02 -08002290 if (mVisibleRegionsDirty) {
2291 computeLayerBounds();
2292 }
2293
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002294 for (auto& layer : mLayersPendingRefresh) {
2295 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002296 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002297 invalidateLayerStack(layer, visibleReg);
2298 }
2299 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002300}
2301
John Reck49d9ad32022-02-23 19:03:31 -05002302bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002303 // Treat all layers as non-HDR if:
2304 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2305 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2306 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2307 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2308 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002309 return false;
2310 }
2311 if (mIgnoreHdrCameraLayers) {
2312 auto buffer = layer->getBuffer();
2313 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2314 return false;
2315 }
2316 }
2317 return true;
2318}
2319
ramindani06e518e2022-03-14 18:47:53 +00002320ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2321 bool isPrimary) const {
2322 const auto id = PhysicalDisplayId::tryCast(displayId);
2323 if (!id) {
2324 return ui::ROTATION_0;
2325 }
2326 if (getHwComposer().getComposer()->isSupported(
2327 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2328 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2329 case Hwc2::AidlTransform::ROT_90:
2330 return ui::ROTATION_90;
2331 case Hwc2::AidlTransform::ROT_180:
2332 return ui::ROTATION_180;
2333 case Hwc2::AidlTransform::ROT_270:
2334 return ui::ROTATION_270;
2335 default:
2336 return ui::ROTATION_0;
2337 }
2338 }
2339
2340 if (isPrimary) {
2341 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2342 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2343 case Values::ORIENTATION_90:
2344 return ui::ROTATION_90;
2345 case Values::ORIENTATION_180:
2346 return ui::ROTATION_180;
2347 case Values::ORIENTATION_270:
2348 return ui::ROTATION_270;
2349 default:
2350 break;
2351 }
2352 }
2353 return ui::ROTATION_0;
2354}
2355
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002356void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002357 ATRACE_CALL();
Dominik Laskowski8792c112022-07-12 09:03:39 -07002358 ALOGV(__func__);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002359
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002360 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002361
2362 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002363 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002364 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002365 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002366 ->getRenderSurface()
2367 ->getClientTargetAcquireFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002368 } else {
2369 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2370 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002371
Ady Abrahambe0f9482019-04-24 15:41:53 -07002372 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002373
Dominik Laskowski8792c112022-07-12 09:03:39 -07002374 auto presentFence =
2375 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
2376
2377 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
2378 mPreviousPresentFences[0] = {presentFence, presentFenceTime};
2379
Matt Buckley2fa85012022-08-30 22:38:45 +00002380 const TimePoint presentTime = TimePoint::now();
Vishnu Nair9a69a042021-06-18 13:19:49 -07002381
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002382 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2383 // information from previous' frame classification is already available when sending jank info
2384 // to clients, so they get jank classification as early as possible.
Dominik Laskowski8792c112022-07-12 09:03:39 -07002385 mFrameTimeline->setSfPresent(presentTime.ns(), presentFenceTime, glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002386
Lloyd Piqueab039b52019-02-13 14:22:42 -08002387 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2388 // be sampled a little later than when we started doing work for this frame,
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002389 // but that should be okay since CompositorTiming has snapping logic.
Dominik Laskowski80c77272022-07-08 12:47:29 -07002390 const TimePoint compositeTime =
2391 TimePoint::fromNs(mCompositionEngine->getLastFrameRefreshTimestamp());
2392 const Duration presentLatency =
Dominik Laskowski8792c112022-07-12 09:03:39 -07002393 mPresentLatencyTracker.trackPendingFrame(compositeTime, presentFenceTime);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002394
2395 const auto& schedule = mScheduler->getVsyncSchedule();
Dominik Laskowski8792c112022-07-12 09:03:39 -07002396 const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(presentTime);
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002397 const Period vsyncPeriod = schedule.period();
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002398 const nsecs_t vsyncPhase = mVsyncConfiguration->getCurrentConfigs().late.sfOffset;
Dominik Laskowski5d164f22022-07-07 07:56:07 -07002399
Dominik Laskowski5a5e01e2022-07-08 07:52:44 -07002400 const CompositorTiming compositorTiming(vsyncDeadline.ns(), vsyncPeriod.ns(), vsyncPhase,
Dominik Laskowski80c77272022-07-08 12:47:29 -07002401 presentLatency.ns());
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002402
Robert Carrc747ad02021-06-11 14:01:24 -07002403 for (const auto& layer: mLayersWithQueuedFrames) {
Dominik Laskowski8792c112022-07-12 09:03:39 -07002404 layer->onPostComposition(display, glCompositionDoneFenceTime, presentFenceTime,
2405 compositorTiming);
2406 layer->releasePendingBuffer(presentTime.ns());
Robert Carrc747ad02021-06-11 14:01:24 -07002407 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002408
John Reck88270902021-03-18 11:27:35 -04002409 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2410 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002411 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002412 {
2413 Mutex::Autolock lock(mStateLock);
2414 if (mFpsReporter) {
2415 mFpsReporter->dispatchLayerFps();
2416 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002417
2418 if (mTunnelModeEnabledReporter) {
2419 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2420 }
John Reck88270902021-03-18 11:27:35 -04002421 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002422 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2423 if (reporter && reporter->hasListeners()) {
2424 if (const auto display = getDisplayDeviceLocked(displayId)) {
2425 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002426 }
2427 }
2428 }
Robert Carr167bdde2021-07-28 11:26:51 -07002429 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2430 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002431 }
2432
Robert Carr167bdde2021-07-28 11:26:51 -07002433 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2434 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2435 HdrLayerInfoReporter::HdrLayerInfo info;
2436 int32_t maxArea = 0;
2437 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2438 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002439 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002440 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002441 const auto* outputLayer =
2442 compositionDisplay->getOutputLayerForLayer(layerFe);
2443 if (outputLayer) {
2444 info.numberOfHdrLayers++;
2445 const auto displayFrame = outputLayer->getState().displayFrame;
2446 const int32_t area = displayFrame.width() * displayFrame.height();
2447 if (area > maxArea) {
2448 maxArea = area;
2449 info.maxW = displayFrame.width();
2450 info.maxH = displayFrame.height();
2451 }
John Reckdb1a16b2021-07-09 13:05:52 -04002452 }
John Reck88270902021-03-18 11:27:35 -04002453 }
2454 }
Robert Carr167bdde2021-07-28 11:26:51 -07002455 });
2456 listener->dispatchHdrLayerInfo(info);
2457 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002458 }
2459
Robert Carr167bdde2021-07-28 11:26:51 -07002460 mSomeDataspaceChanged = false;
2461 mVisibleRegionsWereDirtyThisFrame = false;
2462
Dominik Laskowski8792c112022-07-12 09:03:39 -07002463 mTransactionCallbackInvoker.addPresentFence(std::move(presentFence));
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002464 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002465 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002466
Dominik Laskowski8792c112022-07-12 09:03:39 -07002467 mTimeStats->incrementTotalFrames();
2468 mTimeStats->setPresentFenceGlobal(presentFenceTime);
2469
Ady Abrahamed3290f2021-05-17 15:12:14 -07002470 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Dominik Laskowski8792c112022-07-12 09:03:39 -07002471 presentFenceTime->isValid()) {
2472 mScheduler->addPresentFence(std::move(presentFenceTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002473 }
2474
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002475 const bool isDisplayConnected =
2476 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002477
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002478 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002479 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002480 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002481 }
2482 }
2483
Alec Mouri717bcb62020-02-10 17:07:19 -08002484 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2485 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2486 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2487
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002488 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002489 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002490 return;
2491 }
2492
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002493 // Cleanup any outstanding resources due to rendering a prior frame.
2494 getRenderEngine().cleanupPostRender();
2495
Dan Stoza436ccf32018-06-21 12:10:12 -07002496 {
2497 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002498 if (mTexturePool.size() < mTexturePoolSize) {
2499 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002500 const size_t offset = mTexturePool.size();
2501 mTexturePool.resize(mTexturePoolSize);
2502 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2503 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002504 } else if (mTexturePool.size() > mTexturePoolSize) {
2505 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2506 const size_t offset = mTexturePoolSize;
2507 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2508 mTexturePool.resize(mTexturePoolSize);
2509 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002510 }
2511 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002512
Dan Stoza45de5ba2019-04-25 14:12:09 -07002513 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2514 // side-effect of getTotalSize(), so we check that again here
2515 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002516 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002517 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2518 }
Dominik Laskowski8792c112022-07-12 09:03:39 -07002519
2520 logFrameStats(presentTime);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002521}
2522
chaviw79468ab2021-10-27 11:11:24 -05002523FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002524 const ui::Size maxSize = [this] {
2525 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002526
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002527 // The LayerTraceGenerator tool runs without displays.
2528 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002529
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002530 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2531 [](ui::Size size, const auto& pair) -> ui::Size {
2532 const auto& display = pair.second;
2533 return {std::max(size.getWidth(), display->getWidth()),
2534 std::max(size.getHeight(), display->getHeight())};
2535 });
2536 }();
chaviwb09c6552021-08-12 17:20:43 -05002537
2538 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2539 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002540 const float xMax = maxSize.getWidth() * 10.f;
2541 const float yMax = maxSize.getHeight() * 10.f;
2542
2543 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002544}
2545
2546void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002547 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002548 for (const auto& layer : mDrawingState.layersSortedByZ) {
2549 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002550 }
2551}
2552
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002553void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002554 ATRACE_CALL();
2555
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002556 // Keep a copy of the drawing state (that is going to be overwritten
2557 // by commitTransactionsLocked) outside of mStateLock so that the side
2558 // effects of the State assignment don't happen with mStateLock held,
2559 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002560 State drawingState(mDrawingState);
2561
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002562 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002563 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564
Mathias Agopianca4d3602011-05-19 15:38:14 -07002565 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002566 // so we can call commitTransactionsLocked unconditionally.
2567 // We clear the flags with mStateLock held to guarantee that
2568 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002569 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002570 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002571
Mathias Agopianca4d3602011-05-19 15:38:14 -07002572 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002573}
2574
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002575std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2576 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002577 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2578 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002579
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002580 int attempt = 0;
2581 constexpr int kMaxAttempts = 3;
2582 do {
2583 hwcModes = getHwComposer().getModes(displayId);
2584 activeModeHwcId = getHwComposer().getActiveMode(displayId);
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002585
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002586 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
Dominik Laskowskibab51282022-08-12 09:28:55 -07002587 return mode.hwcId == activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002588 };
2589
2590 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2591 break;
2592 }
2593 } while (++attempt < kMaxAttempts);
2594
Dominik Laskowskibab51282022-08-12 09:28:55 -07002595 if (attempt == kMaxAttempts) {
2596 const std::string activeMode =
2597 activeModeHwcId ? std::to_string(*activeModeHwcId) : "unknown"s;
2598 ALOGE("HWC failed to report an active mode that is supported: activeModeHwcId=%s, "
2599 "hwcModes={%s}",
2600 activeMode.c_str(), base::Join(hwcModes, ", ").c_str());
2601 return {};
2602 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002603
2604 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002605 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2606 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002607 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002608
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002609 ui::DisplayModeId nextModeId = 1 +
2610 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2611 [](ui::DisplayModeId max, const auto& pair) {
2612 return std::max(max, pair.first.value());
2613 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002614
2615 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002616 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002617 const DisplayModeId id{nextModeId++};
2618 newModes.try_emplace(id,
2619 DisplayMode::Builder(hwcMode.hwcId)
2620 .setId(id)
2621 .setPhysicalDisplayId(displayId)
2622 .setResolution({hwcMode.width, hwcMode.height})
2623 .setVsyncPeriod(hwcMode.vsyncPeriod)
2624 .setDpiX(hwcMode.dpiX)
2625 .setDpiY(hwcMode.dpiY)
2626 .setGroup(hwcMode.configGroup)
2627 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002628 }
2629
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002630 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002631 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002632 [](const auto& lhs, const auto& rhs) {
2633 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002634 });
2635
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002636 // Keep IDs if modes have not changed.
2637 const auto& modes = sameModes ? oldModes : newModes;
2638 const DisplayModePtr activeMode =
2639 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2640 return pair.second->getHwcId() == activeModeHwcId;
2641 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002642
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002643 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002644}
2645
Dominik Laskowskif11728a2022-07-28 13:07:42 -07002646bool SurfaceFlinger::configureLocked() {
2647 std::vector<HotplugEvent> events;
2648 {
2649 std::lock_guard<std::mutex> lock(mHotplugMutex);
2650 events = std::move(mPendingHotplugEvents);
2651 }
2652
Dominik Laskowskibb66e632022-08-17 08:00:25 -07002653 for (const auto [hwcDisplayId, connection] : events) {
2654 if (auto info = getHwComposer().onHotplug(hwcDisplayId, connection)) {
2655 const auto displayId = info->id;
2656 const bool connected = connection == hal::Connection::CONNECTED;
Lloyd Piqueba04e622017-12-14 17:11:26 -08002657
Dominik Laskowskibb66e632022-08-17 08:00:25 -07002658 if (const char* const log =
2659 processHotplug(displayId, hwcDisplayId, connected, std::move(*info))) {
2660 ALOGI("%s display %s (HAL ID %" PRIu64 ")", log, to_string(displayId).c_str(),
2661 hwcDisplayId);
2662 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002663 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002664 }
2665
Dominik Laskowskif11728a2022-07-28 13:07:42 -07002666 return !events.empty();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002667}
2668
Dominik Laskowskibb66e632022-08-17 08:00:25 -07002669const char* SurfaceFlinger::processHotplug(PhysicalDisplayId displayId,
2670 hal::HWDisplayId hwcDisplayId, bool connected,
2671 DisplayIdentificationInfo&& info) {
2672 const auto tokenOpt = mPhysicalDisplayTokens.get(displayId);
2673 if (!connected) {
2674 LOG_ALWAYS_FATAL_IF(!tokenOpt);
2675
2676 if (const ssize_t index = mCurrentState.displays.indexOfKey(tokenOpt->get()); index >= 0) {
2677 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2678 mInterceptor->saveDisplayDeletion(state.sequenceId);
2679 mCurrentState.displays.removeItemsAt(index);
2680 }
2681
2682 mPhysicalDisplayTokens.erase(displayId);
2683 return "Disconnecting";
2684 }
2685
2686 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
2687 if (!activeMode) {
2688 // TODO(b/241286153): Report hotplug failure to the framework.
2689 ALOGE("Failed to hotplug display %s", to_string(displayId).c_str());
2690 getHwComposer().disconnectDisplay(displayId);
2691 return nullptr;
2692 }
2693
2694 if (tokenOpt) {
2695 auto& state = mCurrentState.displays.editValueFor(tokenOpt->get());
2696 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
2697 state.physical->supportedModes = std::move(supportedModes);
2698 state.physical->activeMode = std::move(activeMode);
2699 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2700 state.physical->deviceProductInfo = std::move(info.deviceProductInfo);
2701 }
2702 return "Reconnecting";
2703 }
2704
2705 DisplayDeviceState state;
2706 state.physical = {.id = displayId,
2707 .type = getHwComposer().getDisplayConnectionType(displayId),
2708 .hwcDisplayId = hwcDisplayId,
2709 .deviceProductInfo = std::move(info.deviceProductInfo),
2710 .supportedModes = std::move(supportedModes),
2711 .activeMode = std::move(activeMode)};
2712 state.isSecure = true; // All physical displays are currently considered secure.
2713 state.displayName = std::move(info.name);
2714
2715 sp<IBinder> token = sp<BBinder>::make();
2716 mCurrentState.displays.add(token, state);
2717 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
2718 mInterceptor->saveDisplayCreation(state);
2719 return "Connecting";
2720}
2721
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002722void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002723 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2724 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002725}
2726
Lloyd Pique99d3da52018-01-22 17:48:03 -08002727sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002728 const wp<IBinder>& displayToken,
2729 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002730 const DisplayDeviceState& state,
2731 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002732 const sp<IGraphicBufferProducer>& producer) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002733 DisplayDeviceCreationArgs creationArgs(sp<SurfaceFlinger>::fromExisting(this), getHwComposer(),
2734 displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002735 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002736 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002737 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002738 creationArgs.hasWideColorGamut = false;
2739 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002740
Dominik Laskowski55c85402020-01-21 16:25:47 -08002741 if (const auto& physical = state.physical) {
2742 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002743 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002744 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002745 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2746 getKernelIdleTimerProperties(compositionDisplay->getId());
2747
Ady Abraham3efa3942021-06-24 19:01:25 -07002748 scheduler::RefreshRateConfigs::Config config =
2749 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2750 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002751 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002752 .idleTimerTimeout = idleTimerTimeoutMs,
2753 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002754 creationArgs.refreshRateConfigs =
2755 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2756 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002757 }
2758
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002759 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002760 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002761
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002762 if (useColorManagement) {
2763 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2764 for (ColorMode colorMode : modes) {
2765 if (isWideColorMode(colorMode)) {
2766 creationArgs.hasWideColorGamut = true;
2767 }
2768
2769 std::vector<RenderIntent> renderIntents =
2770 getHwComposer().getRenderIntents(*id, colorMode);
2771 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002772 }
2773 }
tangrobin6753a022018-08-10 10:58:54 +08002774 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002775
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002776 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2777 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2778 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002779 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002780
Lloyd Pique90c115d2018-09-18 21:39:42 -07002781 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002782 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002783 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002784
Lloyd Pique99d3da52018-01-22 17:48:03 -08002785 // Make sure that composition can never be stalled by a virtual display
2786 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002787 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002788 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002789 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2790 }
2791
Dominik Laskowski718f9602019-11-09 20:01:35 -08002792 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002793 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2794 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002795
Lloyd Pique99d3da52018-01-22 17:48:03 -08002796 // virtual displays are always considered enabled
linpeter1c69cd32022-07-13 19:20:48 +08002797 creationArgs.initialPowerMode =
2798 state.isVirtual() ? std::make_optional(hal::PowerMode::ON) : std::nullopt;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002799
Lloyd Pique9370a482019-10-03 17:58:30 -07002800 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002801
Ady Abraham8565ad22021-06-22 17:45:44 -07002802 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002803
2804 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002805 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002806 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002807 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002808 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002809 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002810 display->getCompositionDisplay()->setColorProfile(
2811 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2812 RenderIntent::COLORIMETRIC,
2813 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002814 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002815 FTL_FAKE_GUARD(kMainThreadContext,
2816 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002817 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002818 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002819
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002820 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002821 display->setProjection(state.orientation, state.layerStackSpaceRect,
2822 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002823 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002824 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002825
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002826 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002827}
2828
Marin Shalamanovae685592020-02-12 17:12:22 +01002829void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2830 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002831 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002832 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2833 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002834 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002835 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2836 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002837 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002838 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002839 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002840 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002841 int format;
2842 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002843 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002844 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002845 } else {
2846 // Virtual displays without a surface are dormant:
2847 // they have external state (layer stack, projection,
2848 // etc.) but no internal state (i.e. a DisplayDevice).
2849 return;
2850 }
2851
2852 compositionengine::DisplayCreationArgsBuilder builder;
2853 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002854 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002855 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002856 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002857 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002858
Marin Shalamanov045b7002021-01-07 16:56:24 +01002859 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002860 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002861 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002862 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002863 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002864 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002865
2866 sp<compositionengine::DisplaySurface> displaySurface;
2867 sp<IGraphicBufferProducer> producer;
2868 sp<IGraphicBufferProducer> bqProducer;
2869 sp<IGraphicBufferConsumer> bqConsumer;
2870 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2871
Marin Shalamanovae685592020-02-12 17:12:22 +01002872 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002873 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2874 LOG_FATAL_IF(!displayId);
2875 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2876 bqProducer, bqConsumer, state.displayName);
2877 displaySurface = surface;
2878 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002879 } else {
2880 ALOGE_IF(state.surface != nullptr,
2881 "adding a supported display, but rendering "
2882 "surface is provided (%p), ignoring it",
2883 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002884 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2885 LOG_FATAL_IF(!displayId);
2886 displaySurface =
2887 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002888 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002889 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002890 producer = bqProducer;
2891 }
2892
Marin Shalamanov700e6392020-02-12 20:22:26 +01002893 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002894 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2895 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002896 if (display->isPrimary()) {
2897 initScheduler(display);
2898 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002899 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002900 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002901 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002902
2903 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01002904}
2905
2906void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002907 auto display = getDisplayDeviceLocked(displayToken);
2908 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002909 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002910
2911 if (display->isVirtual()) {
2912 releaseVirtualDisplay(display->getVirtualId());
2913 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002914 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01002915 }
2916 }
2917
2918 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08002919
2920 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002921 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002922 // Destroy the display without holding the mStateLock.
2923 // This is a temporary solution until we can manage transaction queues without
2924 // holding the mStateLock.
2925 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
2926 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
2927 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
2928 // ends up running on the main thread causing a deadlock since setTransactionstate
2929 // will try to acquire the mStateLock. Instead we extend the lifetime of
2930 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
2931 // The display will be disconnected and removed from the mDisplays list so it will
2932 // not be accessible.
2933 }));
2934 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002935}
2936
2937void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2938 const DisplayDeviceState& currentState,
2939 const DisplayDeviceState& drawingState) {
2940 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2941 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002942
2943 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01002944 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02002945 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002946
Marin Shalamanovae685592020-02-12 17:12:22 +01002947 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2948 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002949 if (display->isVirtual()) {
2950 releaseVirtualDisplay(display->getVirtualId());
2951 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002952 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002953
Marin Shalamanovae685592020-02-12 17:12:22 +01002954 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002955
Marin Shalamanov700e6392020-02-12 20:22:26 +01002956 if (const auto& physical = currentState.physical) {
2957 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2958 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002959
Marin Shalamanovae685592020-02-12 17:12:22 +01002960 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002961
Marin Shalamanov700e6392020-02-12 20:22:26 +01002962 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002963 const auto display = getDisplayDeviceLocked(displayToken);
2964 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01002965
2966 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002967 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07002968 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01002969 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002970 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002971 return;
2972 }
2973
2974 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2975 if (currentState.layerStack != drawingState.layerStack) {
2976 display->setLayerStack(currentState.layerStack);
2977 }
Evan Rosky2239b372021-05-20 13:43:47 -07002978 if (currentState.flags != drawingState.flags) {
2979 display->setFlags(currentState.flags);
2980 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002981 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002982 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
2983 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
2984 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
2985 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07002986 if (isDisplayActiveLocked(display)) {
2987 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08002988 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002989 }
2990 if (currentState.width != drawingState.width ||
2991 currentState.height != drawingState.height) {
2992 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07002993
Ady Abrahamed3290f2021-05-17 15:12:14 -07002994 if (isDisplayActiveLocked(display)) {
2995 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01002996 }
2997 }
2998 }
2999}
Ady Abraham3efa3942021-06-24 19:01:25 -07003000void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003001 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003002 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003003 updatePhaseConfiguration(refreshRate);
3004 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003005}
Marin Shalamanovae685592020-02-12 17:12:22 +01003006
Lloyd Pique347200f2017-12-14 17:00:15 -08003007void SurfaceFlinger::processDisplayChangesLocked() {
3008 // here we take advantage of Vector's copy-on-write semantics to
3009 // improve performance by skipping the transaction entirely when
3010 // know that the lists are identical
3011 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3012 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3013 if (!curr.isIdenticalTo(draw)) {
3014 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003015 mUpdateInputInfo = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003016
3017 // find the displays that were removed
3018 // (ie: in drawing state but not in current state)
3019 // also handle displays that changed
3020 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003021 for (size_t i = 0; i < draw.size(); i++) {
3022 const wp<IBinder>& displayToken = draw.keyAt(i);
3023 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003024 if (j < 0) {
3025 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003026 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003027 } else {
3028 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003029 const DisplayDeviceState& currentState = curr[j];
3030 const DisplayDeviceState& drawingState = draw[i];
3031 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003032 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003033 }
3034
3035 // find displays that were added
3036 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003037 for (size_t i = 0; i < curr.size(); i++) {
3038 const wp<IBinder>& displayToken = curr.keyAt(i);
3039 if (draw.indexOfKey(displayToken) < 0) {
3040 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003041 }
3042 }
3043 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003044
3045 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003046}
3047
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003048void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3049 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003050 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3051 if (displayTransactionNeeded) {
3052 processDisplayChangesLocked();
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003053 }
Robert Carrb552ff52021-06-11 13:35:54 -07003054 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055
Robert Carre450fb52021-06-11 13:21:09 -07003056 if (mSomeChildrenChanged) {
3057 mVisibleRegionsDirty = true;
3058 mSomeChildrenChanged = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003059 mUpdateInputInfo = true;
Robert Carre450fb52021-06-11 13:21:09 -07003060 }
3061
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003062 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003063 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003064 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003065 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003066 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003067 // the hint is set before we acquire a buffer from the surface texture.
3068 //
3069 // NOTE: layer transactions have taken place already, so we use their
3070 // drawing state. However, SurfaceFlinger's own transaction has not
3071 // happened yet, so we must use the current state layer list
3072 // (soon to become the drawing state list).
3073 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003074 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003075 ui::LayerStack layerStack;
3076
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003077 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003078 // NOTE: we rely on the fact that layers are sorted by
3079 // layerStack first (so we don't have to traverse the list
3080 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003081 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3082 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003083 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003084
3085 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003086 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003087 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3088 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003089 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003090
3091 // Pick the primary display if another display mirrors the layer.
3092 if (hintDisplay) {
3093 hintDisplay = nullptr;
3094 break;
3095 }
3096
3097 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003098 }
3099 }
Chet Haase91d25932013-04-11 15:24:55 -07003100
Vishnu Naire3066de2022-06-08 12:16:25 -07003101 if (!hintDisplay && mDisplays.size() > 0) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003102 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3103 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003104
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003105 // could be null when this layer is using a layerStack
3106 // that is not visible on any display. Also can occur at
3107 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003108 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003109 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003110
Vishnu Naire3066de2022-06-08 12:16:25 -07003111 if (hintDisplay) {
3112 layer->updateTransformHint(hintDisplay->getTransformHint());
3113 } else {
3114 ALOGW("Ignoring transform hint update for %s", layer->getDebugName());
3115 }
Robert Carr2047fae2016-11-28 14:09:09 -08003116 });
Mathias Agopian84300952012-11-21 16:02:13 -08003117 }
3118
Robert Carr1f0a16a2016-10-24 16:27:39 -07003119 if (mLayersAdded) {
3120 mLayersAdded = false;
3121 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003122 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003123 mUpdateInputInfo = true;
Mathias Agopian3559b072012-08-15 13:46:03 -07003124 }
3125
3126 // some layers might have been removed, so
3127 // we need to update the regions they're exposing.
3128 if (mLayersRemoved) {
3129 mLayersRemoved = false;
3130 mVisibleRegionsDirty = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00003131 mUpdateInputInfo = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003132 mDrawingState.traverseInZOrder([&](Layer* layer) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07003133 if (mLayersPendingRemoval.indexOf(sp<Layer>::fromExisting(layer)) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003134 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003135 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003136 visibleReg.set(layer->getScreenBounds());
Ady Abrahamd11bade2022-08-01 16:18:03 -07003137 invalidateLayerStack(sp<Layer>::fromExisting(layer), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003138 }
Robert Carr2047fae2016-11-28 14:09:09 -08003139 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140 }
3141
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003142 doCommitTransactions();
3143 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
Riley Andrews03414a12014-07-01 14:22:59 -07003144}
3145
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003146void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003147 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003148 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003149 return;
3150 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003151
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003152 std::vector<WindowInfo> windowInfos;
3153 std::vector<DisplayInfo> displayInfos;
3154 bool updateWindowInfo = false;
Arthur Hung9ed43392022-05-27 06:31:57 +00003155 if (mUpdateInputInfo) {
3156 mUpdateInputInfo = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003157 updateWindowInfo = true;
3158 buildWindowInfos(windowInfos, displayInfos);
Arthur Hung9ed43392022-05-27 06:31:57 +00003159 } else if (mInputWindowCommands.empty()) {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003160 return;
3161 }
Arthur Hung9ed43392022-05-27 06:31:57 +00003162
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003163 BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
3164 windowInfos = std::move(windowInfos),
3165 displayInfos = std::move(displayInfos),
3166 inputWindowCommands =
3167 std::move(mInputWindowCommands),
3168 inputFlinger = mInputFlinger, this]() {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003169 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3170 if (updateWindowInfo) {
Patrick Williams641f7f22022-06-22 19:25:35 +00003171 mWindowInfosListenerInvoker
3172 ->windowInfosChanged(windowInfos, displayInfos,
3173 inputWindowCommands.windowInfosReportedListeners);
3174 } else {
3175 // If there are listeners but no changes to input windows, call the listeners
3176 // immediately.
3177 for (const auto& listener : inputWindowCommands.windowInfosReportedListeners) {
3178 if (IInterface::asBinder(listener)->isBinderAlive()) {
3179 listener->onWindowInfosReported();
3180 }
3181 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003182 }
3183 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3184 inputFlinger->setFocusedWindow(focusRequest);
3185 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003186 }});
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003187
Arthur Hung6cbb9752019-09-05 16:38:18 +08003188 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003189}
3190
Alec Mouricdf16792021-12-10 13:16:06 -08003191void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3192 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3193 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3194 if (!supportsDisplayBrightnessCommand) {
3195 return;
3196 }
3197
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003198 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003199 if (const auto brightness = display->getStagedBrightness(); brightness) {
3200 if (!needsComposite) {
3201 const status_t error =
3202 getHwComposer()
3203 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003204 display->getCompositionDisplay()
3205 ->getState()
3206 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003207 Hwc2::Composer::DisplayBrightnessOptions{
3208 .applyImmediately = true})
3209 .get();
3210
3211 ALOGE_IF(error != NO_ERROR,
3212 "Error setting display brightness for display %s: %d (%s)",
3213 display->getDebugName().c_str(), error, strerror(error));
3214 }
3215 display->persistBrightness(needsComposite);
3216 }
3217 }
3218}
3219
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003220void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3221 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003222 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3223
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003224 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003225 const auto layerStack = display->getLayerStack();
3226 const auto info = display->getInputInfo();
3227
3228 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003229 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003230 continue;
3231 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003232
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003233 // If the layer stack is mirrored on multiple displays, the first display that is configured
3234 // to receive input takes precedence.
3235 auto& otherInfo = it->second;
3236 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003237 ALOGW_IF(display->receivesInput(),
3238 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003239 layerStack.id);
3240 } else {
3241 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003242 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003243 }
Robert Carr720e5062018-07-30 17:45:14 -07003244
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003245 static size_t sNumWindowInfos = 0;
3246 outWindowInfos.reserve(sNumWindowInfos);
3247 sNumWindowInfos = 0;
3248
Robert Carr720e5062018-07-30 17:45:14 -07003249 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003250 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003251
Dominik Laskowski54494bd2022-08-02 13:37:14 -07003252 const auto opt = displayInputInfos.get(layer->getLayerStack())
3253 .transform([](const DisplayDevice::InputInfo& info) {
3254 return Layer::InputDisplayArgs{&info.transform, info.isSecure};
3255 });
3256
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00003257 outWindowInfos.push_back(layer->fillInputInfo(opt.value_or(Layer::InputDisplayArgs{})));
Robert Carr720e5062018-07-30 17:45:14 -07003258 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003259
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003260 sNumWindowInfos = outWindowInfos.size();
3261
3262 outDisplayInfos.reserve(displayInputInfos.size());
3263 for (const auto& [_, info] : displayInputInfos) {
3264 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003265 }
Robert Carr720e5062018-07-30 17:45:14 -07003266}
3267
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003268void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003269 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003270 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003271 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003272 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003273 }
3274 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003275
3276 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003277}
3278
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003279void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003280 // If this is called from the main thread mStateLock must be locked before
3281 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003282 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003283
3284 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003285
3286 const auto display = getDefaultDisplayDeviceLocked();
3287 if (!display || mBootStage != BootStage::FINISHED) {
3288 return;
3289 }
3290 ATRACE_CALL();
3291
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003292 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3293 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003294 return;
3295 }
3296
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003297 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003298}
3299
Ady Abraham62a0be22020-12-08 16:54:10 -08003300void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3301 PhysicalDisplayId displayId = [&]() {
3302 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3303 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3304 }();
3305
3306 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3307}
3308
Ady Abraham3efa3942021-06-24 19:01:25 -07003309void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003310 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003311 // If the scheduler is already initialized, this means that we received
3312 // a hotplug(connected) on the primary display. In that case we should
3313 // update the scheduler with the most recent display information.
3314 ALOGW("Scheduler already initialized, updating instead");
3315 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003316 return;
3317 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003318 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003319 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3320 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003321
Marin Shalamanova903d032020-12-29 20:35:13 +01003322 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003323 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003324
Dominik Laskowski068173d2021-08-11 17:22:59 -07003325 using Feature = scheduler::Feature;
3326 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003327
Dominik Laskowski068173d2021-08-11 17:22:59 -07003328 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3329 features |= Feature::kContentDetection;
3330 }
3331 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3332 features |= Feature::kTracePredictedVsync;
3333 }
3334 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003335 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003336 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003337 }
3338
Dominik Laskowski068173d2021-08-11 17:22:59 -07003339 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3340 static_cast<ISchedulerCallback&>(*this),
3341 features);
3342 {
3343 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003344 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003345 features |= Feature::kKernelIdleTimer;
3346 }
3347
3348 mScheduler->createVsyncSchedule(features);
3349 mScheduler->setRefreshRateConfigs(std::move(configs));
3350 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003351 setVsyncEnabled(false);
3352 mScheduler->startTimers();
3353
Ady Abraham9c53ee72020-07-22 21:16:18 -07003354 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003355 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003356 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003357 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003358 /*workDuration=*/configs.late.appWorkDuration,
3359 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003360 impl::EventThread::InterceptVSyncsCallback());
3361 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003362 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3363 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3364 /*readyDuration=*/configs.late.sfWorkDuration,
3365 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003366 mInterceptor->saveVSyncEvent(timestamp);
3367 });
3368
Dominik Laskowski5d164f22022-07-07 07:56:07 -07003369 mScheduler->initVsync(mScheduler->getVsyncSchedule().getDispatch(),
3370 *mFrameTimeline->getTokenManager(), configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003371
3372 mRegionSamplingThread =
Ady Abrahamd11bade2022-08-01 16:18:03 -07003373 sp<RegionSamplingThread>::make(*this,
3374 RegionSamplingThread::EnvironmentTimingTunables());
3375 mFpsReporter = sp<FpsReporter>::make(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003376 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003377 // initialization, so that the EventThreads always contain a reference to a
3378 // prior configuration.
3379 //
3380 // This is a bit hacky, but this avoids a back-pointer into the main SF
3381 // classes from EventThread, and there should be no run-time binder cost
3382 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003383 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003384}
3385
Marin Shalamanov5801c942020-12-17 17:00:13 +01003386void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3387 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003388 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003389 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003390}
3391
Ady Abraham55fa7272020-09-30 19:19:27 -07003392void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3393 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003394 mScheduler->setDuration(mAppConnectionHandle,
3395 /*workDuration=*/config.appWorkDuration,
3396 /*readyDuration=*/config.sfWorkDuration);
3397 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003398 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3399 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003400 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003401}
3402
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003403void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003404 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003405
Lloyd Pique58e24a32019-08-01 15:50:14 -07003406 if (!mLayersPendingRemoval.isEmpty()) {
3407 // Notify removed layers now that they can't be drawn from
3408 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003409 // Ensure any buffers set to display on any children are released.
3410 if (l->isRemovedFromCurrentState()) {
3411 l->latchAndReleaseBuffer();
3412 }
3413
chaviw6852bff2022-04-19 17:35:11 -05003414 // If a layer has a parent, we allow it to out-live it's handle
3415 // with the idea that the parent holds a reference and will eventually
3416 // be cleaned up. However no one cleans up the top-level so we do so
3417 // here.
3418 if (l->isAtRoot()) {
3419 l->setIsAtRoot(false);
3420 mCurrentState.layersSortedByZ.remove(l);
3421 }
3422
Lloyd Pique58e24a32019-08-01 15:50:14 -07003423 // If the layer has been removed and has no parent, then it will not be reachable
3424 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3425 // ensure we can copy its current to drawing state.
3426 if (!l->getParent()) {
3427 mOffscreenLayers.emplace(l.get());
3428 }
3429 }
3430 mLayersPendingRemoval.clear();
3431 }
3432
Lloyd Pique58e24a32019-08-01 15:50:14 -07003433 mDrawingState = mCurrentState;
3434 // clear the "changed" flags in current state
3435 mCurrentState.colorMatrixChanged = false;
3436
Robert Carra70e91c2021-06-11 13:59:52 -07003437 if (mVisibleRegionsDirty) {
3438 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3439 rootLayer->commitChildList();
3440 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003441 }
Robert Carra70e91c2021-06-11 13:59:52 -07003442
Lloyd Pique58e24a32019-08-01 15:50:14 -07003443 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003444 if (mNumClones > 0) {
3445 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3446 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003447}
3448
chaviw74d90ad2019-04-26 14:45:26 -07003449void SurfaceFlinger::commitOffscreenLayers() {
3450 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003451 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003452 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3453 layer->doTransaction(0);
3454 layer->commitChildList();
3455 }
chaviw74d90ad2019-04-26 14:45:26 -07003456 });
3457 }
3458}
3459
Chia-I Wuab0c3192017-08-01 11:29:00 -07003460void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003461 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003462 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003463 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003464 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003465 }
3466 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003467}
3468
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003469bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003470 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003471
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003472 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003473
Mathias Agopian4fec8732012-06-29 14:12:52 -07003474 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003475 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003476 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003477
3478 // Store the set of layers that need updates. This set must not change as
3479 // buffers are being latched, as this could result in a deadlock.
3480 // Example: Two producers share the same command stream and:
3481 // 1.) Layer 0 is latched
3482 // 2.) Layer 0 gets a new frame
3483 // 2.) Layer 1 gets a new frame
3484 // 3.) Layer 1 is latched.
3485 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3486 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003487 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003488 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3489 const uint32_t flags = layer->doTransaction(0);
3490 if (flags & Layer::eVisibleRegion) {
3491 mVisibleRegionsDirty = true;
3492 }
3493 }
Robert Carrb552ff52021-06-11 13:35:54 -07003494
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003495 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003496 frameQueued = true;
Ady Abrahamd11bade2022-08-01 16:18:03 -07003497 mLayersWithQueuedFrames.emplace(sp<Layer>::fromExisting(layer));
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003498 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003499 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003500 }
Robert Carr2047fae2016-11-28 14:09:09 -08003501 });
Robert Carrb552ff52021-06-11 13:35:54 -07003502 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003503
chaviw49a108c2019-08-12 11:23:06 -07003504 // The client can continue submitting buffers for offscreen layers, but they will not
3505 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3506 // layers to ensure dequeueBuffer doesn't block indefinitely.
3507 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003508 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003509 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3510 }
3511
Lloyd Piquef2c79392018-12-20 16:23:33 -08003512 if (!mLayersWithQueuedFrames.empty()) {
3513 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3514 // writes to Layer current state. See also b/119481871
3515 Mutex::Autolock lock(mStateLock);
3516
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003517 for (const auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair397a0e32022-07-26 00:01:48 +00003518 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003519 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003520 newDataLatched = true;
3521 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003522 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003523 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003524 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003525
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003526 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003527
3528 // If we will need to wake up at some time in the future to deal with a
3529 // queued frame that shouldn't be displayed during this vsync period, wake
3530 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003531 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003532 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003533 }
3534
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003535 // enter boot animation on first buffer latch
3536 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3537 ALOGI("Enter boot animation");
3538 mBootStage = BootStage::BOOTANIMATION;
3539 }
3540
Robert Carr6a0382d2021-07-01 15:57:17 -07003541 if (mNumClones > 0) {
3542 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3543 }
chaviw74b03172019-08-19 11:09:03 -07003544
Dan Stoza6b9454d2014-11-07 16:00:59 -08003545 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003546 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547}
3548
Robert Carrc0df3122019-04-11 13:18:21 -07003549status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003550 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003551 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003552 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003553 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003554 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003555 static_cast<void>(mScheduler->schedule([=] {
3556 ALOGE("Dumping random sampling of on-screen layers: ");
3557 mDrawingState.traverse([&](Layer *layer) {
3558 // Aim to dump about 200 layers to avoid totally trashing
3559 // logcat. On the other hand, if there really are 4096 layers
3560 // something has gone totally wrong its probably the most
3561 // useful information in logcat.
3562 if (rand() % 20 == 13) {
3563 ALOGE("Layer: %s", layer->getName().c_str());
3564 }
3565 });
3566 for (Layer* offscreenLayer : mOffscreenLayers) {
3567 if (rand() % 20 == 13) {
3568 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3569 }
3570 }
3571 }));
arthurhungdba591c2021-02-08 17:28:49 +08003572 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003573 }
3574
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003575 {
3576 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3577 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3578 }
arthurhungdba591c2021-02-08 17:28:49 +08003579
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003580 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003581 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003582 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003583 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003584 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003585 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003586 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003587 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003588
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003589 setTransactionFlags(eTransactionNeeded);
3590 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003591}
3592
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003593uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003594 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003595}
3596
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003597uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3598 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003599}
3600
Dominik Laskowski94000c42022-03-17 12:55:14 -07003601void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003602 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003603 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003604
3605 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003606 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003607 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003608}
3609
Robert Carr79dc06a2022-02-22 15:28:59 -08003610int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003611 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003612 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003613 bool tryApplyUnsignaled) {
Vishnu Nair55e8f512022-07-20 04:10:32 +00003614 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Robert Carr79dc06a2022-02-22 15:28:59 -08003615 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003616 auto it = mPendingTransactionQueues.begin();
3617 while (it != mPendingTransactionQueues.end()) {
3618 auto& [applyToken, transactionQueue] = *it;
3619 while (!transactionQueue.empty()) {
Vishnu Nair55e8f512022-07-20 04:10:32 +00003620 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3621 // then we should have only one applyToken for processing.
3622 // so we can stop further transactions on this applyToken.
3623 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer &&
3624 !applyTokensWithUnsignaledTransactions.empty()) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003625 ATRACE_NAME("stopTransactionProcessing");
3626 break;
3627 }
3628
3629 auto& transaction = transactionQueue.front();
3630 const auto ready =
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003631 transactionIsReadyToBeApplied(transaction, transaction.frameTimelineInfo,
3632 transaction.isAutoTimestamp,
3633 TimePoint::fromNs(transaction.desiredPresentTime),
3634 transaction.originUid, transaction.states,
3635 bufferLayersReadyToPresent, transactions.size(),
3636 tryApplyUnsignaled);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003637 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3638 if (ready == TransactionReadiness::NotReady) {
3639 setTransactionFlags(eTransactionFlushNeeded);
3640 break;
3641 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003642 if (ready == TransactionReadiness::NotReadyBarrier) {
3643 transactionsPendingBarrier++;
3644 setTransactionFlags(eTransactionFlushNeeded);
3645 break;
3646 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003647 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003648 const bool frameNumberChanged = state.bufferData->flags.test(
3649 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003650 if (frameNumberChanged) {
3651 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3652 } else {
3653 // Barrier function only used for BBQ which always includes a frame number
3654 bufferLayersReadyToPresent[state.surface] =
3655 std::numeric_limits<uint64_t>::max();
3656 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003657 });
3658 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3659 if (appliedUnsignaled) {
3660 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3661 }
3662
3663 transactions.emplace_back(std::move(transaction));
3664 transactionQueue.pop();
Vishnu Nair60d902e2022-07-20 02:55:37 +00003665 mPendingTransactionCount--;
3666 ATRACE_INT("TransactionQueue", mPendingTransactionCount.load());
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003667 }
3668
3669 if (transactionQueue.empty()) {
3670 it = mPendingTransactionQueues.erase(it);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003671 } else {
3672 it = std::next(it, 1);
3673 }
3674 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003675 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003676}
3677
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003678bool SurfaceFlinger::flushTransactionQueues(VsyncId vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003679 // to prevent onHandleDestroyed from being called while the lock is held,
3680 // we must keep a copy of the transactions (specifically the composer
3681 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003682 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003683 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003684 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Valerie Haufce31b82019-04-30 16:41:14 -07003685 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003686 Mutex::Autolock _l(mStateLock);
3687 {
Vishnu Nair60d902e2022-07-20 02:55:37 +00003688 while (!mLocklessTransactionQueue.isEmpty()) {
3689 auto maybeTransaction = mLocklessTransactionQueue.pop();
3690 if (!maybeTransaction.has_value()) {
3691 break;
3692 }
3693 auto transaction = maybeTransaction.value();
Vishnu Nair55e8f512022-07-20 04:10:32 +00003694 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003695 }
Arthur Hung58144272021-01-16 03:43:53 +00003696
Robert Carr79dc06a2022-02-22 15:28:59 -08003697 // Transactions with a buffer pending on a barrier may be on a different applyToken
3698 // than the transaction which satisfies our barrier. In fact this is the exact use case
3699 // that the primitive is designed for. This means we may first process
3700 // the barrier dependent transaction, determine it ineligible to complete
3701 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3702 // The barrier dependent transaction was eligible to be presented in this frame
3703 // but we would have prevented it without case. To fix this we continually
3704 // loop through flushPendingTransactionQueues until we perform an iteration
3705 // where the number of transactionsPendingBarrier doesn't change. This way
3706 // we can continue to resolve dependency chains of barriers as far as possible.
Vishnu Nair55e8f512022-07-20 04:10:32 +00003707 int lastTransactionsPendingBarrier = 0;
3708 int transactionsPendingBarrier = 0;
3709 do {
Robert Carr79dc06a2022-02-22 15:28:59 -08003710 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3711 transactionsPendingBarrier =
Vishnu Nair55e8f512022-07-20 04:10:32 +00003712 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3713 /*tryApplyUnsignaled*/ false);
3714 } while (lastTransactionsPendingBarrier != transactionsPendingBarrier);
Robert Carr79dc06a2022-02-22 15:28:59 -08003715
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003716 // We collected all transactions that could apply without latching unsignaled buffers.
3717 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3718 // transactions that were not applied and try to apply them unsignaled.
3719 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
Vishnu Nair55e8f512022-07-20 04:10:32 +00003720 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3721 /*tryApplyUnsignaled*/ true);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003722 }
3723
Vishnu Nair7891e962021-11-11 12:07:21 -08003724 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003725 }
ramindani4d48f902021-09-20 21:07:45 +00003726 }
3727}
3728
Vishnu Nair7891e962021-11-11 12:07:21 -08003729bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003730 VsyncId vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003731 bool needsTraversal = false;
3732 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003733 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003734 needsTraversal |=
3735 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3736 transaction.displays, transaction.flags,
3737 transaction.inputWindowCommands,
3738 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3739 transaction.buffer, transaction.postTime,
3740 transaction.permissions, transaction.hasListenerCallbacks,
3741 transaction.listenerCallbacks, transaction.originPid,
3742 transaction.originUid, transaction.id);
3743 if (transaction.transactionCommittedSignal) {
3744 mTransactionCommittedSignals.emplace_back(
3745 std::move(transaction.transactionCommittedSignal));
3746 }
3747 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003748
Dominik Laskowski46471e62022-01-14 15:34:03 -08003749 if (mTransactionTracing) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003750 mTransactionTracing->addCommittedTransactions(transactions, vsyncId.value);
Vishnu Nair7891e962021-11-11 12:07:21 -08003751 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003752 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003753}
3754
3755bool SurfaceFlinger::transactionFlushNeeded() {
Vishnu Nair60d902e2022-07-20 02:55:37 +00003756 return !mPendingTransactionQueues.empty() || !mLocklessTransactionQueue.isEmpty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003757}
3758
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003759bool SurfaceFlinger::frameIsEarly(TimePoint expectedPresentTime, VsyncId vsyncId) const {
3760 const auto prediction =
3761 mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId.value);
3762 if (!prediction) {
Ady Abraham8db10102021-03-15 17:19:23 -07003763 return false;
3764 }
3765
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003766 const auto predictedPresentTime = TimePoint::fromNs(prediction->presentTime);
3767
3768 // The duration for which SF can delay a frame if it is considered early based on the
3769 // VsyncModulator::VsyncConfig::appWorkDuration.
3770 if (constexpr std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3771 std::chrono::abs(predictedPresentTime - expectedPresentTime) >= kEarlyLatchMaxThreshold) {
Ady Abraham8db10102021-03-15 17:19:23 -07003772 return false;
3773 }
3774
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003775 const Duration earlyLatchVsyncThreshold = mScheduler->getVsyncSchedule().period() / 2;
3776
3777 return predictedPresentTime >= expectedPresentTime &&
3778 predictedPresentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
Ady Abraham8db10102021-03-15 17:19:23 -07003779}
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003780
Ady Abraham9dada822022-02-03 10:26:59 -08003781bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003782 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003783 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3784 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3785 return false;
3786 }
Ady Abraham8db10102021-03-15 17:19:23 -07003787
Ady Abraham9dada822022-02-03 10:26:59 -08003788 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3789 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3790 return true;
3791 }
3792
3793 // We only want to latch unsignaled when a single layer is updated in this
3794 // transaction (i.e. not a blast sync transaction).
3795 if (numStates != 1) {
3796 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3797 return false;
3798 }
3799
Ady Abraham2739e832022-02-14 17:42:00 -08003800 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3801 if (totalTXapplied > 0) {
3802 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3803 __func__, totalTXapplied);
3804 return false;
3805 }
3806
3807 // We don't want to latch unsignaled if are in early / client composition
3808 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3809 // or window animations being slow.
3810 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3811 if (!isDefaultVsyncConfig) {
3812 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3813 __func__);
3814 return false;
3815 }
Ady Abraham9dada822022-02-03 10:26:59 -08003816 }
3817
3818 if (!layer->simpleBufferUpdate(state)) {
3819 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3820 return false;
3821 }
3822
3823 ALOGV("%s: true", __func__);
3824 return true;
3825}
3826
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003827auto SurfaceFlinger::transactionIsReadyToBeApplied(
3828 TransactionState& transaction, const FrameTimelineInfo& info, bool isAutoTimestamp,
3829 TimePoint desiredPresentTime, uid_t originUid, const Vector<ComposerState>& states,
3830 const std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>&
3831 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003832 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003833 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Marissa Wall17b4e452018-12-26 16:32:34 -08003834 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3835 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003836 if (!isAutoTimestamp && desiredPresentTime >= mExpectedPresentTime &&
3837 desiredPresentTime < mExpectedPresentTime + 1s) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003838 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003839 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003840 }
3841
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003842 if (!mScheduler->isVsyncValid(mExpectedPresentTime, originUid)) {
Ady Abraham5690bda2021-03-12 15:01:18 -08003843 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003844 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003845 }
3846
Ady Abraham8db10102021-03-15 17:19:23 -07003847 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3848 // present time of this transaction.
Dominik Laskowski08fbd852022-07-14 08:53:42 -07003849 if (isAutoTimestamp && frameIsEarly(mExpectedPresentTime, VsyncId{info.vsyncId})) {
Ady Abraham8db10102021-03-15 17:19:23 -07003850 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08003851 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07003852 }
3853
Ady Abraham9dada822022-02-03 10:26:59 -08003854 bool fenceUnsignaled = false;
Robert Carr4c1b6462021-12-21 10:30:50 -08003855 auto queueProcessTime = systemTime();
Marissa Wall713b63f2018-10-17 15:42:43 -07003856 for (const ComposerState& state : states) {
3857 const layer_state_t& s = state.state;
Robert Carr4c1b6462021-12-21 10:30:50 -08003858
Ady Abrahamf20c1922020-12-21 18:39:01 -08003859 sp<Layer> layer = nullptr;
3860 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07003861 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003862 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08003863 ALOGW("Transaction with buffer, but no Layer?");
3864 continue;
3865 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003866 if (!layer) {
3867 continue;
3868 }
Ady Abraham43752eb2021-03-04 16:24:25 -08003869
Robert Carr79dc06a2022-02-22 15:28:59 -08003870 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
3871 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
3872 const bool willApplyBarrierFrame =
3873 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
3874 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
3875 if (!willApplyBarrierFrame) {
3876 ATRACE_NAME("NotReadyBarrier");
3877 return TransactionReadiness::NotReadyBarrier;
3878 }
3879 }
3880
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003881 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08003882 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08003883 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
3884 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08003885
3886 const bool acquireFenceChanged = s.bufferData &&
3887 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
3888 s.bufferData->acquireFence;
3889 fenceUnsignaled = fenceUnsignaled ||
3890 (acquireFenceChanged &&
3891 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
3892
3893 if (fenceUnsignaled && !allowLatchUnsignaled) {
Robert Carr4c1b6462021-12-21 10:30:50 -08003894 if (!transaction.sentFenceTimeoutWarning &&
Vishnu Nair55e8f512022-07-20 04:10:32 +00003895 queueProcessTime - transaction.postTime > std::chrono::nanoseconds(4s).count()) {
Robert Carr4c1b6462021-12-21 10:30:50 -08003896 transaction.sentFenceTimeoutWarning = true;
3897 auto listener = s.bufferData->releaseBufferListener;
3898 if (listener) {
3899 listener->onTransactionQueueStalled();
3900 }
3901 }
3902
Ady Abraham9dada822022-02-03 10:26:59 -08003903 ATRACE_NAME("fence unsignaled");
3904 return TransactionReadiness::NotReady;
3905 }
3906
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003907 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08003908 // If backpressure is enabled and we already have a buffer to commit, keep the
3909 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08003910 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
3911 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08003912 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003913 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08003914 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08003915 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003916 }
3917 }
Ady Abraham9dada822022-02-03 10:26:59 -08003918 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07003919}
3920
arthurhungf1b7c7b2021-03-03 17:42:23 +08003921void SurfaceFlinger::queueTransaction(TransactionState& state) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003922 // Generate a CountDownLatch pending state if this is a synchronous transaction.
Patrick Williams641f7f22022-06-22 19:25:35 +00003923 if (state.flags & eSynchronous) {
3924 state.transactionCommittedSignal =
3925 std::make_shared<CountDownLatch>(CountDownLatch::eSyncTransaction);
arthurhungf1b7c7b2021-03-03 17:42:23 +08003926 }
3927
Vishnu Nair60d902e2022-07-20 02:55:37 +00003928 mLocklessTransactionQueue.push(state);
3929 mPendingTransactionCount++;
3930 ATRACE_INT("TransactionQueue", mPendingTransactionCount.load());
Ady Abrahame46243a2021-02-23 19:33:49 -08003931
Ady Abrahame46243a2021-02-23 19:33:49 -08003932 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07003933 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
3934 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08003935 return TransactionSchedule::Late;
3936 }(state.flags);
3937
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003938 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
3939
3940 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08003941}
3942
arthurhungf1b7c7b2021-03-03 17:42:23 +08003943void SurfaceFlinger::waitForSynchronousTransaction(
3944 const CountDownLatch& transactionCommittedSignal) {
3945 // applyTransactionState is called on the main SF thread. While a given process may wish
3946 // to wait on synchronous transactions, the main SF thread should apply the transaction and
3947 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08003948 if (!transactionCommittedSignal.wait_until(
3949 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003950 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08003951 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003952}
Ady Abrahame46243a2021-02-23 19:33:49 -08003953
Arthur Hung2274a312021-04-28 15:13:06 +00003954void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003955 for (auto it = mTransactionCommittedSignals.begin();
3956 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00003957 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003958 it = mTransactionCommittedSignals.erase(it);
3959 } else {
3960 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08003961 }
3962 }
3963}
3964
chaviw308ddba2020-08-11 16:23:51 -07003965status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10003966 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07003967 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
3968 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08003969 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00003970 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003971 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003972
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003973 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08003974 callingThreadHasUnscopedSurfaceFlingerAccess() ?
3975 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003976 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
3977 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08003978 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003979 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08003980 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003981 }
3982
Leon Scroggins9a20f722021-12-28 14:43:12 +00003983 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08003984 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00003985 }
3986
Robert Carrde6d7b42022-01-07 18:23:06 -08003987 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07003988 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
3989 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
3990 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08003991 }
3992
Vishnu Nair24e3bba2021-02-23 14:19:36 -08003993 const int64_t postTime = systemTime();
3994
3995 IPCThreadState* ipc = IPCThreadState::self();
3996 const int originPid = ipc->getCallingPid();
3997 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08003998 TransactionState state{frameTimelineInfo, states,
3999 displays, flags,
4000 applyToken, inputWindowCommands,
4001 desiredPresentTime, isAutoTimestamp,
4002 uncacheBuffer, postTime,
4003 permissions, hasListenerCallbacks,
4004 listenerCallbacks, originPid,
4005 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004006
4007 // Check for incoming buffer updates and increment the pending buffer count.
4008 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4009 mBufferCountTracker.increment(state.surface->localBinder());
4010 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004011
Dominik Laskowski46471e62022-01-14 15:34:03 -08004012 if (mTransactionTracing) {
4013 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004014 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004015 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004016
arthurhungf1b7c7b2021-03-03 17:42:23 +08004017 // Check the pending state to make sure the transaction is synchronous.
4018 if (state.transactionCommittedSignal) {
4019 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004020 }
4021
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004022 return NO_ERROR;
4023}
Marissa Wall713b63f2018-10-17 15:42:43 -07004024
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004025bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004026 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004027 const Vector<DisplayState>& displays, uint32_t flags,
4028 const InputWindowCommands& inputWindowCommands,
4029 const int64_t desiredPresentTime, bool isAutoTimestamp,
4030 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004031 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004032 bool hasListenerCallbacks,
4033 const std::vector<ListenerCallbacks>& listenerCallbacks,
4034 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004035 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004036 for (const DisplayState& display : displays) {
4037 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004038 }
4039
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004040 // start and end registration for listeners w/ no surface so they can get their callback. Note
4041 // that listeners with SurfaceControls will start registration during setClientStateLocked
4042 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004043 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004044 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004045 }
4046
Marissa Walle2ffb422018-10-12 11:33:52 -07004047 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004048 for (int i = 0; i < states.size(); i++) {
4049 ComposerState& state = states.editItemAt(i);
4050 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004051 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004052 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004053 if (const auto layer = fromHandle(state.state.surface).promote()) {
4054 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004055 mScheduler->recordLayerHistory(layer.get(),
4056 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004057 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004058 }
4059 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004060 }
4061
Marissa Walle2ffb422018-10-12 11:33:52 -07004062 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004063
Robert Carrde6d7b42022-01-07 18:23:06 -08004064 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004065 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4066 } else if (!inputWindowCommands.empty()) {
4067 ALOGE("Only privileged callers are allowed to send input commands.");
4068 }
chaviw273171b2018-12-26 11:46:30 -08004069
Marissa Wall947d34e2019-03-29 14:03:53 -07004070 if (uncacheBuffer.isValid()) {
4071 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004072 }
4073
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004074 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4075 // anyway. This can be used as a flush mechanism for previous async transactions.
4076 // Empty animation transaction can be used to simulate back-pressure, so also force a
4077 // transaction for empty animation transactions.
4078 if (transactionFlags == 0 &&
4079 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004080 transactionFlags = eTransactionNeeded;
4081 }
4082
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004083 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004084 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004085 if (mInterceptor->isEnabled()) {
4086 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004087 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004088 }
4089
Arthur Hung58144272021-01-16 03:43:53 +00004090 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4091 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4092 if (transactionFlags & eTraversalNeeded) {
4093 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004094 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004095 }
Arthur Hung58144272021-01-16 03:43:53 +00004096 if (transactionFlags) {
4097 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004098 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004099 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004100
4101 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004102}
4103
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004104uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4105 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4106 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004107
Mathias Agopiane57f2922012-08-09 16:29:12 -07004108 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004109 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4110
4111 const uint32_t what = s.what;
4112 if (what & DisplayState::eSurfaceChanged) {
4113 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4114 state.surface = s.surface;
4115 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004116 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004117 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004118 if (what & DisplayState::eLayerStackChanged) {
4119 if (state.layerStack != s.layerStack) {
4120 state.layerStack = s.layerStack;
4121 flags |= eDisplayTransactionNeeded;
4122 }
4123 }
Evan Rosky2239b372021-05-20 13:43:47 -07004124 if (what & DisplayState::eFlagsChanged) {
4125 if (state.flags != s.flags) {
4126 state.flags = s.flags;
4127 flags |= eDisplayTransactionNeeded;
4128 }
4129 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004130 if (what & DisplayState::eDisplayProjectionChanged) {
4131 if (state.orientation != s.orientation) {
4132 state.orientation = s.orientation;
4133 flags |= eDisplayTransactionNeeded;
4134 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004135 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4136 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004137 flags |= eDisplayTransactionNeeded;
4138 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004139 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4140 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004141 flags |= eDisplayTransactionNeeded;
4142 }
4143 }
4144 if (what & DisplayState::eDisplaySizeChanged) {
4145 if (state.width != s.width) {
4146 state.width = s.width;
4147 flags |= eDisplayTransactionNeeded;
4148 }
4149 if (state.height != s.height) {
4150 state.height = s.height;
4151 flags |= eDisplayTransactionNeeded;
4152 }
4153 }
4154
Mathias Agopiane57f2922012-08-09 16:29:12 -07004155 return flags;
4156}
4157
Steven Thomasd4071902020-03-24 16:02:53 -07004158bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004159 IPCThreadState* ipc = IPCThreadState::self();
4160 const int pid = ipc->getCallingPid();
4161 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004162 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004163 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4164 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004165 return false;
4166 }
4167 return true;
4168}
4169
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004170uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004171 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004172 int64_t desiredPresentTime, bool isAutoTimestamp,
4173 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004174 layer_state_t& s = composerState.state;
4175 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004176
4177 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004178 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004179 // Starts a registration but separates the callback ids according to callback type. This
4180 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004181 // note that startRegistration will not re-register if the listener has
4182 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004183
4184 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4185 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004186 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004187 }
4188
4189 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4190 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004191 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004192 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004193 }
4194
arthurhungdba591c2021-02-08 17:28:49 +08004195 const uint64_t what = s.what;
4196 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004197 sp<Layer> layer = nullptr;
4198 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004199 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004200 } else {
4201 // The client may provide us a null handle. Treat it as if the layer was removed.
4202 ALOGW("Attempt to set client state with a null layer handle");
4203 }
chaviw8b3871a2017-11-01 17:41:01 -07004204 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004205 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004206 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Ady Abrahamd11bade2022-08-01 16:18:03 -07004207 sp<CallbackHandle>::make(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004208 }
chaviw8b3871a2017-11-01 17:41:01 -07004209 return 0;
4210 }
4211
Valerie Hau871d6352020-01-29 08:44:02 -08004212 // Only set by BLAST adapter layers
4213 if (what & layer_state_t::eProducerDisconnect) {
4214 layer->onDisconnect();
4215 }
4216
chaviw8b3871a2017-11-01 17:41:01 -07004217 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004218 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004219 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004220 }
chaviw8b3871a2017-11-01 17:41:01 -07004221 }
4222 if (what & layer_state_t::eLayerChanged) {
4223 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004224 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004225 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004226 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004227 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004228 mCurrentState.layersSortedByZ.removeAt(idx);
4229 mCurrentState.layersSortedByZ.add(layer);
4230 // we need traversal (state changed)
4231 // AND transaction (list changed)
4232 flags |= eTransactionNeeded|eTraversalNeeded;
4233 }
chaviw8b3871a2017-11-01 17:41:01 -07004234 } else {
4235 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004236 flags |= eTransactionNeeded|eTraversalNeeded;
4237 }
4238 }
chaviw8b3871a2017-11-01 17:41:01 -07004239 }
4240 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004241 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004242 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004243 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4244 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004245 if (p == nullptr) {
4246 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004247 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004248 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004249 mCurrentState.layersSortedByZ.removeAt(idx);
4250 mCurrentState.layersSortedByZ.add(layer);
4251 // we need traversal (state changed)
4252 // AND transaction (list changed)
4253 flags |= eTransactionNeeded|eTraversalNeeded;
4254 }
4255 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004256 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004257 flags |= eTransactionNeeded|eTraversalNeeded;
4258 }
chaviw8b3871a2017-11-01 17:41:01 -07004259 }
4260 }
chaviw8b3871a2017-11-01 17:41:01 -07004261 if (what & layer_state_t::eAlphaChanged) {
4262 if (layer->setAlpha(s.alpha))
4263 flags |= eTraversalNeeded;
4264 }
4265 if (what & layer_state_t::eColorChanged) {
4266 if (layer->setColor(s.color))
4267 flags |= eTraversalNeeded;
4268 }
Peiyong Lind3788632018-09-18 16:01:31 -07004269 if (what & layer_state_t::eColorTransformChanged) {
4270 if (layer->setColorTransform(s.colorTransform)) {
4271 flags |= eTraversalNeeded;
4272 }
4273 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004274 if (what & layer_state_t::eBackgroundColorChanged) {
4275 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4276 flags |= eTraversalNeeded;
4277 }
4278 }
chaviw8b3871a2017-11-01 17:41:01 -07004279 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004280 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004281 }
4282 if (what & layer_state_t::eTransparentRegionChanged) {
4283 if (layer->setTransparentRegionHint(s.transparentRegion))
4284 flags |= eTraversalNeeded;
4285 }
4286 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004287 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004288 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004289 if (what & layer_state_t::eCornerRadiusChanged) {
4290 if (layer->setCornerRadius(s.cornerRadius))
4291 flags |= eTraversalNeeded;
4292 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004293 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004294 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4295 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004296 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004297 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4298 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004299 if (what & layer_state_t::eRenderBorderChanged) {
Tianhao Yao10cea3c2022-03-30 01:37:22 +00004300 if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00004301 flags |= eTraversalNeeded;
4302 }
4303 }
chaviw8b3871a2017-11-01 17:41:01 -07004304 if (what & layer_state_t::eLayerStackChanged) {
4305 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4306 // We only allow setting layer stacks for top level layers,
4307 // everything else inherits layer stack from its parent.
4308 if (layer->hasParent()) {
4309 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004310 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004311 } else if (idx < 0) {
4312 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004313 "that also does not appear in the top level layer list. Something"
4314 " has gone wrong.",
4315 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004316 } else if (layer->setLayerStack(s.layerStack)) {
4317 mCurrentState.layersSortedByZ.removeAt(idx);
4318 mCurrentState.layersSortedByZ.add(layer);
4319 // we need traversal (state changed)
4320 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004321 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004322 }
4323 }
Marissa Wall61c58622018-07-18 10:12:20 -07004324 if (what & layer_state_t::eTransformChanged) {
4325 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4326 }
4327 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4328 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4329 flags |= eTraversalNeeded;
4330 }
4331 if (what & layer_state_t::eCropChanged) {
4332 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4333 }
Marissa Wall61c58622018-07-18 10:12:20 -07004334 if (what & layer_state_t::eDataspaceChanged) {
4335 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4336 }
4337 if (what & layer_state_t::eHdrMetadataChanged) {
4338 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4339 }
4340 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4341 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4342 }
4343 if (what & layer_state_t::eApiChanged) {
4344 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4345 }
4346 if (what & layer_state_t::eSidebandStreamChanged) {
4347 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4348 }
Robert Carr720e5062018-07-30 17:45:14 -07004349 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004350 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4351 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004352 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004353 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004354 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004355 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004356
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004357 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4358 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004359 // The transaction will be received on the Task layer and needs to be applied to all
4360 // child layers. Child layers that are added at a later point will obtain the game mode
4361 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004362 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004363 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004364
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004365 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4366 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004367 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4368 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4369 flags |= eTraversalNeeded;
4370 }
4371 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004372 if (what & layer_state_t::eShadowRadiusChanged) {
4373 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4374 }
Andy Labrada096227e2022-06-15 16:58:11 +00004375 if (what & layer_state_t::eDefaultFrameRateCompatibilityChanged) {
4376 const auto compatibility =
4377 Layer::FrameRate::convertCompatibility(s.defaultFrameRateCompatibility);
4378
4379 if (layer->setDefaultFrameRateCompatibility(compatibility)) {
4380 flags |= eTraversalNeeded;
4381 }
4382 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004383 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004384 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004385 flags |= eTraversalNeeded;
4386 }
4387 }
Steven Thomas3172e202020-01-06 19:25:30 -08004388 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004389 const auto compatibility =
4390 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4391 const auto strategy =
4392 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004393
Robert Carrde6d7b42022-01-07 18:23:06 -08004394 if (layer->setFrameRate(
4395 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4396 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004397 }
Steven Thomas3172e202020-01-06 19:25:30 -08004398 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004399 if (what & layer_state_t::eFixedTransformHintChanged) {
4400 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4401 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4402 }
4403 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004404 if (what & layer_state_t::eAutoRefreshChanged) {
4405 layer->setAutoRefresh(s.autoRefresh);
4406 }
Sally Qi421ffb02022-03-21 19:41:33 -07004407 if (what & layer_state_t::eDimmingEnabledChanged) {
4408 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4409 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004410 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004411 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4412 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004413 }
4414 }
John Reckcdb4ed72021-02-04 13:39:33 -05004415 if (what & layer_state_t::eStretchChanged) {
4416 if (layer->setStretchEffect(s.stretchEffect)) {
4417 flags |= eTraversalNeeded;
4418 }
4419 }
chaviwf3f40fe2021-04-27 15:54:02 -05004420 if (what & layer_state_t::eBufferCropChanged) {
4421 if (layer->setBufferCrop(s.bufferCrop)) {
4422 flags |= eTraversalNeeded;
4423 }
4424 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004425 if (what & layer_state_t::eDestinationFrameChanged) {
4426 if (layer->setDestinationFrame(s.destinationFrame)) {
4427 flags |= eTraversalNeeded;
4428 }
4429 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004430 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004431 if (layer->setDropInputMode(s.dropInputMode)) {
4432 flags |= eTraversalNeeded;
Arthur Hung9ed43392022-05-27 06:31:57 +00004433 mUpdateInputInfo = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004434 }
4435 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004436 // This has to happen after we reparent children because when we reparent to null we remove
4437 // child layers from current state and remove its relative z. If the children are reparented in
4438 // the same transaction, then we have to make sure we reparent the children first so we do not
4439 // lose its relative z order.
4440 if (what & layer_state_t::eReparent) {
4441 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004442 auto parentHandle = (s.parentSurfaceControlForChild)
4443 ? s.parentSurfaceControlForChild->getHandle()
4444 : nullptr;
4445 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004446 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004447 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004448 mCurrentState.layersSortedByZ.remove(layer);
4449 }
4450 flags |= eTransactionNeeded | eTraversalNeeded;
4451 }
4452 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004453 std::vector<sp<CallbackHandle>> callbackHandles;
4454 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4455 for (auto& [listener, callbackIds] : filteredListeners) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07004456 callbackHandles.emplace_back(
4457 sp<CallbackHandle>::make(listener, callbackIds, s.surface));
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004458 }
4459 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004460
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004461 if (what & layer_state_t::eBufferChanged) {
4462 std::shared_ptr<renderengine::ExternalTexture> buffer =
4463 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4464 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4465 dequeueBufferTimestamp, frameTimelineInfo)) {
4466 flags |= eTraversalNeeded;
4467 }
Ady Abraham8db10102021-03-15 17:19:23 -07004468 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4469 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004470 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004471
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004472 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004473 // Do not put anything that updates layer state or modifies flags after
4474 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004475 return flags;
4476}
4477
chaviw273171b2018-12-26 11:46:30 -08004478uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004479 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004480 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004481}
4482
Vishnu Nair84125ac2021-12-02 08:47:48 -08004483status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4484 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4485 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004486 if (!mirrorFromHandle) {
4487 return NAME_NOT_FOUND;
4488 }
4489
4490 sp<Layer> mirrorLayer;
4491 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004492 {
4493 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004494 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004495 if (!mirrorFrom) {
4496 return NAME_NOT_FOUND;
4497 }
Vishnu Nairb21272e2022-07-01 22:47:33 +00004498 LayerCreationArgs mirrorArgs = args;
4499 mirrorArgs.flags |= ISurfaceComposerClient::eNoColorFill;
4500 status_t result = createEffectLayer(mirrorArgs, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004501 if (result != NO_ERROR) {
4502 return result;
4503 }
4504
Robert Carr6a0382d2021-07-01 15:57:17 -07004505 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004506 }
4507
Ady Abraham9f0a4002020-10-05 15:47:26 -07004508 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004509 if (mTransactionTracing) {
4510 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4511 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004512 }
4513 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004514 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004515}
4516
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00004517status_t SurfaceFlinger::mirrorDisplay(DisplayId displayId, const LayerCreationArgs& args,
4518 sp<IBinder>* outHandle, int32_t* outLayerId) {
4519 IPCThreadState* ipc = IPCThreadState::self();
4520 const int uid = ipc->getCallingUid();
4521 if (uid != AID_ROOT && uid != AID_GRAPHICS && uid != AID_SYSTEM && uid != AID_SHELL) {
4522 ALOGE("Permission denied when trying to mirror display");
4523 return PERMISSION_DENIED;
4524 }
4525
4526 ui::LayerStack layerStack;
4527 sp<Layer> rootMirrorLayer;
4528 status_t result = 0;
4529
4530 {
4531 Mutex::Autolock lock(mStateLock);
4532
4533 const auto display = getDisplayDeviceLocked(displayId);
4534 if (!display) {
4535 return NAME_NOT_FOUND;
4536 }
4537
4538 layerStack = display->getLayerStack();
4539 LayerCreationArgs mirrorArgs = args;
4540 mirrorArgs.flags |= ISurfaceComposerClient::eNoColorFill;
4541 result = createEffectLayer(mirrorArgs, outHandle, &rootMirrorLayer);
4542 *outLayerId = rootMirrorLayer->sequence;
4543 result |= addClientLayer(args.client, *outHandle, rootMirrorLayer /* layer */,
4544 nullptr /* parent */, true /* addToRoot */,
4545 nullptr /* outTransformHint */);
4546 }
4547
4548 if (result != NO_ERROR) {
4549 return result;
4550 }
4551
4552 if (mTransactionTracing) {
4553 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), *outLayerId, args.name,
4554 args.flags, -1 /* parentId */);
4555 }
4556
4557 {
4558 std::scoped_lock<std::mutex> lock(mMirrorDisplayLock);
4559 mMirrorDisplays.emplace_back(layerStack, *outHandle, args.client);
4560 }
4561
4562 setTransactionFlags(eTransactionFlushNeeded);
4563 return NO_ERROR;
4564}
4565
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004566status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004567 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4568 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004569 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4570 "Expected only one of parentLayer or parentHandle to be non-null. "
4571 "Programmer error?");
4572
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004573 status_t result = NO_ERROR;
4574
4575 sp<Layer> layer;
4576
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004577 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004578 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004579 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004580 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004581 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4582 if (pendingBufferCounter) {
4583 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004584 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004585 pendingBufferCounter);
4586 }
4587 } break;
Vishnu Nair29810f72022-07-01 16:38:41 +00004588 case ISurfaceComposerClient::eFXSurfaceContainer:
4589 args.flags |= ISurfaceComposerClient::eNoColorFill;
4590 FMT_FALLTHROUGH;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004591 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004592 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004593 break;
4594 default:
4595 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004596 break;
4597 }
4598
Dan Stoza7d89d062015-04-30 13:29:25 -07004599 if (result != NO_ERROR) {
4600 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004601 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004602
Vishnu Nair858a3b42022-01-12 20:42:28 -08004603 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004604 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4605 if (parentHandle != nullptr && parent == nullptr) {
4606 ALOGE("Invalid parent handle %p.", parentHandle.get());
4607 addToRoot = false;
4608 }
4609 if (parentLayer != nullptr) {
4610 addToRoot = false;
4611 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004612
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004613 int parentId = -1;
4614 // We can safely promote the layer in binder thread because we have a strong reference
4615 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4616 sp<Layer> parentSp = parent.promote();
4617 if (parentSp != nullptr) {
4618 parentId = parentSp->getSequence();
4619 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004620 if (mTransactionTracing) {
4621 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4622 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004623 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004624
Vishnu Nair047fb332021-12-09 09:54:36 -08004625 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4626 if (result != NO_ERROR) {
4627 return result;
4628 }
4629
Ady Abraham9f0a4002020-10-05 15:47:26 -07004630 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004631 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004632}
4633
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004634status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004635 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004636 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004637 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004638 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004639 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004640}
4641
Vishnu Nair84125ac2021-12-02 08:47:48 -08004642status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004643 sp<Layer>* outLayer) {
4644 *outLayer = getFactory().createEffectLayer(args);
4645 *handle = (*outLayer)->getHandle();
4646 return NO_ERROR;
4647}
4648
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004649void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004650 mLayersPendingRemoval.add(layer);
4651 mLayersRemoved = true;
4652 setTransactionFlags(eTransactionNeeded);
4653}
4654
Vishnu Nairf9096652021-07-20 18:49:42 -07004655void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004656 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004657 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004658 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004659 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004660 if (mTransactionTracing) {
4661 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004662 }
Rob Carr4bba3702018-10-08 21:53:30 +00004663}
4664
Mathias Agopianb60314a2012-04-10 22:09:54 -07004665// ---------------------------------------------------------------------------
4666
Andy McFadden13a082e2012-08-24 10:16:42 -07004667void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004668 const auto display = getDefaultDisplayDeviceLocked();
4669 if (!display) return;
4670
4671 const sp<IBinder> token = display->getDisplayToken().promote();
4672 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004673
Jesse Hall01e29052013-02-19 16:13:35 -08004674 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004675 Vector<ComposerState> state;
4676 Vector<DisplayState> displays;
4677 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004678 d.what = DisplayState::eDisplayProjectionChanged |
4679 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004680 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004681 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004682 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004683 d.orientedDisplaySpaceRect.makeInvalid();
4684 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004685 d.width = 0;
4686 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004687 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004688
Vishnu Nair9a69a042021-06-18 13:19:49 -07004689 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004690
4691 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004692 // It should be on the main thread, apply it directly.
4693 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004694 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004695 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004696
Peiyong Lin65248e02020-04-18 21:15:07 -07004697 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski66296b22022-07-12 08:20:36 -07004698
Ady Abraham1273ac12021-08-26 17:31:53 -07004699 mActiveDisplayTransformHint = display->getTransformHint();
Andy McFadden13a082e2012-08-24 10:16:42 -07004700}
4701
4702void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004703 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004704 static_cast<void>(
4705 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004706}
4707
Peiyong Lin65248e02020-04-18 21:15:07 -07004708void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004709 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004710 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004711 return;
4712 }
4713
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004714 const auto displayId = display->getPhysicalId();
4715 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004716
linpeter1c69cd32022-07-13 19:20:48 +08004717 std::optional<hal::PowerMode> currentMode = display->getPowerMode();
4718 if (currentMode.has_value() && mode == *currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004719 return;
4720 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004721
Ady Abraham4f960d12021-10-13 16:59:49 -07004722 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4723 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4724 activeDisplay->isPoweredOn()) {
4725 ALOGW("Trying to change power mode on non active display while the active display is ON");
4726 }
4727
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004728 display->setPowerMode(mode);
4729
Lloyd Pique4dccc412018-01-22 17:21:36 -08004730 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004731 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004732 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004733 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
linpeter1c69cd32022-07-13 19:20:48 +08004734 if (*currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004735 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004736 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004737 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004738 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004739 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4740 // We can merge the syscall later.
4741 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4742 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4743 }
Martin Liu4a322352020-03-24 21:30:38 +08004744 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4745 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4746 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004747 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004748 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004749 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004750 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004751 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004752 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004753
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004754 mVisibleRegionsDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004755 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004756 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004757 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004758 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4759 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004760 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004761 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4762 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4763 }
linpeter1c69cd32022-07-13 19:20:48 +08004764 if (isDisplayActiveLocked(display) && *currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004765 mScheduler->disableHardwareVsync(true);
4766 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004767 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004768
Ady Abraham27c70212019-06-11 10:52:26 -07004769 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004770 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004771
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004772 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004773 mVisibleRegionsDirty = true;
4774 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004775 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004776 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004777 getHwComposer().setPowerMode(displayId, mode);
linpeter1c69cd32022-07-13 19:20:48 +08004778 if (isDisplayActiveLocked(display) && *currentMode == hal::PowerMode::DOZE_SUSPEND) {
Yifei Zhangf0bd62e2021-06-16 15:27:05 -07004779 ALOGI("Force repainting for DOZE_SUSPEND -> DOZE or ON.");
4780 mVisibleRegionsDirty = true;
4781 scheduleRepaint();
Ana Krulecc2870422019-01-29 19:00:58 -08004782 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004783 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004784 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004785 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004786 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004787 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004788 mScheduler->disableHardwareVsync(true);
4789 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004790 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004791 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004792 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004793 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004794 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004795 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004796
Ady Abrahamadc914c2021-10-13 17:04:27 -07004797 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004798 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004799 mRefreshRateStats->setPowerMode(mode);
Rachel Lee6a9731d2022-06-06 17:08:14 -07004800 mScheduler->setDisplayPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004801 }
4802
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004803 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004804}
4805
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004806void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004807 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004808 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004809 if (!display) {
4810 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4811 displayToken.get());
4812 } else if (display->isVirtual()) {
4813 ALOGW("Attempt to set power mode %d for virtual display", mode);
4814 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004815 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004816 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004817 });
4818
4819 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004820}
4821
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004822status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004823 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004824
Mathias Agopianbd115332013-04-18 16:41:04 -07004825 IPCThreadState* ipc = IPCThreadState::self();
4826 const int pid = ipc->getCallingPid();
4827 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004828
Mathias Agopianbd115332013-04-18 16:41:04 -07004829 if ((uid != AID_SHELL) &&
4830 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004831 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4832 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004833 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004834 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004835 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004836 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004837 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004838 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004839 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004840 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4841 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4842 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004843 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004844 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004845 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004846 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004847 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Ady Abraham5ad28d62022-08-11 11:26:57 -07004848 {"--hwclayers"s, dumper(&SurfaceFlinger::dumpHwcLayersMinidumpLocked)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004849 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004850
Dominik Laskowskic2867142019-01-21 11:33:38 -08004851 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004852
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004853 bool dumpLayers = true;
4854 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004855 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004856 if (!lock.locked()) {
4857 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4858 strerror(-lock.status), lock.status);
4859 }
4860
4861 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4862 (it->second)(args, asProto, result);
4863 dumpLayers = false;
4864 } else if (!asProto) {
4865 dumpAllLocked(args, result);
4866 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004867 }
4868
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004869 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004870 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05004871 LayersTraceProto* layersTrace = traceFileProto.add_entry();
4872 LayersProto layersProto = dumpProtoFromMainThread();
4873 layersTrace->mutable_layers()->Swap(&layersProto);
4874 dumpDisplayProto(*layersTrace);
4875
Dominik Laskowski46470112019-08-02 13:13:11 -07004876 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05004877 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07004878 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004879 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05004880 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07004881 result.append(LayerProtoParser::layerTreeToString(layerTree));
4882 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004883 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004884 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004885 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004886 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004887 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004888 return NO_ERROR;
4889}
4890
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004891status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08004892 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004893 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004894 if (mTransactionTracing) {
4895 mTransactionTracing->writeToFile();
4896 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004897 }
4898
4899 return doDump(fd, DumpArgs(), asProto);
4900}
4901
Dominik Laskowskic2867142019-01-21 11:33:38 -08004902void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004903 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004904 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004905}
4906
Dominik Laskowskic2867142019-01-21 11:33:38 -08004907void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07004908 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Dominik Laskowski66296b22022-07-12 08:20:36 -07004909 if (args.size() < 2) return;
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004910
Dominik Laskowski66296b22022-07-12 08:20:36 -07004911 const auto name = String8(args[1]);
4912 mCurrentState.traverseInZOrder([&](Layer* layer) {
4913 if (layer->getName() == name.string()) {
4914 layer->dumpFrameStats(result);
4915 }
4916 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004917}
4918
Dominik Laskowskic2867142019-01-21 11:33:38 -08004919void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004920 const bool clearAll = args.size() < 2;
4921 const auto name = clearAll ? String8() : String8(args[1]);
4922
Edgar Arriaga844fa672020-01-16 14:21:42 -08004923 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004924 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004925 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004926 }
Robert Carr2047fae2016-11-28 14:09:09 -08004927 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004928}
4929
Dominik Laskowskic2867142019-01-21 11:33:38 -08004930void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4931 mTimeStats->parseArgs(asProto, args, result);
4932}
4933
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004934void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
4935 mFrameTimeline->parseArgs(args, result);
4936}
4937
Dominik Laskowski8792c112022-07-12 09:03:39 -07004938void SurfaceFlinger::logFrameStats(TimePoint now) {
Dominik Laskowski8792c112022-07-12 09:03:39 -07004939 static TimePoint sTimestamp = now;
4940 if (now - sTimestamp < 30min) return;
4941 sTimestamp = now;
4942
4943 ATRACE_CALL();
Dominik Laskowski66296b22022-07-12 08:20:36 -07004944 mDrawingState.traverse([&](Layer* layer) { layer->logFrameStats(); });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004945}
4946
Yiwei Zhang5434a782018-12-05 18:06:32 -08004947void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004948 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004949
Yiwei Zhang5434a782018-12-05 18:06:32 -08004950 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4951 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08004952 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
4953 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004954 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4955 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4956 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004957 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004958}
4959
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004960void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004961 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004962
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004963 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004964 result.append("\n");
4965
Ady Abraham8287e852020-08-12 14:44:58 -07004966 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004967 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004968 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07004969 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004970
Marin Shalamanova7fe3042021-01-29 21:02:08 +01004971 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
4972 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004973
Ana Krulecc2870422019-01-29 19:00:58 -08004974 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07004975 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07004976 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
4977 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004978}
4979
Dan Stoza269dc4d2021-01-15 15:07:43 -08004980void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
4981 for (const auto& [token, display] : mDisplays) {
4982 const auto compositionDisplay = display->getCompositionDisplay();
4983 compositionDisplay->dumpPlannerInfo(args, result);
4984 }
4985}
4986
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004987void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
4988 for (const auto& [token, display] : mDisplays) {
4989 display->getCompositionDisplay()->dump(result);
4990 result += '\n';
4991 }
4992}
4993
4994void SurfaceFlinger::dumpDisplays(std::string& result) const {
4995 for (const auto& [token, display] : mDisplays) {
4996 display->dump(result);
4997 result += '\n';
4998 }
4999}
5000
Yiwei Zhang5434a782018-12-05 18:06:32 -08005001void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005002 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005003 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005004 if (!displayId) {
5005 continue;
5006 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005007 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005008 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005009 continue;
5010 }
5011
Yiwei Zhang5434a782018-12-05 18:06:32 -08005012 StringAppendF(&result,
5013 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5014 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005015 uint8_t port;
5016 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005017 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005018 result.append("no identification data\n");
5019 continue;
5020 }
5021
5022 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005023 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005024 continue;
5025 }
5026
5027 const auto edid = parseEdid(data);
5028 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005029 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005030 continue;
5031 }
5032
Yiwei Zhang5434a782018-12-05 18:06:32 -08005033 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005034 result.append(edid->displayName.data(), edid->displayName.length());
5035 result.append("\"\n");
5036 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005037}
5038
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005039void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5040 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005041 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005042 uint8_t port;
5043 DisplayIdentificationData data;
5044
5045 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5046 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5047 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5048 }
5049}
5050
Yiwei Zhang5434a782018-12-05 18:06:32 -08005051void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005052 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005053 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5054 StringAppendF(&result, "DisplayColorSetting: %s\n",
5055 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005056
5057 // TODO: print out if wide-color mode is active or not
5058
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005059 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005060 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005061 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005062 continue;
5063 }
5064
Yiwei Zhang5434a782018-12-05 18:06:32 -08005065 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005066 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005067 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005068 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005069 }
5070
Lloyd Pique32cbe282018-10-19 13:09:22 -07005071 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005072 StringAppendF(&result, " Current color mode: %s (%d)\n",
5073 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005074 }
5075 result.append("\n");
5076}
5077
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005078LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005079 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005080 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005081 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005082 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005083
chaviw1d044282017-09-27 12:19:28 -07005084 return layersProto;
5085}
5086
chaviw0a398992021-08-13 10:13:01 -05005087void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005088 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005089 DisplayProto* displayProto = layersTraceProto.add_displays();
5090 displayProto->set_id(display->getId().value);
5091 displayProto->set_name(display->getDisplayName());
5092 displayProto->set_layer_stack(display->getLayerStack().id);
5093 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5094 [&]() { return displayProto->mutable_size(); });
5095 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5096 return displayProto->mutable_layer_stack_space_rect();
5097 });
5098 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5099 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005100 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005101 }
5102}
5103
Alec Mouri6b9e9912020-01-21 10:50:24 -08005104void SurfaceFlinger::dumpHwc(std::string& result) const {
5105 getHwComposer().dump(result);
5106}
5107
Vishnu Nair0f085c62019-08-30 08:49:12 -07005108void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5109 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5110 // it.
5111 LayerProto* rootProto = layersProto.add_layers();
5112 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5113 rootProto->set_id(offscreenRootLayerId);
5114 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005115 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005116
5117 for (Layer* offscreenLayer : mOffscreenLayers) {
5118 // Add layer as child of the fake root
5119 rootProto->add_children(offscreenLayer->sequence);
5120
5121 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005122 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005123 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005124 }
5125}
5126
Vishnu Nair8406fd72019-07-30 11:29:31 -07005127LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005128 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005129}
5130
Vishnu Nair0f085c62019-08-30 08:49:12 -07005131void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005132 auto future = mScheduler->schedule([this] {
5133 std::string result;
5134 for (Layer* offscreenLayer : mOffscreenLayers) {
5135 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5136 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5137 }
5138 return result;
5139 });
5140
Vishnu Nair0f085c62019-08-30 08:49:12 -07005141 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005142 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005143}
5144
Ady Abraham5ad28d62022-08-11 11:26:57 -07005145void SurfaceFlinger::dumpHwcLayersMinidumpLocked(std::string& result) const {
5146 for (const auto& [token, display] : mDisplays) {
5147 const auto displayId = HalDisplayId::tryCast(display->getId());
5148 if (!displayId) {
5149 continue;
5150 }
5151
5152 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5153 (isDisplayActiveLocked(display) ? "active" : "inactive"));
5154 Layer::miniDumpHeader(result);
5155
5156 const DisplayDevice& ref = *display;
5157 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
5158 result.append("\n");
5159 }
5160}
5161
Dominik Laskowskic2867142019-01-21 11:33:38 -08005162void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5163 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005164 Colorizer colorizer(colorize);
5165
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005166 // figure out if we're stuck somewhere
5167 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005168 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005169 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5170
5171 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005172 * Dump library configuration.
5173 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005174
5175 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005176 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005177 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005178 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005179 result.append("\n");
5180
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005181 result.append("\nDisplay identification data:\n");
5182 dumpDisplayIdentificationData(result);
5183
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005184 result.append("\nWide-Color information:\n");
5185 dumpWideColorInfo(result);
5186
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005187 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005188 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005189 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005190 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005191 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005192
Andy McFadden41d67d72014-04-25 16:58:34 -07005193 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005194 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005195 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005196 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005197 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005198
Alec Mouri40189b02019-03-05 15:07:54 -08005199 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5200 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5201 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005202
Andy McFadden4803b742012-09-24 19:07:20 -07005203 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005204 * Dump the visible layer list
5205 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005206 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005207 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005208 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005209
Chia-I Wu2f884132018-09-13 15:17:58 -07005210 {
Lloyd Pique207def92019-02-28 16:09:52 -08005211 StringAppendF(&result, "Composition layers\n");
5212 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005213 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005214 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005215
5216 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5217 layer->getDebugName() ? layer->getDebugName()
5218 : "<unknown>");
5219 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005220 });
5221 }
5222
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005223 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005224 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005225 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005226 dumpDisplays(result);
5227 dumpCompositionDisplays(result);
5228 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005229
5230 mCompositionEngine->dump(result);
5231
5232 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005233 * Dump SurfaceFlinger global state
5234 */
5235
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005236 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005237 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005238 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005239
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005240 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005241
Robert Carrbeba6f02021-02-10 21:06:27 -08005242 result.append("ClientCache state:\n");
5243 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005244 DebugEGLImageTracker::getInstance()->dump(result);
5245
Dominik Laskowski075d3172018-05-24 15:50:06 -07005246 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005247 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5248 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005249 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5250 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005251 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005252 StringAppendF(&result,
5253 " transaction-flags : %08x\n"
5254 " gpu_to_cpu_unsupported : %d\n",
5255 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005256
Marin Shalamanov045b7002021-01-07 16:56:24 +01005257 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005258 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005259 if (const auto activeMode = display->getActiveMode()) {
5260 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005261
5262 const auto dpi = activeMode->getDpi();
5263 xDpi = base::StringPrintf("%.2f", dpi.x);
5264 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005265 } else {
5266 fps = "unknown";
5267 xDpi = "unknown";
5268 yDpi = "unknown";
5269 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005270 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005271 " refresh-rate : %s\n"
5272 " x-dpi : %s\n"
5273 " y-dpi : %s\n",
5274 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005275 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005276
Yiwei Zhang5434a782018-12-05 18:06:32 -08005277 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005278
Dan Stozae22aec72016-08-01 13:20:59 -07005279 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005280 * Tracing state
5281 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005282 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005283
5284 result.append("\nTransaction tracing: ");
5285 if (mTransactionTracing) {
5286 result.append("enabled\n");
5287 mTransactionTracing->dump(result);
5288 } else {
5289 result.append("disabled\n");
5290 }
5291 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005292
Ady Abraham5ad28d62022-08-11 11:26:57 -07005293 dumpHwcLayersMinidumpLocked(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005294
Ady Abraham2790e9f2021-04-28 13:14:20 -07005295 {
5296 DumpArgs plannerArgs;
5297 plannerArgs.add(); // first argument is ignored
5298 plannerArgs.add(String16("--layers"));
5299 dumpPlannerInfo(plannerArgs, result);
5300 }
5301
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005302 /*
5303 * Dump HWComposer state
5304 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005305 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005306 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005307 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005308 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005309 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005310 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005311
5312 /*
5313 * Dump gralloc state
5314 */
5315 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5316 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005317
rnleea2ecd832021-07-29 13:58:30 -07005318 /*
5319 * Dump flag/property manager state
5320 */
Robert Carr9b623c32022-03-21 15:55:22 -07005321 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005322
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005323 result.append(mTimeStats->miniDump());
5324 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005325}
5326
chaviw17ac24b2021-01-28 18:50:05 -08005327mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5328 if (saturation == 1) {
5329 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005330 }
5331
chaviw17ac24b2021-01-28 18:50:05 -08005332 float3 luminance{0.213f, 0.715f, 0.072f};
5333 luminance *= 1.0f - saturation;
5334 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5335 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5336 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5337 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5338 return saturationMatrix;
5339}
5340
5341void SurfaceFlinger::updateColorMatrixLocked() {
5342 mat4 colorMatrix =
5343 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5344
Chia-I Wu28f320b2018-05-03 11:02:56 -07005345 if (mCurrentState.colorMatrix != colorMatrix) {
5346 mCurrentState.colorMatrix = colorMatrix;
5347 mCurrentState.colorMatrixChanged = true;
5348 setTransactionFlags(eTransactionNeeded);
5349 }
5350}
5351
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005352status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005353#pragma clang diagnostic push
5354#pragma clang diagnostic error "-Wswitch-enum"
5355 switch (static_cast<ISurfaceComposerTag>(code)) {
5356 // These methods should at minimum make sure that the client requested
5357 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005358 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005359 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005360 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005361 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005362 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5363 // permission dynamically. Don't use the permission cache for this check.
5364 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005365 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005366 IPCThreadState* ipc = IPCThreadState::self();
5367 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5368 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005369 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005370 }
Robert Carr1db73f62016-12-21 12:58:51 -08005371 return OK;
5372 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005373 // The following calls are currently used by clients that do not
5374 // request necessary permissions. However, they do not expose any secret
5375 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005376 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005377 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005378 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005379 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005380 // Calling setTransactionState is safe, because you need to have been
5381 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005382 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005383 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005384 return OK;
5385 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005386 case BOOT_FINISHED:
5387 // Used by apps to hook Choreographer to SurfaceFlinger.
5388 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005389 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005390 case CREATE_DISPLAY:
5391 case DESTROY_DISPLAY:
5392 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5393 case GET_PHYSICAL_DISPLAY_IDS:
5394 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005395 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005396 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005397 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005398 case GET_DISPLAY_STATE:
5399 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005400 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005401 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005402 case GET_DISPLAY_NATIVE_PRIMARIES:
5403 case SET_ACTIVE_COLOR_MODE:
5404 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005405 case CLEAR_BOOT_DISPLAY_MODE:
5406 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5407 case SET_AUTO_LOW_LATENCY_MODE:
5408 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005409 case CAPTURE_LAYERS:
5410 case CAPTURE_DISPLAY:
5411 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005412 case CLEAR_ANIMATION_FRAME_STATS:
5413 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005414 case OVERRIDE_HDR_TYPES:
5415 case ON_PULL_ATOM:
5416 case ENABLE_VSYNC_INJECTIONS:
5417 case INJECT_VSYNC:
5418 case GET_LAYER_DEBUG_INFO:
5419 case GET_COLOR_MANAGEMENT:
5420 case GET_COMPOSITION_PREFERENCE:
5421 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5422 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005423 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005424 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005425 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005426 case ADD_REGION_SAMPLING_LISTENER:
5427 case REMOVE_REGION_SAMPLING_LISTENER:
5428 case ADD_FPS_LISTENER:
5429 case REMOVE_FPS_LISTENER:
5430 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5431 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5432 case ADD_WINDOW_INFOS_LISTENER:
5433 case REMOVE_WINDOW_INFOS_LISTENER:
5434 case SET_DESIRED_DISPLAY_MODE_SPECS:
5435 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005436 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5437 case SET_DISPLAY_BRIGHTNESS:
5438 case ADD_HDR_LAYER_INFO_LISTENER:
5439 case REMOVE_HDR_LAYER_INFO_LISTENER:
5440 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005441 case SET_GLOBAL_SHADOW_SETTINGS:
5442 case GET_DISPLAY_DECORATION_SUPPORT:
5443 case SET_FRAME_RATE:
5444 case SET_OVERRIDE_FRAME_RATE:
5445 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005446 case ADD_TRANSACTION_TRACE_LISTENER:
5447 case GET_GPU_CONTEXT_PRIORITY:
5448 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005449 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005450 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005451 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005452
5453 // These codes are used for the IBinder protocol to either interrogate the recipient
5454 // side of the transaction for its canonical interface descriptor or to dump its state.
5455 // We let them pass by default.
5456 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5457 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5458 code == IBinder::SYSPROPS_TRANSACTION) {
5459 return OK;
5460 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005461 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005462 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005463 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005464 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5465 return OK;
5466 }
5467 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5468 return PERMISSION_DENIED;
5469#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005470}
5471
Ana Krulec13be8ad2018-08-21 02:43:56 +00005472status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5473 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005474 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5475 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005476 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005477
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005478 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5479 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005480 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005481 IPCThreadState* ipc = IPCThreadState::self();
5482 const int uid = ipc->getCallingUid();
5483 if (CC_UNLIKELY(uid != AID_SYSTEM
5484 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005485 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005486 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005487 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005488 return PERMISSION_DENIED;
5489 }
5490 int n;
5491 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005492 case 1000: // Unused.
5493 case 1001:
5494 return NAME_NOT_FOUND;
5495 case 1002: // Toggle flashing on surface damage.
5496 if (const int delay = data.readInt32(); delay > 0) {
5497 mDebugFlashDelay = delay;
5498 } else {
5499 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5500 }
5501 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005502 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005503 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005504 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005505 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005506 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005507 case 1005: { // Force commit ahead of next VSYNC.
5508 Mutex::Autolock lock(mStateLock);
5509 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5510 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005511 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005512 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005513 case 1007: // Unused.
5514 return NAME_NOT_FOUND;
5515 case 1008: // Toggle forced GPU composition.
5516 mDebugDisableHWC = data.readInt32() != 0;
5517 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005518 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005519 case 1009: // Toggle use of transform hint.
5520 mDebugDisableTransformHint = data.readInt32() != 0;
5521 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005522 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005523 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005524 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005525 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005526 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005527 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005528 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005529 return NO_ERROR;
Dominik Laskowski8792c112022-07-12 09:03:39 -07005530 case 1013: // Unused.
5531 return NAME_NOT_FOUND;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005532 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005533 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005534 // daltonize
5535 n = data.readInt32();
5536 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005537 case 1:
5538 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5539 break;
5540 case 2:
5541 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5542 break;
5543 case 3:
5544 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5545 break;
5546 default:
5547 mDaltonizer.setType(ColorBlindnessType::None);
5548 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005549 }
5550 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005551 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005552 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005553 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005554 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005555
5556 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005557 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005558 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005559 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005560 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005561 // apply a color matrix
5562 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005563 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005564 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005565 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005566 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005567 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005568 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005569 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005570 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005571 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005572 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005573
5574 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5575 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005576 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005577 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5578 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5579 }
5580
Chia-I Wu28f320b2018-05-03 11:02:56 -07005581 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005582 return NO_ERROR;
5583 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005584 case 1016: { // Unused.
5585 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005586 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005587 case 1017: {
5588 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005589 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005590 return NO_ERROR;
5591 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005592 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005593 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005594 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005595 return NO_ERROR;
5596 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005597 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005598 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005599 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005600 return NO_ERROR;
5601 }
Irvel468051e2016-06-13 16:44:44 -07005602 case 1020: { // Layer updates interceptor
5603 n = data.readInt32();
5604 if (n) {
5605 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005606 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005607 }
5608 else{
5609 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005610 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005611 }
5612 return NO_ERROR;
5613 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005614 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005615 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005616 static_cast<void>(
5617 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005618 return NO_ERROR;
5619 }
Romain Guy0147a172017-06-01 13:53:56 -07005620 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005621 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005622 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005623
Chia-I Wu28f320b2018-05-03 11:02:56 -07005624 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005625 return NO_ERROR;
5626 }
Romain Guy54f154a2017-10-24 21:40:32 +01005627 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005628 int32_t colorMode;
5629
Chia-I Wu0d711262018-05-21 15:19:35 -07005630 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005631 if (data.readInt32(&colorMode) == NO_ERROR) {
5632 mForceColorMode = static_cast<ColorMode>(colorMode);
5633 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005634 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005635 return NO_ERROR;
5636 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005637 // Deprecate, use 1030 to check whether the device is color managed.
5638 case 1024: {
5639 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005640 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005641 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005642 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005643 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005644 if (n == 1) {
5645 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005646 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005647 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005648 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005649 int64_t startingTime =
5650 (fixedStartingTime) ? fixedStartingTime : systemTime();
5651 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005652 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Pablo Gamitob8775792022-06-10 15:02:42 +00005653 mLayerTracing.notify(true /* visibleRegionDirty */,
Dominik Laskowski08fbd852022-07-14 08:53:42 -07005654 startingTime, mLastCommittedVsyncId.value);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005655 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005656 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005657 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005658 } else if (n == 2) {
5659 std::string filename = std::string(data.readCString());
5660 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5661 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005662 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005663 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005664 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005665 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005666 mTracingEnabledChanged = tracingEnabledChanged;
5667 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005668 return NO_ERROR;
5669 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005670 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005671 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005672 return NO_ERROR;
5673 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005674 // Is a DisplayColorSetting supported?
5675 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005676 const auto display = getDefaultDisplayDevice();
5677 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005678 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005679 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005680
5681 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5682 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005683 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005684 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005685 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005686 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005687 reply->writeBool(true);
5688 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005689 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005690 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005691 break;
5692 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005693 reply->writeBool(
5694 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005695 break;
5696 }
5697 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005698 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005699 case 1028: { // Unused.
5700 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005701 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005702 // Set buffer size for SF tracing (value in KB)
5703 case 1029: {
5704 n = data.readInt32();
5705 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5706 ALOGW("Invalid buffer size: %d KB", n);
5707 reply->writeInt32(BAD_VALUE);
5708 return BAD_VALUE;
5709 }
5710
5711 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005712 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005713 reply->writeInt32(NO_ERROR);
5714 return NO_ERROR;
5715 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005716 // Is device color managed?
5717 case 1030: {
5718 reply->writeBool(useColorManagement);
5719 return NO_ERROR;
5720 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005721 // Override default composition data space
5722 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5723 // && adb shell stop zygote && adb shell start zygote
5724 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5725 // adb shell stop zygote && adb shell start zygote
5726 case 1031: {
5727 Mutex::Autolock _l(mStateLock);
5728 n = data.readInt32();
5729 if (n) {
5730 n = data.readInt32();
5731 if (n) {
5732 Dataspace dataspace = static_cast<Dataspace>(n);
5733 if (!validateCompositionDataspace(dataspace)) {
5734 return BAD_VALUE;
5735 }
5736 mDefaultCompositionDataspace = dataspace;
5737 }
5738 n = data.readInt32();
5739 if (n) {
5740 Dataspace dataspace = static_cast<Dataspace>(n);
5741 if (!validateCompositionDataspace(dataspace)) {
5742 return BAD_VALUE;
5743 }
5744 mWideColorGamutCompositionDataspace = dataspace;
5745 }
5746 } else {
5747 // restore composition data space.
5748 mDefaultCompositionDataspace = defaultCompositionDataspace;
5749 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5750 }
5751 return NO_ERROR;
5752 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005753 // Set trace flags
5754 case 1033: {
5755 n = data.readUint32();
5756 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005757 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005758 reply->writeInt32(NO_ERROR);
5759 return NO_ERROR;
5760 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005761 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005762 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005763 switch (n = data.readInt32()) {
5764 case 0:
5765 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005766 FTL_FAKE_GUARD(mStateLock,
5767 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005768 break;
5769 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005770 reply->writeBool(
5771 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005772 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005773 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005774 });
5775
5776 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005777 return NO_ERROR;
5778 }
Ady Abraham34392f72019-04-10 11:29:27 -07005779 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005780 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005781
Dominik Laskowskif1833852021-03-23 15:06:50 -07005782 const auto display = [&]() -> sp<IBinder> {
5783 uint64_t value;
5784 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005785 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005786 }
5787
Dominik Laskowskif1833852021-03-23 15:06:50 -07005788 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5789 return getPhysicalDisplayToken(*id);
5790 }
5791
5792 ALOGE("Invalid physical display ID");
5793 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005794 }();
5795
Shiyong Li2bcece92021-08-30 20:38:50 +00005796 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005797 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005798 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5799 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005800 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005801 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5802 // manager frame rate policy a new policy which allows switching between all refresh
5803 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005804 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005805 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005806 return mScheduler
5807 ->schedule([this] {
5808 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005809 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005810
Dominik Laskowski756b7892021-08-04 12:53:59 -07005811 // This is a little racy, but not in a way that hurts anything. As
5812 // we grab the defaultMode from the display manager policy, we could
5813 // be setting a new display manager policy, leaving us using a stale
5814 // defaultMode. The defaultMode doesn't matter for the override
5815 // policy though, since we set allowGroupSwitching to true, so it's
5816 // not a problem.
5817 scheduler::RefreshRateConfigs::Policy overridePolicy;
5818 overridePolicy.defaultMode = display->refreshRateConfigs()
5819 .getDisplayManagerPolicy()
5820 .defaultMode;
5821 overridePolicy.allowGroupSwitching = true;
5822 constexpr bool kOverridePolicy = true;
5823 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5824 kOverridePolicy);
5825 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005826 .get();
5827 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07005828 return mScheduler
5829 ->schedule([this] {
5830 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005831 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07005832 constexpr bool kOverridePolicy = true;
5833 return setDesiredDisplayModeSpecsInternal(display, {},
5834 kOverridePolicy);
5835 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005836 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07005837 }
Ady Abraham07e54702020-04-16 15:05:37 -07005838 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02005839 // Inject a hotplug connected event for the primary display. This will deallocate and
5840 // reallocate the display state including framebuffers.
5841 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07005842 const hal::HWDisplayId hwcId =
5843 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
5844
5845 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02005846 return NO_ERROR;
5847 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07005848 // Modify the max number of display frames stored within FrameTimeline
5849 case 1038: {
5850 n = data.readInt32();
5851 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
5852 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
5853 return BAD_VALUE;
5854 }
5855 if (n == 0) {
5856 // restore to default
5857 mFrameTimeline->reset();
5858 return NO_ERROR;
5859 }
5860 mFrameTimeline->setMaxDisplayFrames(n);
5861 return NO_ERROR;
5862 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07005863 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07005864 PhysicalDisplayId displayId = [&]() {
5865 Mutex::Autolock lock(mStateLock);
5866 return getDefaultDisplayDeviceLocked()->getPhysicalId();
5867 }();
5868
5869 auto inUid = static_cast<uid_t>(data.readInt32());
5870 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08005871 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
5872 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07005873 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08005874 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005875 // Toggle caching feature
5876 // First argument is an int32 - nonzero enables caching and zero disables caching
5877 // Second argument is an optional uint64 - if present, then limits enabling/disabling
5878 // caching to a particular physical display
5879 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005880 auto future = mScheduler->schedule([&] {
5881 n = data.readInt32();
5882 std::optional<PhysicalDisplayId> inputId = std::nullopt;
5883 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
5884 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
5885 if (!inputId || getPhysicalDisplayToken(*inputId)) {
5886 ALOGE("No display with id: %" PRIu64, inputDisplayId);
5887 return NAME_NOT_FOUND;
5888 }
5889 }
5890 {
5891 Mutex::Autolock lock(mStateLock);
5892 mLayerCachingEnabled = n != 0;
5893 for (const auto& [_, display] : mDisplays) {
5894 if (!inputId || *inputId == display->getPhysicalId()) {
5895 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07005896 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005897 }
5898 }
5899 return OK;
5900 });
Alec Mouricdd722b2021-05-19 14:29:05 -07005901
Dominik Laskowski756b7892021-08-04 12:53:59 -07005902 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07005903 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005904 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005905 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005906 return NO_ERROR;
5907 }
Vishnu Nair7891e962021-11-11 12:07:21 -08005908 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08005909 if (mTransactionTracing) {
5910 if (data.readInt32()) {
5911 // Transaction tracing is always running but allow the user to temporarily
5912 // increase the buffer when actively debugging.
5913 mTransactionTracing->setBufferSize(
5914 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
5915 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005916 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005917 mTransactionTracing->setBufferSize(
5918 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005919 }
Vishnu Nair7891e962021-11-11 12:07:21 -08005920 }
5921 reply->writeInt32(NO_ERROR);
5922 return NO_ERROR;
5923 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005924 case 1042: { // Write layers trace or transaction trace to file
5925 if (mTransactionTracing) {
5926 mTransactionTracing->writeToFile();
5927 }
5928 if (mLayerTracingEnabled) {
5929 mLayerTracing.writeToFile();
5930 }
5931 reply->writeInt32(NO_ERROR);
5932 return NO_ERROR;
5933 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005934 }
5935 }
5936 return err;
5937}
5938
Ady Abrahama09852a2020-02-20 14:23:42 -08005939void SurfaceFlinger::kernelTimerChanged(bool expired) {
5940 static bool updateOverlay =
5941 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005942 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005943
5944 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005945 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07005946 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005947 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07005948 if (!display) {
5949 ALOGW("%s: default display is null", __func__);
5950 return;
5951 }
Adrian Salidoa942af82022-02-17 19:22:31 -08005952 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07005953
5954 const auto desiredActiveMode = display->getDesiredActiveMode();
5955 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
5956 ? std::make_optional(desiredActiveMode->mode->getId())
5957 : std::nullopt;
5958
5959 const bool timerExpired = mKernelIdleTimerEnabled && expired;
5960
Ady Abraham1b11bc62021-06-03 19:51:19 -07005961 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005962 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08005963 }
5964 }));
5965}
5966
ramindani32cf0602022-03-02 02:30:29 +00005967std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
5968SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
5969 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
5970 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
5971 const auto timeout = getIdleTimerTimeout(displayId);
5972 if (isKernelIdleTimerHwcSupported) {
5973 if (const auto id = PhysicalDisplayId::tryCast(displayId);
5974 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
5975 // In order to decide if we can use the HWC api for idle timer
5976 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
5977 // without relying on hasDisplayCapability.
5978 // hasDisplayCapability relies on DisplayCapabilities
5979 // which are updated after we set the PowerMode::ON.
5980 // DISPLAY_IDLE_TIMER is a display driver property
5981 // and is available before the PowerMode::ON
5982 return {KernelIdleTimerController::HwcApi, timeout};
5983 }
5984 return {std::nullopt, timeout};
5985 }
5986 if (getKernelIdleTimerSyspropConfig(displayId)) {
5987 return {KernelIdleTimerController::Sysprop, timeout};
5988 }
5989
5990 return {std::nullopt, timeout};
5991}
5992
5993void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
5994 KernelIdleTimerController controller,
5995 PhysicalDisplayId displayId) {
5996 switch (controller) {
5997 case KernelIdleTimerController::HwcApi: {
5998 getHwComposer().setIdleTimerEnabled(displayId, timeout);
5999 break;
6000 }
6001 case KernelIdleTimerController::Sysprop: {
6002 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6003 break;
6004 }
6005 }
6006}
6007
Ana Krulecb9afd792020-06-11 13:16:15 -07006008void SurfaceFlinger::toggleKernelIdleTimer() {
6009 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6010
Ady Abraham3efa3942021-06-24 19:01:25 -07006011 const auto display = getDefaultDisplayDeviceLocked();
6012 if (!display) {
6013 ALOGW("%s: default display is null", __func__);
6014 return;
6015 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006016
Ady Abrahame9316b72021-09-24 17:04:36 -07006017 // If the support for kernel idle timer is disabled for the active display,
6018 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006019 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6020 display->refreshRateConfigs().kernelIdleTimerController();
6021 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006022 return;
6023 }
6024
Ady Abraham3efa3942021-06-24 19:01:25 -07006025 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006026
Ana Krulecb9afd792020-06-11 13:16:15 -07006027 switch (action) {
6028 case KernelIdleTimerAction::TurnOff:
6029 if (mKernelIdleTimerEnabled) {
6030 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006031 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6032 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6033 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006034 mKernelIdleTimerEnabled = false;
6035 }
6036 break;
6037 case KernelIdleTimerAction::TurnOn:
6038 if (!mKernelIdleTimerEnabled) {
6039 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006040 const std::chrono::milliseconds timeout =
6041 display->refreshRateConfigs().getIdleTimerTimeout();
6042 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6043 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006044 mKernelIdleTimerEnabled = true;
6045 }
6046 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006047 }
6048}
6049
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006050// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6051class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006052public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006053 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6054 ~WindowDisconnector() {
6055 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006056 }
6057
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006058private:
6059 ANativeWindow* mWindow;
6060 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006061};
6062
chaviw93df2ea2019-04-30 16:45:12 -07006063static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6064 switch (colorMode) {
6065 case ColorMode::DISPLAY_P3:
6066 case ColorMode::BT2100_PQ:
6067 case ColorMode::BT2100_HLG:
6068 case ColorMode::DISPLAY_BT2020:
6069 return Dataspace::DISPLAY_P3;
6070 default:
6071 return Dataspace::V0_SRGB;
6072 }
6073}
6074
chaviwf5bb97b2021-04-28 15:35:37 -05006075static bool hasCaptureBlackoutContentPermission() {
6076 IPCThreadState* ipc = IPCThreadState::self();
6077 const int pid = ipc->getCallingPid();
6078 const int uid = ipc->getCallingUid();
6079 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6080 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6081}
6082
chaviw4b9d5e12020-08-04 18:30:35 -07006083static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6084 IPCThreadState* ipc = IPCThreadState::self();
6085 const int pid = ipc->getCallingPid();
6086 const int uid = ipc->getCallingUid();
6087 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6088 return OK;
6089 }
6090
6091 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6092 // itself, we allow it to continue.
6093 if (captureArgs.uid == uid) {
6094 return OK;
6095 }
6096
6097 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6098 return PERMISSION_DENIED;
6099}
6100
Peiyong Lin05cc0112020-10-14 16:16:37 -07006101status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6102 static constexpr int kFifoPriority = 2;
6103 static constexpr int kOtherPriority = 0;
6104
6105 struct sched_param param = {0};
6106 int sched_policy;
6107 if (enabled) {
6108 sched_policy = SCHED_FIFO;
6109 param.sched_priority = kFifoPriority;
6110 } else {
6111 sched_policy = SCHED_OTHER;
6112 param.sched_priority = kOtherPriority;
6113 }
6114
6115 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6116 return -errno;
6117 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006118
6119 return NO_ERROR;
6120}
6121
6122status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6123 static const unsigned int kUclampMin =
6124 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6125
6126 if (!kUclampMin) {
6127 // uclamp.min set to 0 (default), skip setting
6128 return NO_ERROR;
6129 }
6130
6131 // Currently, there is no wrapper in bionic: b/183240349.
6132 struct sched_attr {
6133 uint32_t size;
6134 uint32_t sched_policy;
6135 uint64_t sched_flags;
6136 int32_t sched_nice;
6137 uint32_t sched_priority;
6138 uint64_t sched_runtime;
6139 uint64_t sched_deadline;
6140 uint64_t sched_period;
6141 uint32_t sched_util_min;
6142 uint32_t sched_util_max;
6143 };
6144
6145 sched_attr attr = {};
6146 attr.size = sizeof(attr);
6147
6148 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6149 attr.sched_util_min = enabled ? kUclampMin : 0;
6150 attr.sched_util_max = 1024;
6151
6152 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6153 return -errno;
6154 }
6155
Peiyong Lin05cc0112020-10-14 16:16:37 -07006156 return NO_ERROR;
6157}
6158
chaviwd2432892020-07-24 17:42:39 -07006159status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006160 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006161 ATRACE_CALL();
6162
chaviw4b9d5e12020-08-04 18:30:35 -07006163 status_t validate = validateScreenshotPermissions(args);
6164 if (validate != OK) {
6165 return validate;
6166 }
6167
chaviwd2432892020-07-24 17:42:39 -07006168 if (!args.displayToken) return BAD_VALUE;
6169
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006170 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006171 ui::LayerStack layerStack;
6172 ui::Size reqSize(args.width, args.height);
6173 ui::Dataspace dataspace;
6174 {
6175 Mutex::Autolock lock(mStateLock);
6176 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6177 if (!display) return NAME_NOT_FOUND;
6178 displayWeak = display;
6179 layerStack = display->getLayerStack();
6180
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006181 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006182 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006183 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006184 }
6185
arthurhung79e81aa2020-08-28 00:09:19 +08006186 // The dataspace is depended on the color mode of display, that could use non-native mode
6187 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6188 // and failed if display is not in native mode. This provide a way to force using native
6189 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006190 dataspace = args.dataspace;
6191 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006192 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6193 dataspace = pickDataspaceFromColorMode(colorMode);
6194 }
chaviwd2432892020-07-24 17:42:39 -07006195 }
6196
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006197 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006198 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006199 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006200 });
6201
chaviw4b9d5e12020-08-04 18:30:35 -07006202 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6203 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006204 };
chaviw03900772020-08-18 12:34:51 -07006205
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006206 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6207 args.pixelFormat, args.allowProtected, args.grayscale,
6208 captureListener);
6209 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006210}
6211
Dominik Laskowskif1833852021-03-23 15:06:50 -07006212status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006213 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006214 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006215 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006216 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006217 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006218 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006219 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006220
Dominik Laskowskif1833852021-03-23 15:06:50 -07006221 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006222 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006223 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006224 }
6225
chaviw93df2ea2019-04-30 16:45:12 -07006226 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006227 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006228 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006229
chaviw426b5c02020-07-27 11:20:15 -07006230 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006231 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6232 }
6233
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006234 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006235 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006236 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006237 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006238 });
chaviw93df2ea2019-04-30 16:45:12 -07006239
Marin Shalamanov1c434292020-06-12 01:47:29 +02006240 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006241 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006242 };
6243
Sally Qi59a9f502021-10-12 18:53:23 +00006244 if (captureListener == nullptr) {
6245 ALOGE("capture screen must provide a capture listener callback");
6246 return BAD_VALUE;
6247 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006248
6249 constexpr bool kAllowProtected = false;
6250 constexpr bool kGrayscale = false;
6251
6252 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6253 ui::PixelFormat::RGBA_8888, kAllowProtected, kGrayscale,
6254 captureListener);
6255 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006256}
6257
chaviw3efadb12020-07-27 10:07:15 -07006258status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006259 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006260 ATRACE_CALL();
6261
chaviw4b9d5e12020-08-04 18:30:35 -07006262 status_t validate = validateScreenshotPermissions(args);
6263 if (validate != OK) {
6264 return validate;
6265 }
6266
Marin Shalamanov1c434292020-06-12 01:47:29 +02006267 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006268 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006269 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006270 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006271 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006272
6273 // Call this before holding mStateLock to avoid any deadlocking.
6274 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6275
Robert Carrc0df3122019-04-11 13:18:21 -07006276 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006277 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006278
Vishnu Nairf9096652021-07-20 18:49:42 -07006279 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006280 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006281 ALOGE("captureLayers called with an invalid or removed parent");
6282 return NAME_NOT_FOUND;
6283 }
6284
chaviwf5bb97b2021-04-28 15:35:37 -05006285 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006286 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006287 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6288 return PERMISSION_DENIED;
6289 }
6290
Robert Carr6a160312021-05-17 12:08:20 -07006291 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006292 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006293 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006294 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006295 }
6296
chaviw3efadb12020-07-27 10:07:15 -07006297 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006298 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006299 crop.bottom = parentSourceBounds.getHeight();
6300 }
6301
chaviw17ac24b2021-01-28 18:50:05 -08006302 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006303 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6304 // crop was not specified, or an invalid frame scale was provided.
6305 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006306 }
chaviw17ac24b2021-01-28 18:50:05 -08006307 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006308
chaviw3efadb12020-07-27 10:07:15 -07006309 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006310 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006311 if (excludeLayer != nullptr) {
6312 excludeLayers.emplace(excludeLayer);
6313 } else {
6314 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6315 return NAME_NOT_FOUND;
6316 }
6317 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006318
arthurhung79e81aa2020-08-28 00:09:19 +08006319 // The dataspace is depended on the color mode of display, that could use non-native mode
6320 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6321 // and failed if display is not in native mode. This provide a way to force using native
6322 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006323 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006324 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006325
Chia-I Wu20261cb2018-08-23 12:55:44 -07006326 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006327 if (reqSize.width <= 0 || reqSize.height <= 0) {
6328 ALOGW("Failed to captureLayes: crop or scale too small");
6329 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006330 }
6331
chaviw79468ab2021-10-27 11:11:24 -05006332 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006333 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006334 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006335 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006336 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006337 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006338 });
6339
chaviw03900772020-08-18 12:34:51 -07006340 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006341 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6342 if (!layer->isVisible()) {
6343 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006344 } else if (args.childrenOnly && layer == parent.get()) {
6345 return;
6346 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006347 return;
chaviwa76b2712017-09-20 12:02:26 -07006348 }
Robert Carr866455f2019-04-02 16:28:26 -07006349
Ady Abrahamd11bade2022-08-01 16:18:03 -07006350 auto p = sp<Layer>::fromExisting(layer);
Robert Carr866455f2019-04-02 16:28:26 -07006351 while (p != nullptr) {
6352 if (excludeLayers.count(p) != 0) {
6353 return;
6354 }
6355 p = p->getParent();
6356 }
6357
chaviwa76b2712017-09-20 12:02:26 -07006358 visitor(layer);
6359 });
6360 };
Robert Carr108b2c72019-04-02 16:32:58 -07006361
Sally Qi59a9f502021-10-12 18:53:23 +00006362 if (captureListener == nullptr) {
6363 ALOGE("capture screen must provide a capture listener callback");
6364 return BAD_VALUE;
6365 }
6366
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006367 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6368 args.pixelFormat, args.allowProtected, args.grayscale,
6369 captureListener);
6370 return fenceStatus(future.get());
chaviwa76b2712017-09-20 12:02:26 -07006371}
6372
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006373ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Sally Qi59a9f502021-10-12 18:53:23 +00006374 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6375 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6376 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006377 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006378
Garfield Tan9c9c1912021-07-19 12:02:16 -07006379 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6380 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6381 ") that exceeds render target size limit.",
6382 bufferSize.getWidth(), bufferSize.getHeight());
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006383 return ftl::yield<FenceResult>(base::unexpected(BAD_VALUE)).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006384 }
6385
Peiyong Lin05cc0112020-10-14 16:16:37 -07006386 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6387 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6388 // A protected layer has no implication on whether it's secure, which is explicitly set by
6389 // application to avoid being screenshot or drawn via unsecure display.
6390 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6391 bool hasProtectedLayer = false;
6392 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006393 auto future = mScheduler->schedule([=]() {
6394 bool protectedLayerFound = false;
6395 traverseLayers([&](Layer* layer) {
6396 protectedLayerFound =
6397 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6398 });
6399 return protectedLayerFound;
6400 });
6401 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006402 }
6403
Richard Liucbcb8952020-04-08 10:51:55 +00006404 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6405 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006406 (hasProtectedLayer && allowProtected && supportsProtected
6407 ? GRALLOC_USAGE_PROTECTED
6408 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006409 sp<GraphicBuffer> buffer =
6410 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6411 static_cast<android_pixel_format>(reqPixelFormat),
6412 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006413
6414 const status_t bufferStatus = buffer->initCheck();
Alec Mourid8f17c52022-07-21 18:43:10 +00006415 if (bufferStatus != OK) {
6416 // Animations may end up being really janky, but don't crash here.
6417 // Otherwise an irreponsible process may cause an SF crash by allocating
6418 // too much.
6419 ALOGE("%s: Buffer failed to allocate: %d", __func__, bufferStatus);
6420 return ftl::yield<FenceResult>(base::unexpected(bufferStatus)).share();
6421 }
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006422 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6423 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6424 renderengine::impl::ExternalTexture::Usage::
6425 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006426 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006427 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006428}
6429
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006430ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006431 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6432 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6433 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006434 ATRACE_CALL();
6435
chaviwf5bb97b2021-04-28 15:35:37 -05006436 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006437
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006438 auto future = mScheduler->schedule([=, renderAreaFuture = std::move(renderAreaFuture)]() mutable
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006439 -> ftl::SharedFuture<FenceResult> {
chaviw03900772020-08-18 12:34:51 -07006440 ScreenCaptureResults captureResults;
6441 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6442 if (!renderArea) {
6443 ALOGW("Skipping screen capture because of invalid render area.");
Patrick Williamsfdb57bb2022-08-09 22:48:18 +00006444 captureResults.fenceResult = base::unexpected(NO_MEMORY);
Ady Abraham99599942021-01-27 20:27:23 -08006445 captureListener->onScreenCaptureCompleted(captureResults);
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006446 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
chaviw03900772020-08-18 12:34:51 -07006447 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006448
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006449 ftl::SharedFuture<FenceResult> renderFuture;
chaviw03900772020-08-18 12:34:51 -07006450 renderArea->render([&] {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006451 renderFuture =
6452 renderScreenImpl(*renderArea, traverseLayers, buffer, canCaptureBlackoutContent,
6453 regionSampling, grayscale, captureResults);
chaviw03900772020-08-18 12:34:51 -07006454 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006455
6456 if (captureListener) {
Dominik Laskowskifb3beed2022-07-07 07:34:38 -07006457 // Defer blocking on renderFuture back to the Binder thread.
6458 return ftl::Future(std::move(renderFuture))
6459 .then([captureListener, captureResults = std::move(captureResults)](
6460 FenceResult fenceResult) mutable -> FenceResult {
Patrick Williamsfdb57bb2022-08-09 22:48:18 +00006461 captureResults.fenceResult = std::move(fenceResult);
Dominik Laskowskifb3beed2022-07-07 07:34:38 -07006462 captureListener->onScreenCaptureCompleted(captureResults);
6463 return base::unexpected(NO_ERROR);
6464 })
6465 .share();
Sally Qi59a9f502021-10-12 18:53:23 +00006466 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006467 return renderFuture;
Sally Qi59a9f502021-10-12 18:53:23 +00006468 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006469
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006470 // Flatten nested futures.
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006471 auto chain = ftl::Future(std::move(future)).then([](ftl::SharedFuture<FenceResult> future) {
6472 return future;
6473 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006474
6475 return chain.share();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006476}
6477
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006478ftl::SharedFuture<FenceResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006479 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006480 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6481 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6482 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006483 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006484
chaviw426b5c02020-07-27 11:20:15 -07006485 traverseLayers([&](Layer* layer) {
6486 captureResults.capturedSecureLayers =
6487 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6488 });
6489
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006490 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006491
chaviw426b5c02020-07-27 11:20:15 -07006492 // We allow the system server to take screenshots of secure layers for
6493 // use in situations like the Screen-rotation animation and place
6494 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006495 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006496 ALOGW("FB is protected: PERMISSION_DENIED");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006497 return ftl::yield<FenceResult>(base::unexpected(PERMISSION_DENIED)).share();
chaviw426b5c02020-07-27 11:20:15 -07006498 }
6499
Alec Mouria90a5702021-04-16 16:36:21 +00006500 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006501 auto dataspace = renderArea.getReqDataSpace();
6502 auto parent = renderArea.getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00006503 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07006504 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
6505 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
6506
Robert Carr12a3b9b2022-03-10 09:55:29 -08006507 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6508 Mutex::Autolock lock(mStateLock);
6509 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6510 return display.getLayerStack() == layerStack;
6511 });
6512 if (!display) {
6513 // If the layer is not on a display, use the dataspace for the default display.
6514 display = getDefaultDisplayDeviceLocked();
6515 }
6516
6517 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6518 dataspace = pickDataspaceFromColorMode(colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00006519 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07006520 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
6521 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08006522 }
6523 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006524
chaviwa76b2712017-09-20 12:02:26 -07006525 const auto reqWidth = renderArea.getReqWidth();
6526 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006527 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006528 const auto transform = renderArea.getTransform();
6529 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006530 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006531
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006532 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006533 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006534
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006535 // assume that bounds are never offset, and that they are the same as the
6536 // buffer bounds.
6537 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006538 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006539 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006540
Robert Carr12a3b9b2022-03-10 09:55:29 -08006541 clientCompositionDisplay.outputDataspace = dataspace;
Sally Qie258f092022-05-19 15:24:12 -07006542 clientCompositionDisplay.currentLuminanceNits = displayBrightnessNits;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006543 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006544 clientCompositionDisplay.renderIntent =
6545 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006546
chaviw17ac24b2021-01-28 18:50:05 -08006547 const float colorSaturation = grayscale ? 0 : 1;
6548 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6549
chaviw50da5042018-04-09 13:49:37 -07006550 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006551
Vishnu Nair9b079a22020-01-21 14:36:08 -08006552 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006553 fillLayer.source.buffer.buffer = nullptr;
6554 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006555 fillLayer.geometry.boundaries =
6556 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006557 fillLayer.alpha = half(alpha);
6558 clientCompositionLayers.push_back(fillLayer);
6559
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006560 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006561 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006562 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006563 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006564 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006565
Lloyd Piquef16688f2019-02-19 17:47:57 -08006566 Region clip(renderArea.getBounds());
6567 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6568 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006569 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006570 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006571 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006572 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006573 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006574 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006575 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006576 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006577 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6578 BlurSetting::Disabled
6579 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6580 BlurSetting::Enabled,
Sally Qidb653012022-05-04 13:12:22 -07006581 isHdrLayer(layer) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006582
Lloyd Piquef16688f2019-02-19 17:47:57 -08006583 };
Patrick Williams16d8b2c2022-08-08 17:29:05 +00006584 std::optional<compositionengine::LayerFE::LayerSettings> settings =
6585 layer->prepareClientComposition(targetSettings);
6586 if (!settings) {
6587 return;
Yichi Chen40773d92020-04-01 10:10:18 +08006588 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006589
Patrick Williams16d8b2c2022-08-08 17:29:05 +00006590 settings->geometry.positionTransform =
6591 transform.asMatrix4() * settings->geometry.positionTransform;
6592 // There's no need to process blurs when we're executing region sampling,
6593 // we're just trying to understand what we're drawing, and doing so without
6594 // blurs is already a pretty good approximation.
6595 if (regionSampling) {
6596 settings->backgroundBlurRadius = 0;
Patrick Williams3fbc8ca2022-08-19 15:35:24 +00006597 settings->blurRegions.clear();
Patrick Williams16d8b2c2022-08-08 17:29:05 +00006598 }
6599 captureResults.capturedHdrLayers |= isHdrLayer(layer);
6600
6601 clientCompositionLayers.push_back(std::move(*settings));
6602 renderedLayers.push_back(layer);
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;
Patrick Williams2e9748f2022-08-09 22:48:18 +00006618 const auto future = getRenderEngine()
6619 .drawLayers(clientCompositionDisplay, clientRenderEngineLayers,
6620 buffer, kUseFramebufferCache, std::move(bufferFence))
6621 .share();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006622
Sally Qi59a9f502021-10-12 18:53:23 +00006623 for (auto* layer : renderedLayers) {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006624 layer->onLayerDisplayed(future);
Yichi Chen40773d92020-04-01 10:10:18 +08006625 }
Ady Abraham99599942021-01-27 20:27:23 -08006626
Peiyong Lin05cc0112020-10-14 16:16:37 -07006627 // Always switch back to unprotected context.
6628 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006629
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006630 return future;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006631}
6632
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006633// ---------------------------------------------------------------------------
6634
Edgar Arriaga844fa672020-01-16 14:21:42 -08006635void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6636 layersSortedByZ.traverse(visitor);
6637}
6638
Dan Stoza412903f2017-04-27 13:42:17 -07006639void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6640 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006641}
6642
Dan Stoza412903f2017-04-27 13:42:17 -07006643void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6644 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006645}
6646
chaviw4b9d5e12020-08-04 18:30:35 -07006647void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006648 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006649 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006650 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006651 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006652 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006653 continue;
6654 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006655 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006656 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006657 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006658 return;
6659 }
chaviwa76b2712017-09-20 12:02:26 -07006660 if (!layer->isVisible()) {
6661 return;
6662 }
chaviw4b9d5e12020-08-04 18:30:35 -07006663 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6664 return;
6665 }
chaviwa76b2712017-09-20 12:02:26 -07006666 visitor(layer);
6667 });
6668 }
6669}
6670
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006671status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006672 const sp<DisplayDevice>& display,
6673 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006674 Mutex::Autolock lock(mStateLock);
6675
Ady Abrahamfb853662021-04-09 11:46:40 -07006676 if (mDebugDisplayModeSetByBackdoor) {
6677 // ignore this request as mode is overridden by backdoor
6678 return NO_ERROR;
6679 }
6680
Ady Abrahama92a5682022-06-07 23:35:38 +00006681 const status_t setPolicyResult = display->setRefreshRatePolicy(policy, overridePolicy);
Ady Abraham3efa3942021-06-24 19:01:25 -07006682 if (setPolicyResult < 0) {
6683 return BAD_VALUE;
6684 }
6685 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6686 return NO_ERROR;
6687 }
6688
Ady Abraham3efa3942021-06-24 19:01:25 -07006689 scheduler::RefreshRateConfigs::Policy currentPolicy =
6690 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006691
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006692 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006693
Ana Krulecb9afd792020-06-11 13:16:15 -07006694 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6695 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006696 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006697 if (isDisplayActiveLocked(display)) {
6698 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6699 toggleKernelIdleTimer();
6700 } else {
6701 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6702 }
Ady Abraham838de062019-02-04 10:24:03 -08006703
Ady Abraham690f4612021-07-01 23:24:03 -07006704 const DisplayModePtr preferredDisplayMode = [&] {
6705 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6706 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6707 return schedulerMode;
6708 }
6709
6710 return display->getMode(currentPolicy.defaultMode);
6711 }();
6712
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006713 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006714 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006715
Ady Abraham690f4612021-07-01 23:24:03 -07006716 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006717 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006718 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006719 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006720 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006721 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006722 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006723 }
6724
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006725 return NO_ERROR;
6726}
6727
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006728status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6729 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6730 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6731 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006732 ATRACE_CALL();
6733
6734 if (!displayToken) {
6735 return BAD_VALUE;
6736 }
6737
Dominik Laskowski756b7892021-08-04 12:53:59 -07006738 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006739 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006740 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006741 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006742 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006743 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006744 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006745 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006746 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006747 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006748 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006749 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006750 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006751 {Fps::fromValue(primaryRefreshRateMin),
6752 Fps::fromValue(primaryRefreshRateMax)},
6753 {Fps::fromValue(appRequestRefreshRateMin),
6754 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006755 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006756
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006757 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006758 }
6759 });
6760
6761 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006762}
6763
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006764status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6765 ui::DisplayModeId* outDefaultMode,
6766 bool* outAllowGroupSwitching,
6767 float* outPrimaryRefreshRateMin,
6768 float* outPrimaryRefreshRateMax,
6769 float* outAppRequestRefreshRateMin,
6770 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006771 ATRACE_CALL();
6772
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006773 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006774 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006775 return BAD_VALUE;
6776 }
6777
6778 Mutex::Autolock lock(mStateLock);
6779 const auto display = getDisplayDeviceLocked(displayToken);
6780 if (!display) {
6781 return NAME_NOT_FOUND;
6782 }
6783
Ady Abraham3efa3942021-06-24 19:01:25 -07006784 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006785 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006786 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006787
6788 scheduler::RefreshRateConfigs::Policy policy =
6789 display->refreshRateConfigs().getDisplayManagerPolicy();
6790 *outDefaultMode = policy.defaultMode.value();
6791 *outAllowGroupSwitching = policy.allowGroupSwitching;
6792 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6793 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6794 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6795 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6796 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006797}
6798
Vishnu Nairf9096652021-07-20 18:49:42 -07006799wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6800 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006801}
6802
Dominik Laskowski75848362019-11-11 17:57:20 -08006803void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006804 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006805 if (!layer->isRemovedFromCurrentState()) {
6806 mScheduler->registerLayer(layer);
6807 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006808}
6809
6810void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6811 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006812 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006813 if (!layer->isRemovedFromCurrentState()) {
6814 mScheduler->deregisterLayer(layer);
6815 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08006816 if (mTransactionTracing) {
6817 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08006818 }
Valerie Hauc5686802019-11-22 14:18:09 -08006819}
6820
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006821void SurfaceFlinger::onLayerUpdate() {
6822 scheduleCommit(FrameHint::kActive);
6823}
6824
Valerie Hauc5686802019-11-22 14:18:09 -08006825// WARNING: ONLY CALL THIS FROM LAYER DTOR
6826// Here we add children in the current state to offscreen layers and remove the
6827// layer itself from the offscreen layer list. Since
6828// this is the dtor, it is safe to access the current state. This keeps us
6829// from dangling children layers such that they are not reachable from the
6830// Drawing state nor the offscreen layer list
6831// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07006832void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08006833 for (auto& child : layer->getCurrentChildren()) {
6834 mOffscreenLayers.emplace(child.get());
6835 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006836 mOffscreenLayers.erase(layer);
6837}
6838
Robert Carr867be372021-06-29 17:36:02 -07006839void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6840 mOffscreenLayers.erase(layer);
6841}
6842
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006843status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6844 float lightPosY, float lightPosZ,
6845 float lightRadius) {
6846 Mutex::Autolock _l(mStateLock);
6847 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6848 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6849 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6850 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6851 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6852
6853 // these values are overridden when calculating the shadow settings for a layer.
6854 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6855 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006856 return NO_ERROR;
6857}
6858
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006859const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6860 const {
6861 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6862 // on the work to remove the table in that bug rather than adding more to
6863 // it.
6864 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08006865 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
6866 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006867 };
6868 return genericLayerMetadataKeyMap;
6869}
6870
Andy Yu2ae6b6b2021-11-18 14:51:06 -08006871status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
6872 PhysicalDisplayId displayId = [&]() {
6873 Mutex::Autolock lock(mStateLock);
6874 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6875 }();
6876
6877 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
6878 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
6879 return NO_ERROR;
6880}
6881
Dominik Laskowski20134642020-04-20 22:36:44 -07006882void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07006883 for (const auto& [ignored, display] : mDisplays) {
6884 if (display->isInternal()) {
6885 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07006886 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07006887 }
Dominik Laskowski20134642020-04-20 22:36:44 -07006888}
6889
Pablo Gamito6ee484d2020-07-30 14:26:28 +00006890status_t SurfaceFlinger::addTransactionTraceListener(
6891 const sp<gui::ITransactionTraceListener>& listener) {
6892 if (!listener) {
6893 return BAD_VALUE;
6894 }
6895
6896 mInterceptor->addTransactionTraceListener(listener);
6897
6898 return NO_ERROR;
6899}
6900
Huihong Luo02186fb2022-02-23 14:21:54 -08006901int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08006902 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08006903}
6904
Ady Abraham899dcdb2021-06-15 16:56:21 -07006905int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
6906 std::chrono::nanoseconds presentLatency) {
6907 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
6908 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08006909 pipelineDepth++;
6910 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07006911 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08006912}
6913
Ady Abraham899dcdb2021-06-15 16:56:21 -07006914status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006915 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006916
6917 if (!getHwComposer().isHeadless()) {
6918 if (const auto display = getDefaultDisplayDevice()) {
6919 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07006920 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006921 }
6922
6923 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08006924 return NO_ERROR;
6925}
6926
rnleeed20fa42021-08-10 18:00:03 -07006927uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006928 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07006929
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006930 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
6931 refreshRate = *frameRateOverride;
6932 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006933 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006934 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07006935 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006936 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006937
Ady Abraham899dcdb2021-06-15 16:56:21 -07006938 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
6939}
6940
6941int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
6942 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
6943 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
6944 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
6945}
6946
Dominik Laskowski08fbd852022-07-14 08:53:42 -07006947void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state, VsyncId vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08006948 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08006949 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08006950 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
6951 return;
arthurhungdba591c2021-02-08 17:28:49 +08006952 }
6953
6954 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08006955 bool addToRoot = state.addToRoot;
6956 if (state.initialParent != nullptr) {
6957 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08006958 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08006959 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07006960 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08006961 }
arthurhungdba591c2021-02-08 17:28:49 +08006962 }
6963
Garfield Tand712ad32021-10-27 13:44:22 -07006964 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07006965 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08006966 mCurrentState.layersSortedByZ.add(layer);
6967 } else if (parent == nullptr) {
6968 layer->onRemovedFromCurrentState();
6969 } else if (parent->isRemovedFromCurrentState()) {
6970 parent->addChild(layer);
6971 layer->onRemovedFromCurrentState();
6972 } else {
6973 parent->addChild(layer);
6974 }
6975
Ady Abraham1273ac12021-08-26 17:31:53 -07006976 layer->updateTransformHint(mActiveDisplayTransformHint);
Vishnu Nair286f4f92022-06-08 16:37:39 -07006977 if (mTransactionTracing) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -07006978 mTransactionTracing->onLayerAddedToDrawingState(layer->getSequence(), vsyncId.value);
Vishnu Nair286f4f92022-06-08 16:37:39 -07006979 }
Arthur Hung23e07502021-10-15 11:58:19 +00006980 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08006981}
Ady Abraham562c2712021-05-07 15:10:42 -07006982
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006983void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07006984 if (!mLumaSampling || !mRegionSamplingThread) {
6985 return;
6986 }
6987
Dominik Laskowski756b7892021-08-04 12:53:59 -07006988 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07006989}
6990
Ady Abrahamed3290f2021-05-17 15:12:14 -07006991void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
6992 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
6993 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
6994}
6995
6996void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
6997 ATRACE_CALL();
6998
Ady Abrahamdb036a82021-07-16 14:18:34 -07006999 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7000 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7001 }
7002
Ady Abrahamed3290f2021-05-17 15:12:14 -07007003 if (!activeDisplay) {
7004 ALOGE("%s: activeDisplay is null", __func__);
7005 return;
7006 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007007 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007008 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007009 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007010 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007011 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007012 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007013 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007014
7015 // Update the kernel timer for the current active display, since the policy
7016 // for this display might have changed when it was not the active display.
7017 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007018}
7019
chaviw60c9d3e2021-06-04 12:52:17 -05007020status_t SurfaceFlinger::addWindowInfosListener(
7021 const sp<IWindowInfosListener>& windowInfosListener) const {
7022 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7023 return NO_ERROR;
7024}
7025
7026status_t SurfaceFlinger::removeWindowInfosListener(
7027 const sp<IWindowInfosListener>& windowInfosListener) const {
7028 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7029 return NO_ERROR;
7030}
7031
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007032std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7033 const BufferData& bufferData, const char* layerName) const {
7034 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7035 bool bufferSizeExceedsLimit = false;
7036 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7037 if (cacheIdChanged && bufferData.buffer != nullptr) {
7038 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7039 bufferData.buffer->getHeight());
7040 if (!bufferSizeExceedsLimit) {
7041 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7042 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7043 }
7044 } else if (cacheIdChanged) {
7045 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7046 } else if (bufferData.buffer != nullptr) {
7047 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7048 bufferData.buffer->getHeight());
7049 if (!bufferSizeExceedsLimit) {
7050 buffer = std::make_shared<
7051 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7052 renderengine::impl::ExternalTexture::
7053 Usage::READABLE);
7054 }
7055 }
7056 ALOGE_IF(bufferSizeExceedsLimit,
7057 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7058 "limit.",
7059 layerName);
7060 return buffer;
7061}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007062
Dominik Laskowski08fbd852022-07-14 08:53:42 -07007063bool SurfaceFlinger::commitMirrorDisplays(VsyncId vsyncId) {
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00007064 std::vector<MirrorDisplayState> mirrorDisplays;
7065 {
7066 std::scoped_lock<std::mutex> lock(mMirrorDisplayLock);
7067 mirrorDisplays = std::move(mMirrorDisplays);
7068 mMirrorDisplays.clear();
7069 if (mirrorDisplays.size() == 0) {
7070 return false;
7071 }
7072 }
7073
7074 sp<IBinder> unused;
7075 for (const auto& mirrorDisplay : mirrorDisplays) {
7076 // Set mirror layer's default layer stack to -1 so it doesn't end up rendered on a display
7077 // accidentally.
7078 sp<Layer> rootMirrorLayer = Layer::fromHandle(mirrorDisplay.rootHandle).promote();
7079 rootMirrorLayer->setLayerStack(ui::LayerStack::fromValue(-1));
7080 for (const auto& layer : mDrawingState.layersSortedByZ) {
7081 if (layer->getLayerStack() != mirrorDisplay.layerStack ||
7082 layer->isInternalDisplayOverlay()) {
7083 continue;
7084 }
7085
7086 LayerCreationArgs mirrorArgs(this, mirrorDisplay.client, "MirrorLayerParent",
7087 ISurfaceComposerClient::eNoColorFill,
7088 gui::LayerMetadata());
7089 sp<Layer> childMirror;
7090 createEffectLayer(mirrorArgs, &unused, &childMirror);
7091 childMirror->setClonedChild(layer->createClone());
7092 if (mTransactionTracing) {
7093 mTransactionTracing->onLayerAddedToDrawingState(childMirror->getSequence(),
Dominik Laskowski08fbd852022-07-14 08:53:42 -07007094 vsyncId.value);
Chavi Weingarten7043a7d2022-07-19 23:40:35 +00007095 }
7096 childMirror->reparent(mirrorDisplay.rootHandle);
7097 }
7098 }
7099 return true;
7100}
7101
Dominik Laskowski08fbd852022-07-14 08:53:42 -07007102bool SurfaceFlinger::commitCreatedLayers(VsyncId vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007103 std::vector<LayerCreatedState> createdLayers;
7104 {
7105 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7106 createdLayers = std::move(mCreatedLayers);
7107 mCreatedLayers.clear();
7108 if (createdLayers.size() == 0) {
7109 return false;
7110 }
7111 }
7112
7113 Mutex::Autolock _l(mStateLock);
7114 for (const auto& createdLayer : createdLayers) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07007115 handleLayerCreatedLocked(createdLayer, vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007116 }
7117 createdLayers.clear();
7118 mLayersAdded = true;
7119 return true;
7120}
Huihong Luof5029222021-12-16 14:33:46 -08007121
7122// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007123
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007124binder::Status SurfaceComposerAIDL::bootFinished() {
7125 status_t status = checkAccessPermission();
7126 if (status != OK) {
7127 return binderStatusFromStatusT(status);
7128 }
7129 mFlinger->bootFinished();
7130 return binder::Status::ok();
7131}
7132
7133binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7134 VsyncSource vsyncSource, EventRegistration eventRegistration,
7135 sp<IDisplayEventConnection>* outConnection) {
7136 sp<IDisplayEventConnection> conn =
7137 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration);
7138 if (conn == nullptr) {
7139 *outConnection = nullptr;
7140 return binderStatusFromStatusT(BAD_VALUE);
7141 } else {
7142 *outConnection = conn;
7143 return binder::Status::ok();
7144 }
7145}
7146
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007147binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07007148 const sp<Client> client = sp<Client>::make(mFlinger);
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007149 if (client->initCheck() == NO_ERROR) {
7150 *outClient = client;
7151 return binder::Status::ok();
7152 } else {
7153 *outClient = nullptr;
7154 return binderStatusFromStatusT(BAD_VALUE);
7155 }
7156}
7157
Huihong Luo07e72362022-02-14 14:26:04 -08007158binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7159 sp<IBinder>* outDisplay) {
7160 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007161 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007162 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007163 }
Huihong Luo37396db2022-02-15 10:43:00 -08007164 String8 displayName8 = String8::format("%s", displayName.c_str());
7165 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7166 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007167}
7168
7169binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7170 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007171 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007172 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007173 }
Huihong Luo37396db2022-02-15 10:43:00 -08007174 mFlinger->destroyDisplay(display);
7175 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007176}
7177
7178binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7179 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7180 std::vector<int64_t> displayIds;
7181 displayIds.reserve(physicalDisplayIds.size());
7182 for (auto item : physicalDisplayIds) {
7183 displayIds.push_back(static_cast<int64_t>(item.value));
7184 }
7185 *outDisplayIds = displayIds;
7186 return binder::Status::ok();
7187}
7188
Huihong Luo07e72362022-02-14 14:26:04 -08007189binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7190 sp<IBinder>* outDisplay) {
7191 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7192 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7193 return binder::Status::ok();
7194}
7195
Huihong Luo37396db2022-02-15 10:43:00 -08007196binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7197 status_t status = checkAccessPermission();
7198 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007199 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007200 }
7201 mFlinger->setPowerMode(display, mode);
7202 return binder::Status::ok();
7203}
7204
Huihong Luo0a81aa32022-02-22 16:02:36 -08007205binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7206 std::vector<FrameEvent>* outSupported) {
7207 status_t status;
7208 if (!outSupported) {
7209 status = UNEXPECTED_NULL;
7210 } else {
7211 outSupported->clear();
7212 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7213 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007214 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007215}
7216
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007217binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7218 gui::DisplayStatInfo* outStatInfo) {
7219 DisplayStatInfo statInfo;
7220 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7221 if (status == NO_ERROR) {
7222 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7223 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7224 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007225 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007226}
7227
7228binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7229 gui::DisplayState* outState) {
7230 ui::DisplayState state;
7231 status_t status = mFlinger->getDisplayState(display, &state);
7232 if (status == NO_ERROR) {
7233 outState->layerStack = state.layerStack.id;
7234 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7235 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7236 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7237 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007238 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007239}
7240
Huihong Luoa79ddf42022-02-17 00:01:38 -08007241binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7242 gui::StaticDisplayInfo* outInfo) {
7243 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7244 ui::StaticDisplayInfo info;
7245 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7246 if (status == NO_ERROR) {
7247 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7248 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7249 outInfo->density = info.density;
7250 outInfo->secure = info.secure;
7251 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7252
7253 gui::DeviceProductInfo dinfo;
7254 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7255 dinfo.name = std::move(dpi->name);
7256 dinfo.manufacturerPnpId =
7257 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7258 dinfo.productId = dpi->productId;
Kriti Dang1de958d2022-05-30 15:26:58 +02007259 dinfo.relativeAddress =
7260 std::vector<uint8_t>(dpi->relativeAddress.begin(), dpi->relativeAddress.end());
Huihong Luoa79ddf42022-02-17 00:01:38 -08007261 if (const auto* model =
7262 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7263 gui::DeviceProductInfo::ModelYear modelYear;
7264 modelYear.year = model->year;
7265 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7266 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7267 &dpi->manufactureOrModelDate)) {
7268 gui::DeviceProductInfo::ManufactureYear date;
7269 date.modelYear.year = manufacture->year;
7270 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7271 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7272 &dpi->manufactureOrModelDate)) {
7273 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7274 date.manufactureYear.modelYear.year = manufacture->year;
7275 date.week = manufacture->week;
7276 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7277 }
7278
7279 outInfo->deviceProductInfo = dinfo;
7280 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007281 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007282}
7283
Huihong Luo38603fd2022-02-21 14:32:54 -08007284binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7285 gui::DynamicDisplayInfo* outInfo) {
7286 ui::DynamicDisplayInfo info;
7287 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7288 if (status == NO_ERROR) {
7289 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7290 outInfo->supportedDisplayModes.clear();
7291 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7292 for (const auto& mode : info.supportedDisplayModes) {
7293 gui::DisplayMode outMode;
7294 outMode.id = mode.id;
7295 outMode.resolution.width = mode.resolution.width;
7296 outMode.resolution.height = mode.resolution.height;
7297 outMode.xDpi = mode.xDpi;
7298 outMode.yDpi = mode.yDpi;
7299 outMode.refreshRate = mode.refreshRate;
7300 outMode.appVsyncOffset = mode.appVsyncOffset;
7301 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7302 outMode.presentationDeadline = mode.presentationDeadline;
7303 outMode.group = mode.group;
7304 outInfo->supportedDisplayModes.push_back(outMode);
7305 }
7306
7307 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7308
7309 outInfo->supportedColorModes.clear();
7310 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7311 for (const auto& cmode : info.supportedColorModes) {
7312 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7313 }
7314
7315 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7316
7317 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7318 hdrCapabilities.supportedHdrTypes.clear();
7319 hdrCapabilities.supportedHdrTypes.reserve(
7320 info.hdrCapabilities.getSupportedHdrTypes().size());
7321 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7322 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7323 }
7324 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7325 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7326 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7327
7328 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7329 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7330 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7331 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007332 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007333}
7334
Huihong Luoca3d9a42022-02-22 11:07:34 -08007335binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7336 gui::DisplayPrimaries* outPrimaries) {
7337 ui::DisplayPrimaries primaries;
7338 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7339 if (status == NO_ERROR) {
7340 outPrimaries->red.X = primaries.red.X;
7341 outPrimaries->red.Y = primaries.red.Y;
7342 outPrimaries->red.Z = primaries.red.Z;
7343
7344 outPrimaries->green.X = primaries.green.X;
7345 outPrimaries->green.Y = primaries.green.Y;
7346 outPrimaries->green.Z = primaries.green.Z;
7347
7348 outPrimaries->blue.X = primaries.blue.X;
7349 outPrimaries->blue.Y = primaries.blue.Y;
7350 outPrimaries->blue.Z = primaries.blue.Z;
7351
7352 outPrimaries->white.X = primaries.white.X;
7353 outPrimaries->white.Y = primaries.white.Y;
7354 outPrimaries->white.Z = primaries.white.Z;
7355 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007356 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007357}
7358
7359binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7360 status_t status = checkAccessPermission();
7361 if (status == OK) {
7362 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7363 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007364 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007365}
7366
7367binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7368 int displayModeId) {
7369 status_t status = checkAccessPermission();
7370 if (status == OK) {
7371 status = mFlinger->setBootDisplayMode(display,
7372 static_cast<ui::DisplayModeId>(displayModeId));
7373 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007374 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007375}
7376
Huihong Luo37396db2022-02-15 10:43:00 -08007377binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7378 status_t status = checkAccessPermission();
7379 if (status == OK) {
7380 status = mFlinger->clearBootDisplayMode(display);
7381 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007382 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007383}
7384
7385binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7386 status_t status = checkAccessPermission();
7387 if (status == OK) {
7388 status = mFlinger->getBootDisplayModeSupport(outMode);
7389 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007390 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007391}
7392
7393binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7394 status_t status = checkAccessPermission();
7395 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007396 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007397 }
7398 mFlinger->setAutoLowLatencyMode(display, on);
7399 return binder::Status::ok();
7400}
7401
7402binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7403 status_t status = checkAccessPermission();
7404 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007405 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007406 }
7407 mFlinger->setGameContentType(display, on);
7408 return binder::Status::ok();
7409}
7410
Huihong Luof5029222021-12-16 14:33:46 -08007411binder::Status SurfaceComposerAIDL::captureDisplay(
7412 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7413 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007414 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007415}
7416
7417binder::Status SurfaceComposerAIDL::captureDisplayById(
7418 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7419 status_t status;
7420 IPCThreadState* ipc = IPCThreadState::self();
7421 const int uid = ipc->getCallingUid();
7422 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7423 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7424 status = mFlinger->captureDisplay(*id, captureListener);
7425 } else {
7426 status = PERMISSION_DENIED;
7427 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007428 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007429}
7430
7431binder::Status SurfaceComposerAIDL::captureLayers(
7432 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7433 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007434 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007435}
7436
Huihong Luo05539a12022-02-23 10:29:40 -08007437binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7438 const std::vector<int32_t>& hdrTypes) {
7439 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7440 // permission dynamically. Don't use the permission cache for this check.
7441 status_t status = checkAccessPermission(false);
7442 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007443 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007444 }
7445
7446 std::vector<ui::Hdr> hdrTypesVector;
7447 for (int32_t i : hdrTypes) {
7448 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7449 }
7450 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007451 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007452}
7453
7454binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7455 status_t status;
7456 const int uid = IPCThreadState::self()->getCallingUid();
7457 if (uid != AID_SYSTEM) {
7458 status = PERMISSION_DENIED;
7459 } else {
7460 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7461 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007462 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007463}
7464
7465binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7466 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007467 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007468 }
7469
7470 status_t status = checkAccessPermission();
7471 if (status == OK) {
7472 status = mFlinger->enableVSyncInjections(enable);
7473 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007474 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007475}
7476
7477binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7478 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007479 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007480 }
7481
7482 status_t status = checkAccessPermission();
7483 if (status == OK) {
7484 status = mFlinger->injectVSync(when);
7485 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007486 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007487}
7488
7489binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7490 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007491 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007492 }
7493
7494 IPCThreadState* ipc = IPCThreadState::self();
7495 const int pid = ipc->getCallingPid();
7496 const int uid = ipc->getCallingUid();
7497 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7498 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007499 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007500 }
7501 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007502 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007503}
7504
7505binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7506 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007507 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007508}
7509
7510binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7511 ui::Dataspace dataspace;
7512 ui::PixelFormat pixelFormat;
7513 ui::Dataspace wideColorGamutDataspace;
7514 ui::PixelFormat wideColorGamutPixelFormat;
7515 status_t status =
7516 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7517 &wideColorGamutPixelFormat);
7518 if (status == NO_ERROR) {
7519 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7520 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7521 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7522 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7523 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007524 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007525}
7526
7527binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7528 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7529 status_t status = checkAccessPermission();
7530 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007531 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007532 }
7533
7534 ui::PixelFormat format;
7535 ui::Dataspace dataspace;
7536 uint8_t componentMask;
7537 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7538 &componentMask);
7539 if (status == NO_ERROR) {
7540 outAttrs->format = static_cast<int32_t>(format);
7541 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7542 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7543 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007544 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007545}
7546
7547binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7548 bool enable,
7549 int8_t componentMask,
7550 int64_t maxFrames) {
7551 status_t status = checkAccessPermission();
7552 if (status == OK) {
7553 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7554 static_cast<uint8_t>(componentMask),
7555 static_cast<uint64_t>(maxFrames));
7556 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007557 return binderStatusFromStatusT(status);
7558}
7559
7560binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7561 int64_t maxFrames, int64_t timestamp,
7562 gui::DisplayedFrameStats* outStats) {
7563 if (!outStats) {
7564 return binderStatusFromStatusT(BAD_VALUE);
7565 }
7566
7567 status_t status = checkAccessPermission();
7568 if (status != OK) {
7569 return binderStatusFromStatusT(status);
7570 }
7571
7572 DisplayedFrameStats stats;
7573 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7574 static_cast<uint64_t>(timestamp), &stats);
7575 if (status == NO_ERROR) {
7576 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7577 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7578 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7579 for (const auto& s : stats.component_0_sample) {
7580 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7581 }
7582 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7583 for (const auto& s : stats.component_1_sample) {
7584 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7585 }
7586 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7587 for (const auto& s : stats.component_2_sample) {
7588 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7589 }
7590 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7591 for (const auto& s : stats.component_3_sample) {
7592 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7593 }
7594 }
7595 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007596}
7597
7598binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7599 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007600 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007601}
7602
Huihong Luo37396db2022-02-15 10:43:00 -08007603binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7604 bool* outIsWideColorDisplay) {
7605 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007606 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007607}
7608
Huihong Luo02186fb2022-02-23 14:21:54 -08007609binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7610 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7611 const sp<gui::IRegionSamplingListener>& listener) {
7612 status_t status = checkReadFrameBufferPermission();
7613 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007614 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007615 }
7616 android::Rect rect;
7617 rect.left = samplingArea.left;
7618 rect.top = samplingArea.top;
7619 rect.right = samplingArea.right;
7620 rect.bottom = samplingArea.bottom;
7621 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007622 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007623}
7624
7625binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7626 const sp<gui::IRegionSamplingListener>& listener) {
7627 status_t status = checkReadFrameBufferPermission();
7628 if (status == OK) {
7629 status = mFlinger->removeRegionSamplingListener(listener);
7630 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007631 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007632}
7633
7634binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7635 const sp<gui::IFpsListener>& listener) {
7636 status_t status = checkReadFrameBufferPermission();
7637 if (status == OK) {
7638 status = mFlinger->addFpsListener(taskId, listener);
7639 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007640 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007641}
7642
7643binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7644 status_t status = checkReadFrameBufferPermission();
7645 if (status == OK) {
7646 status = mFlinger->removeFpsListener(listener);
7647 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007648 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007649}
7650
7651binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7652 const sp<gui::ITunnelModeEnabledListener>& listener) {
7653 status_t status = checkAccessPermission();
7654 if (status == OK) {
7655 status = mFlinger->addTunnelModeEnabledListener(listener);
7656 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007657 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007658}
7659
7660binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7661 const sp<gui::ITunnelModeEnabledListener>& listener) {
7662 status_t status = checkAccessPermission();
7663 if (status == OK) {
7664 status = mFlinger->removeTunnelModeEnabledListener(listener);
7665 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007666 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007667}
7668
7669binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7670 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7671 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7672 float appRequestRefreshRateMax) {
7673 status_t status = checkAccessPermission();
7674 if (status == OK) {
7675 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7676 static_cast<ui::DisplayModeId>(defaultMode),
7677 allowGroupSwitching, primaryRefreshRateMin,
7678 primaryRefreshRateMax,
7679 appRequestRefreshRateMin,
7680 appRequestRefreshRateMax);
7681 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007682 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007683}
7684
7685binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7686 gui::DisplayModeSpecs* outSpecs) {
7687 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007688 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007689 }
7690
7691 status_t status = checkAccessPermission();
7692 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007693 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007694 }
7695
7696 ui::DisplayModeId displayModeId;
7697 bool allowGroupSwitching;
7698 float primaryRefreshRateMin;
7699 float primaryRefreshRateMax;
7700 float appRequestRefreshRateMin;
7701 float appRequestRefreshRateMax;
7702 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7703 &allowGroupSwitching, &primaryRefreshRateMin,
7704 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7705 &appRequestRefreshRateMax);
7706 if (status == NO_ERROR) {
7707 outSpecs->defaultMode = displayModeId;
7708 outSpecs->allowGroupSwitching = allowGroupSwitching;
7709 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7710 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7711 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7712 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7713 }
7714
Huihong Luo3bdef862022-03-03 11:57:19 -08007715 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007716}
7717
Huihong Luo37396db2022-02-15 10:43:00 -08007718binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7719 bool* outSupport) {
7720 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007721 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007722}
7723
7724binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7725 const gui::DisplayBrightness& brightness) {
7726 status_t status = checkControlDisplayBrightnessPermission();
7727 if (status == OK) {
7728 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7729 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007730 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007731}
7732
7733binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7734 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7735 status_t status = checkControlDisplayBrightnessPermission();
7736 if (status == OK) {
7737 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7738 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007739 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007740}
7741
7742binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7743 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7744 status_t status = checkControlDisplayBrightnessPermission();
7745 if (status == OK) {
7746 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7747 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007748 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007749}
7750
7751binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7752 status_t status = checkAccessPermission();
7753 if (status == OK) {
7754 status = mFlinger->notifyPowerBoost(boostId);
7755 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007756 return binderStatusFromStatusT(status);
7757}
7758
7759binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7760 const gui::Color& spotColor,
7761 float lightPosY, float lightPosZ,
7762 float lightRadius) {
7763 status_t status = checkAccessPermission();
7764 if (status != OK) {
7765 return binderStatusFromStatusT(status);
7766 }
7767
7768 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7769 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7770 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7771 lightPosZ, lightRadius);
7772 return binderStatusFromStatusT(status);
7773}
7774
7775binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7776 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7777 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7778 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7779 if (status != NO_ERROR) {
7780 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7781 return binderStatusFromStatusT(status);
7782 }
7783
7784 if (!support || !support.has_value()) {
7785 outSupport->reset();
7786 } else {
7787 outSupport->emplace();
7788 outSupport->value().format = static_cast<int32_t>(support->format);
7789 outSupport->value().alphaInterpretation =
7790 static_cast<int32_t>(support->alphaInterpretation);
7791 }
7792
7793 return binder::Status::ok();
7794}
7795
7796binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
7797 status_t status;
7798 const int c_uid = IPCThreadState::self()->getCallingUid();
7799 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
7800 status = mFlinger->setOverrideFrameRate(uid, frameRate);
7801 } else {
7802 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
7803 status = PERMISSION_DENIED;
7804 }
7805 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007806}
7807
Huihong Luo02186fb2022-02-23 14:21:54 -08007808binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
7809 const sp<gui::ITransactionTraceListener>& listener) {
7810 status_t status;
7811 IPCThreadState* ipc = IPCThreadState::self();
7812 const int uid = ipc->getCallingUid();
7813 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7814 status = mFlinger->addTransactionTraceListener(listener);
7815 } else {
7816 status = PERMISSION_DENIED;
7817 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007818 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007819}
7820
7821binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
7822 *outPriority = mFlinger->getGpuContextPriority();
7823 return binder::Status::ok();
7824}
7825
7826binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
7827 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007828 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007829}
7830
7831binder::Status SurfaceComposerAIDL::addWindowInfosListener(
7832 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7833 status_t status;
7834 const int uid = IPCThreadState::self()->getCallingUid();
7835 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7836 status = mFlinger->addWindowInfosListener(windowInfosListener);
7837 } else {
7838 status = PERMISSION_DENIED;
7839 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007840 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007841}
7842
7843binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
7844 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7845 status_t status;
7846 const int uid = IPCThreadState::self()->getCallingUid();
7847 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7848 status = mFlinger->removeWindowInfosListener(windowInfosListener);
7849 } else {
7850 status = PERMISSION_DENIED;
7851 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007852 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007853}
7854
Huihong Luo07e72362022-02-14 14:26:04 -08007855status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
7856 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
7857 IPCThreadState* ipc = IPCThreadState::self();
7858 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
7859 ipc->getCallingUid());
7860 return PERMISSION_DENIED;
7861 }
7862 return OK;
7863}
7864
Huihong Luo37396db2022-02-15 10:43:00 -08007865status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
7866 IPCThreadState* ipc = IPCThreadState::self();
7867 const int pid = ipc->getCallingPid();
7868 const int uid = ipc->getCallingUid();
7869 if ((uid != AID_GRAPHICS) &&
7870 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
7871 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
7872 return PERMISSION_DENIED;
7873 }
7874 return OK;
7875}
7876
Huihong Luo02186fb2022-02-23 14:21:54 -08007877status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
7878 IPCThreadState* ipc = IPCThreadState::self();
7879 const int pid = ipc->getCallingPid();
7880 const int uid = ipc->getCallingUid();
7881 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
7882 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
7883 return PERMISSION_DENIED;
7884 }
7885 return OK;
7886}
7887
Dominik Laskowski9dab3432019-03-27 13:21:10 -07007888} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07007889
Mathias Agopian3f844832013-08-07 21:24:32 -07007890#if defined(__gl_h_)
7891#error "don't include gl/gl.h in this file"
7892#endif
7893
7894#if defined(__gl2_h_)
7895#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08007896#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08007897
7898// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01007899#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"