blob: 450c6c0cd74186fdeaac038c8e88c5d1e03450e7 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020#pragma clang diagnostic ignored "-Wextra"
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080021
Alec Mourie7d1d4a2019-02-05 01:13:46 +000022//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080023#define ATRACE_TAG ATRACE_TAG_GRAPHICS
24
Alec Mouri5f487d42020-02-06 09:26:19 -080025#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080026
Dominik Laskowski298b08e2022-02-15 13:45:02 -080027#include <android-base/parseint.h>
Ana Krulecb9afd792020-06-11 13:16:15 -070028#include <android-base/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080029#include <android-base/stringprintf.h>
30#include <android-base/strings.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080031#include <android/configuration.h>
Huihong Luo6fac5232021-11-22 16:05:23 -080032#include <android/gui/IDisplayEventConnection.h>
Huihong Luoa79ddf42022-02-17 00:01:38 -080033#include <android/gui/StaticDisplayInfo.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080034#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
35#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
36#include <android/hardware/configstore/1.1/types.h>
Lais Andrade3a6e47d2020-04-02 11:20:16 +010037#include <android/hardware/power/Boost.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080038#include <android/native_window.h>
Chris Ye0783e992020-06-02 21:34:49 -070039#include <android/os/IInputFlinger.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070040#include <binder/IPCThreadState.h>
41#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070042#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070043#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080044#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070045#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070046#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070047#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080048#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080049#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070050#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070051#include <compositionengine/impl/OutputCompositionState.h>
John Reckdb1a16b2021-07-09 13:05:52 -040052#include <compositionengine/impl/OutputLayerCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080053#include <configstore/Utils.h>
54#include <cutils/compiler.h>
55#include <cutils/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080056#include <ftl/fake_guard.h>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080057#include <ftl/future.h>
Dominik Laskowski9f410f02022-01-08 16:22:46 -080058#include <ftl/small_map.h>
Huihong Luo3bdef862022-03-03 11:57:19 -080059#include <gui/AidlStatusUtil.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070060#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070061#include <gui/DebugEGLImageTracker.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080062#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080063#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080064#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080065#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080066#include <gui/Surface.h>
rnlee60f46b52021-05-21 15:14:07 -070067#include <gui/TraceUtils.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000068#include <hidl/ServiceManagement.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080069#include <layerproto/LayerProtoParser.h>
70#include <log/log.h>
71#include <private/android_filesystem_config.h>
72#include <private/gui/SyncFeatures.h>
Wei Wang976a6452021-06-11 15:26:00 -070073#include <processgroup/processgroup.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070074#include <renderengine/RenderEngine.h>
Vishnu Nairdbbe3852022-01-12 20:22:11 -080075#include <renderengine/impl/ExternalTexture.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080076#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <ui/ColorSpace.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070078#include <ui/DataspaceUtils.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070079#include <ui/DebugUtils.h>
Marin Shalamanov045b7002021-01-07 16:56:24 +010080#include <ui/DisplayId.h>
Marin Shalamanova7fe3042021-01-29 21:02:08 +010081#include <ui/DisplayMode.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070082#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080083#include <ui/DisplayState.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010084#include <ui/DynamicDisplayInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070085#include <ui/GraphicBufferAllocator.h>
86#include <ui/PixelFormat.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010087#include <ui/StaticDisplayInfo.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070089#include <utils/String16.h>
90#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070091#include <utils/Timers.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070092#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093
Alec Mouri5f487d42020-02-06 09:26:19 -080094#include <algorithm>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080095#include <cerrno>
Alec Mouri5f487d42020-02-06 09:26:19 -080096#include <cinttypes>
97#include <cmath>
98#include <cstdint>
99#include <functional>
Xiang Wang839fe5b2022-04-04 17:39:38 +0000100#include <memory>
Alec Mouri5f487d42020-02-06 09:26:19 -0800101#include <mutex>
102#include <optional>
Michael Wright44753b12020-07-08 13:48:11 +0100103#include <type_traits>
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105
Alec Mouriff793872022-01-13 17:45:06 -0800106#include <ui/DisplayIdentification.h>
Vishnu Nair03ccbd62021-12-01 17:21:16 -0800107#include "BackgroundExecutor.h"
Robert Carr578038f2018-03-09 12:25:24 -0800108#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -0700109#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -0700110#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200111#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200112#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800113#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800114#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700115#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700116#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700117#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100118#include "DisplayHardware/Hal.h"
Xiang Wang839fe5b2022-04-04 17:39:38 +0000119#include "DisplayHardware/PowerAdvisor.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700120#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200121#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800122#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700123#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700124#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800125#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700126#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700127#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400128#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800129#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500130#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200131#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800132#include "LayerVector.h"
133#include "MonitoredProducer.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800134#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800135#include "NativeWindowSurface.h"
136#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700137#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700138#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700139#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700140#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700141#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700142#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700143#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800144#include "StartPropertySetThread.h"
145#include "SurfaceFlingerProperties.h"
146#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800147#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200148#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500149#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800150
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500151#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500152#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
Alec Mourifcedb9c2022-04-11 20:02:17 +0000153#include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500154
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700155#undef NO_THREAD_SAFETY_ANALYSIS
156#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800157 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500158
Tianhao Yao67dd7122022-02-22 17:48:33 +0000159// To enable layer borders in the system, change the below flag to true.
160#undef DOES_CONTAIN_BORDER
161#define DOES_CONTAIN_BORDER false
162
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700164
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700165using namespace std::string_literals;
166
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800167using namespace hardware::configstore;
168using namespace hardware::configstore::V1_0;
169using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800170
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800171using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
172using aidl::android::hardware::graphics::composer3::Capability;
173using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800174using CompositionStrategyPredictionState = android::compositionengine::impl::
175 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800176
Yiwei Zhang5434a782018-12-05 18:06:32 -0800177using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700178using gui::DisplayInfo;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800179using gui::GameMode;
Huihong Luo6fac5232021-11-22 16:05:23 -0800180using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500181using gui::IWindowInfosListener;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800182using gui::LayerMetadata;
chaviw98318de2021-05-19 16:45:23 -0500183using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800184using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700185using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700186using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800187using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700188using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900189
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800190using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
191
Peiyong Line9d809e2020-04-14 13:10:48 -0700192namespace hal = android::hardware::graphics::composer::hal;
193
Steven Thomasb02664d2017-07-26 18:48:28 -0700194namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700195
196#pragma clang diagnostic push
197#pragma clang diagnostic error "-Wswitch-enum"
198
199bool isWideColorMode(const ColorMode colorMode) {
200 switch (colorMode) {
201 case ColorMode::DISPLAY_P3:
202 case ColorMode::ADOBE_RGB:
203 case ColorMode::DCI_P3:
204 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700205 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700206 case ColorMode::BT2100_PQ:
207 case ColorMode::BT2100_HLG:
208 return true;
209 case ColorMode::NATIVE:
210 case ColorMode::STANDARD_BT601_625:
211 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
212 case ColorMode::STANDARD_BT601_525:
213 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
214 case ColorMode::STANDARD_BT709:
215 case ColorMode::SRGB:
216 return false;
217 }
218 return false;
219}
220
221#pragma clang diagnostic pop
222
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100223// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700224constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800225
226float getDensityFromProperty(const char* property, bool required) {
227 char value[PROPERTY_VALUE_MAX];
228 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
229 if (!density && required) {
230 ALOGE("%s must be defined as a build property", property);
231 return FALLBACK_DENSITY;
232 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700233 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800234}
235
Peiyong Lin9d846a52018-11-05 13:18:20 -0800236// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
237bool validateCompositionDataspace(Dataspace dataspace) {
238 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
239}
240
ramindani32cf0602022-03-02 02:30:29 +0000241std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700242 const auto displayIdleTimerMsKey = [displayId] {
243 std::stringstream ss;
244 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
245 return ss.str();
246 }();
247
ramindani32cf0602022-03-02 02:30:29 +0000248 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
249 if (displayIdleTimerMs > 0) {
250 return std::chrono::milliseconds(displayIdleTimerMs);
251 }
252
253 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
254 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
255 return std::chrono::milliseconds(millis);
256}
257
258bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700259 const auto displaySupportKernelIdleTimerKey = [displayId] {
260 std::stringstream ss;
261 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
262 return ss.str();
263 }();
264
Ady Abraham6d885932021-09-03 18:05:48 -0700265 const auto displaySupportKernelIdleTimer =
266 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000267 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700268}
269
Steven Thomasb02664d2017-07-26 18:48:28 -0700270} // namespace anonymous
271
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272// ---------------------------------------------------------------------------
273
Mathias Agopian99b49842011-06-27 16:05:52 -0700274const String16 sHardwareTest("android.permission.HARDWARE_TEST");
275const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800276const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700277const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400278const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700279const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500280const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000281const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500282
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800283const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700284
285// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700286int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700287bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800288bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800289int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100290uint32_t SurfaceFlinger::maxGraphicsWidth;
291uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600292bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700293bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700294Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
295ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
296Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
297ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000298LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700299
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800300std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
301 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800302 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700303 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800304 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700305 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800306 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700307 return std::string("Enhanced");
308 default:
309 return std::string("Unknown ") +
310 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800311 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800312}
313
Hongwei Wang46213ea2020-12-04 17:17:31 -0800314bool callingThreadHasRotateSurfaceFlingerAccess() {
315 IPCThreadState* ipc = IPCThreadState::self();
316 const int pid = ipc->getCallingPid();
317 const int uid = ipc->getCallingUid();
318 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
319 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
320}
321
Leon Scroggins9a20f722021-12-28 14:43:12 +0000322bool callingThreadHasInternalSystemWindowAccess() {
323 IPCThreadState* ipc = IPCThreadState::self();
324 const int pid = ipc->getCallingPid();
325 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500326 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
327 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000328}
329
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700330SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
331 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800332 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000333 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700334 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800335 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800336 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700337 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700338 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700339 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800340 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700341 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000342 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Dominik Laskowski91f635e2022-01-08 05:46:09 -0800343 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make(*this)) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700344 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700345}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800346
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700347SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800348 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800349
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900350 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900352 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700353
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900354 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700355
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900356 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800357
Brian Lindahla13f2d52020-03-05 11:54:17 +0100358 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
359 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
360
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900361 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900362 mDefaultCompositionDataspace =
363 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700364 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
365 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900366 defaultCompositionDataspace = mDefaultCompositionDataspace;
367 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
368 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
369 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
370 wideColorGamutCompositionPixelFormat =
371 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700372
Yichi Chenda901bf2019-06-28 14:58:27 +0800373 mColorSpaceAgnosticDataspace =
374 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
375
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700376 mLayerCachingEnabled = [] {
377 const bool enable =
378 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
379 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
380 }();
381
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900382 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800383
Sundong Ahn85131bd2019-02-18 15:51:53 +0900384 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800385
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800386 // debugging stuff...
387 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700388
Mathias Agopianb4b17302013-03-20 18:36:41 -0700389 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700390 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700391
Alec Mouri5f487d42020-02-06 09:26:19 -0800392 property_get("ro.build.type", value, "user");
393 mIsUserBuild = strcmp(value, "user") == 0;
394
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700395 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000396
397 // DDMS debugging deprecated (b/120782499)
398 property_get("debug.sf.ddms", value, "0");
399 int debugDdms = atoi(value);
400 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700401
Ady Abrahamadb9a992019-09-19 21:21:55 +0000402 property_get("debug.sf.enable_gl_backpressure", value, "0");
403 mPropagateBackpressureClientComposition = atoi(value);
404 ALOGI_IF(mPropagateBackpressureClientComposition,
405 "Enabling backpressure propagation for Client Composition");
406
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800407 property_get("ro.surface_flinger.supports_background_blur", value, "0");
408 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700409 mSupportsBlur = supportsBlurs;
410 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800411 property_get("ro.sf.blurs_are_expensive", value, "0");
412 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800413
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700414 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700415 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
416 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800417 mGraphicBufferProducerListSizeLogThreshold =
418 std::max(static_cast<int>(0.95 *
419 static_cast<double>(mMaxGraphicBufferProducerListSize)),
420 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700421
Dan Stozaec460082018-12-17 15:35:09 -0800422 property_get("debug.sf.luma_sampling", value, "1");
423 mLumaSampling = atoi(value);
424
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800425 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800426 mDisableClientCompositionCache = atoi(value);
427
Vishnu Nair3539d812022-02-26 09:20:17 -0800428 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800429 mPredictCompositionStrategy = atoi(value);
430
Alec Mouridda07d92022-04-25 22:39:25 +0000431 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
432 mTreat170mAsSrgb = atoi(value);
433
Romain Guy11d63f42017-07-20 12:47:14 -0700434 // We should be reading 'persist.sys.sf.color_saturation' here
435 // but since /data may be encrypted, we need to wait until after vold
436 // comes online to attempt to read the property. The property is
437 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800438
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700439 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800440 // Without the override SurfaceFlinger cannot connect to HIDL
441 // services that are not listed in the manifests. Considered
442 // deriving the setting from the set service name, but it
443 // would be brittle if the name that's not 'default' is used
444 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700445 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000446 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800447 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800448
Ady Abraham29d0da32020-07-16 18:39:33 -0700449 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400450
Dominik Laskowski46471e62022-01-14 15:34:03 -0800451 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
452 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800453 }
John Reck49d9ad32022-02-23 19:03:31 -0500454
455 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
Matt Buckley50c44062022-01-17 20:48:10 +0000456
457 // Power hint session mode, representing which hint(s) to send: early, late, or both)
458 mPowerHintSessionMode =
459 {.late = base::GetBoolProperty("debug.sf.send_late_power_session_hint"s, true),
460 .early = base::GetBoolProperty("debug.sf.send_early_power_session_hint"s, true)};
ramindani4d48f902021-09-20 21:07:45 +0000461}
462
463LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
464 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
465 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000466 }
Ady Abraham9dada822022-02-03 10:26:59 -0800467
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000468 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800469 return LatchUnsignaledConfig::AutoSingleLayer;
470 }
471
472 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800473}
474
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700475SurfaceFlinger::~SurfaceFlinger() = default;
476
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700477void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800478 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700479 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800480
Dominik Laskowski756b7892021-08-04 12:53:59 -0700481 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000482 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
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);
510 flinger->mCurrentState.displays.removeItem(this);
511 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
519 sp<BBinder> token = new DisplayToken(this);
520
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
Vishnu Nair8c8db542021-09-17 19:51:45 -0700611status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
612 Mutex::Autolock lock(mStateLock);
Dominik Laskowski3c363242022-04-07 10:44:12 -0700613 *id = getPrimaryDisplayIdLocked();
Vishnu Nair8c8db542021-09-17 19:51:45 -0700614 return NO_ERROR;
615}
616
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800617sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
618 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200619 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700620}
621
Ady Abraham37965d42018-11-01 13:43:32 -0700622status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
623 if (!outGetColorManagement) {
624 return BAD_VALUE;
625 }
626 *outGetColorManagement = useColorManagement;
627 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700628}
629
Lloyd Pique441d5042018-10-18 16:49:51 -0700630HWComposer& SurfaceFlinger::getHwComposer() const {
631 return mCompositionEngine->getHwComposer();
632}
633
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700634renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
635 return mCompositionEngine->getRenderEngine();
636}
637
Lloyd Pique70d91362018-10-18 16:02:55 -0700638compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
639 return *mCompositionEngine.get();
640}
641
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100642void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700643 if (mBootFinished == true) {
644 ALOGE("Extra call to bootFinished");
645 return;
646 }
647 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700648 if (mStartPropertySetThread->join() != NO_ERROR) {
649 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800650 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700651
652 if (mRenderEnginePrimeCacheFuture.valid()) {
653 mRenderEnginePrimeCacheFuture.get();
654 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800655 const nsecs_t now = systemTime();
656 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000657 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700658
Mikael Pessa90092f42019-08-26 17:22:04 -0700659 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700660 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700661 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700662
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700663 // wait patiently for the window manager death
664 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700665 mWindowManager = defaultServiceManager()->getService(name);
666 if (mWindowManager != 0) {
667 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700668 }
669
670 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700671 // formerly we would just kill the process, but we now ask it to exit so it
672 // can choose where to stop the animation.
673 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700674
675 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
676 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
677 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700678
Denis Hsue70cc6c2020-06-17 10:17:30 +0800679 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
680
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000681 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800682 if (input == nullptr) {
683 ALOGE("Failed to link to input service");
684 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700685 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800686 }
687
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800688 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000689 mPowerAdvisor->onBootFinished();
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000690 const bool powerHintEnabled = mFlagManager.use_adpf_cpu_hint();
691 mPowerAdvisor->enablePowerHint(powerHintEnabled);
692 const bool powerHintUsed = mPowerAdvisor->usePowerHintSession();
693 ALOGD("Power hint is %s",
694 powerHintUsed ? "supported" : (powerHintEnabled ? "unsupported" : "disabled"));
695 if (powerHintUsed) {
Xiang Wang76236e12022-03-22 17:25:30 +0000696 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
697 std::vector<int32_t> tidList;
698 tidList.emplace_back(gettid());
699 if (renderEngineTid.has_value()) {
700 tidList.emplace_back(*renderEngineTid);
701 }
Xiang Wang839fe5b2022-04-04 17:39:38 +0000702 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000703 ALOGW("Cannot start power hint session");
704 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000705 }
706
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800707 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800708
Ady Abraham8a82ba62020-01-17 12:43:17 -0800709 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800710 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800711 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800712 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800713}
714
Dan Stoza436ccf32018-06-21 12:10:12 -0700715uint32_t SurfaceFlinger::getNewTexture() {
716 {
717 std::lock_guard lock(mTexturePoolMutex);
718 if (!mTexturePool.empty()) {
719 uint32_t name = mTexturePool.back();
720 mTexturePool.pop_back();
721 ATRACE_INT("TexturePoolSize", mTexturePool.size());
722 return name;
723 }
724
725 // The pool was too small, so increase it for the future
726 ++mTexturePoolSize;
727 }
728
729 // The pool was empty, so we need to get a new texture name directly using a
730 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700731 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700732 uint32_t name = 0;
733 getRenderEngine().genTextures(1, &name);
734 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700735 };
736 if (std::this_thread::get_id() == mMainThreadId) {
737 return genTextures();
738 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700739 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700740 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700741}
742
Mathias Agopian3f844832013-08-07 21:24:32 -0700743void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700744 std::lock_guard lock(mTexturePoolMutex);
745 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
746 // to actually delete this or not based on mTexturePoolSize
747 mTexturePool.push_back(texture);
748 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700749}
750
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500751static std::optional<renderengine::RenderEngine::RenderEngineType>
752chooseRenderEngineTypeViaSysProp() {
753 char prop[PROPERTY_VALUE_MAX];
754 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
755
756 if (strcmp(prop, "gles") == 0) {
757 return renderengine::RenderEngine::RenderEngineType::GLES;
758 } else if (strcmp(prop, "threaded") == 0) {
759 return renderengine::RenderEngine::RenderEngineType::THREADED;
760 } else if (strcmp(prop, "skiagl") == 0) {
761 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
762 } else if (strcmp(prop, "skiaglthreaded") == 0) {
763 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
764 } else {
765 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
766 return {};
767 }
768}
769
Wei Wangf9b05ee2017-07-19 20:59:39 -0700770// Do not call property_set on main thread which will be blocked by init
771// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700772void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700773 ALOGI( "SurfaceFlinger's main thread ready to run. "
774 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700775 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800776
Steven Thomasb02664d2017-07-26 18:48:28 -0700777 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700778 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800779 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500780 auto builder = renderengine::RenderEngineCreationArgs::Builder()
781 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
782 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
783 .setUseColorManagerment(useColorManagement)
784 .setEnableProtectedContext(enable_protected_contents(false))
785 .setPrecacheToneMapperShaderOnly(false)
786 .setSupportsBackgroundBlur(mSupportsBlur)
787 .setContextPriority(
788 useContextPriority
789 ? renderengine::RenderEngine::ContextPriority::REALTIME
790 : renderengine::RenderEngine::ContextPriority::MEDIUM);
791 if (auto type = chooseRenderEngineTypeViaSysProp()) {
792 builder.setRenderEngineType(type.value());
793 }
794 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700795 mMaxRenderTargetSize =
796 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700797
798 // Set SF main policy after initializing RenderEngine which has its own policy.
799 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
800 ALOGW("Failed to set main task profile");
801 }
802
Alec Mourie4034bb2019-11-19 12:45:54 -0800803 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700804 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800805 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000806 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800807
Ady Abraham9dada822022-02-03 10:26:59 -0800808 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
809
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800810 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
811 enableHalVirtualDisplays(true);
812 }
813
Lloyd Piqueba04e622017-12-14 17:11:26 -0800814 // Process any initial hotplug and resulting display changes.
815 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700816 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700817 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200818 const auto displayId = display->getPhysicalId();
819 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700820 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800821
Mathias Agopian92a979a2012-08-02 18:32:23 -0700822 // initialize our drawing state
823 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700824
Andy McFadden13a082e2012-08-24 10:16:42 -0700825 // set initial conditions (e.g. unblank default device)
826 initializeDisplays();
827
Xiang Wang839fe5b2022-04-04 17:39:38 +0000828 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700829
Steven Thomas137d4bc2019-07-25 16:55:14 -0700830 char primeShaderCache[PROPERTY_VALUE_MAX];
831 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
832 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700833 if (setSchedFifo(false) != NO_ERROR) {
834 ALOGW("Can't set SCHED_OTHER for primeCache");
835 }
836
837 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
838
839 if (setSchedFifo(true) != NO_ERROR) {
840 ALOGW("Can't set SCHED_OTHER for primeCache");
841 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700842 }
Dan Stoza4e637772016-07-28 13:31:51 -0700843
Ady Abrahamed3290f2021-05-17 15:12:14 -0700844 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400845
Wei Wangf9b05ee2017-07-19 20:59:39 -0700846 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700847
848 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800849 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700850 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700851
852 if (mStartPropertySetThread->Start() != NO_ERROR) {
853 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800854 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800855
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700857}
858
Romain Guy11d63f42017-07-20 12:47:14 -0700859void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700860 Mutex::Autolock _l(mStateLock);
861
Romain Guy11d63f42017-07-20 12:47:14 -0700862 char value[PROPERTY_VALUE_MAX];
863
864 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800865 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700866 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800867 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100868
869 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700870 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800871
872 property_get("persist.sys.sf.color_mode", value, "0");
873 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700874}
875
Mathias Agopiana67e4182012-06-19 17:26:12 -0700876void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800877 // Start boot animation service by setting a property mailbox
878 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700879 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800880 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700881 if (mStartPropertySetThread->join() != NO_ERROR) {
882 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800883 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700884}
885
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800886// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800887
Brian Anderson6b376712017-04-04 10:51:39 -0700888status_t SurfaceFlinger::getSupportedFrameTimestamps(
889 std::vector<FrameEvent>* outSupported) const {
890 *outSupported = {
891 FrameEvent::REQUESTED_PRESENT,
892 FrameEvent::ACQUIRE,
893 FrameEvent::LATCH,
894 FrameEvent::FIRST_REFRESH_START,
895 FrameEvent::LAST_REFRESH_START,
896 FrameEvent::GPU_COMPOSITION_DONE,
897 FrameEvent::DEQUEUE_READY,
898 FrameEvent::RELEASE,
899 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800900
901 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
902
Ady Abrahamde549d42022-01-26 19:19:17 -0800903 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700904 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
905 }
906 return NO_ERROR;
907}
908
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800909status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
910 if (!displayToken || !state) {
911 return BAD_VALUE;
912 }
913
914 Mutex::Autolock lock(mStateLock);
915
916 const auto display = getDisplayDeviceLocked(displayToken);
917 if (!display) {
918 return NAME_NOT_FOUND;
919 }
920
921 state->layerStack = display->getLayerStack();
922 state->orientation = display->getOrientation();
923
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200924 const Rect layerStackRect = display->getLayerStackSpaceRect();
925 state->layerStackSpaceRect =
926 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800927
928 return NO_ERROR;
929}
930
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100931status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
932 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800933 if (!displayToken || !info) {
934 return BAD_VALUE;
935 }
936
937 Mutex::Autolock lock(mStateLock);
938
939 const auto display = getDisplayDeviceLocked(displayToken);
940 if (!display) {
941 return NAME_NOT_FOUND;
942 }
943
Dominik Laskowski55c85402020-01-21 16:25:47 -0800944 if (const auto connectionType = display->getConnectionType())
945 info->connectionType = *connectionType;
946 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800947 return INVALID_OPERATION;
948 }
949
950 if (mEmulatedDisplayDensity) {
951 info->density = mEmulatedDisplayDensity;
952 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100953 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800954 ? mInternalDisplayDensity
955 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800956 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700957 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800958
959 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200960 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000961 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800962
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800963 return NO_ERROR;
964}
965
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100966status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
967 ui::DynamicDisplayInfo* info) {
968 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700969 return BAD_VALUE;
970 }
971
Dominik Laskowski22488f62019-03-28 09:53:04 -0700972 Mutex::Autolock lock(mStateLock);
973
Marin Shalamanov5801c942020-12-17 17:00:13 +0100974 const auto display = getDisplayDeviceLocked(displayToken);
975 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700976 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700977 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700978
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700979 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
980 if (!displayId) {
981 return INVALID_OPERATION;
982 }
983
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800984 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700985
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100986 const auto& supportedModes = display->getSupportedModes();
987 info->supportedDisplayModes.clear();
988 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800989
990 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100991 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800992 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700993
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800994 auto [width, height] = mode->getResolution();
995 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700996
ramindani06e518e2022-03-14 18:47:53 +0000997 if (const auto physicalOrientation = display->getPhysicalOrientation();
998 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800999 std::swap(width, height);
1000 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -07001001 }
1002
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001003 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -08001004
Huan Songf7eeb102022-03-28 11:02:38 -07001005 outMode.xDpi = xDpi;
1006 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001007
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001008 const nsecs_t period = mode->getVsyncPeriod();
1009 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001010
Ady Abraham8287e852020-08-12 14:44:58 -07001011 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001012 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001013 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1014 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1015 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001016
Andy McFadden91b2ca82014-06-13 14:04:23 -07001017 // This is how far in advance a buffer must be queued for
1018 // presentation at a given time. If you want a buffer to appear
1019 // on the screen at time N, you must submit the buffer before
1020 // (N - presentationDeadline).
1021 //
1022 // Normally it's one full refresh period (to give SF a chance to
1023 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001024 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001025 // composer or panel must be accounted for here.
1026 //
1027 // We add an additional 1ms to allow for processing time and
1028 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001029 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001030
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001031 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001032 }
1033
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001034 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001035 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001036 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001037
Marin Shalamanovb173f752021-02-16 19:38:36 +01001038 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001039 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001040 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001041 info->gameContentTypeSupported =
1042 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001043
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001044 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001045
1046 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001047 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1048 if (const auto modeId = display->translateModeId(*hwcId)) {
1049 info->preferredBootDisplayMode = modeId->value();
1050 }
1051 }
1052 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001053
Dan Stoza7f7da322014-05-02 15:26:25 -07001054 return NO_ERROR;
1055}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001056
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001057status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
1058 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001059 return BAD_VALUE;
1060 }
1061
Ady Abrahame90dd522020-12-29 12:08:45 -08001062 *stats = mScheduler->getDisplayStatInfo(systemTime());
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001063 return NO_ERROR;
1064}
1065
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001066void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001067 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001068
1069 if (!info.mode) {
1070 ALOGW("requested display mode is null");
1071 return;
1072 }
1073 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001074 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001075 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001076 return;
1077 }
1078
Ady Abraham690f4612021-07-01 23:24:03 -07001079 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001080 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001081
Alec Mouri754c98a2019-03-18 18:53:42 -07001082 // Start receiving vsync samples now, so that we can detect a period
1083 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001084 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001085 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001086 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001087 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001088
Ady Abraham690f4612021-07-01 23:24:03 -07001089 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001090 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001091 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001092}
1093
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001094status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001095 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001096
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001097 if (!displayToken) {
1098 return BAD_VALUE;
1099 }
Ady Abraham838de062019-02-04 10:24:03 -08001100
Dominik Laskowski756b7892021-08-04 12:53:59 -07001101 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001102 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001103 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001104 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001105 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001106 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001107 }
1108
1109 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001110 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001111 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001112 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001113
1114 const auto mode = display->getMode(DisplayModeId{modeId});
1115 if (!mode) {
1116 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1117 return BAD_VALUE;
1118 }
1119
1120 const auto fps = mode->getFps();
1121 // Keep the old switching type.
1122 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001123 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001124 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1125 allowGroupSwitching,
1126 {fps, fps}};
1127 constexpr bool kOverridePolicy = false;
1128
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001129 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001130 });
1131
1132 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001133}
1134
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001135void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001136 ATRACE_CALL();
1137
Dominik Laskowski22488f62019-03-28 09:53:04 -07001138 const auto display = getDefaultDisplayDeviceLocked();
1139 if (!display) {
1140 return;
1141 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001142
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001143 const auto upcomingModeInfo =
1144 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1145
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001146 if (!upcomingModeInfo.mode) {
1147 // There is no pending mode change. This can happen if the active
1148 // display changed and the mode change happened on a different display.
1149 return;
1150 }
1151
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001152 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001153 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1154 // We need to generate new sequenceId in order to recreate the display (and this
1155 // way the framebuffer).
1156 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001157 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001158 processDisplayChangesLocked();
1159
1160 // processDisplayChangesLocked will update all necessary components so we're done here.
1161 return;
1162 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001163
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001164 // We just created this display so we can call even if we are not on the main thread.
1165 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001166 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001167
Ady Abraham690f4612021-07-01 23:24:03 -07001168 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001169 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001170 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001171
Dominik Laskowski068173d2021-08-11 17:22:59 -07001172 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001173 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001174 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001175}
1176
Ady Abraham690f4612021-07-01 23:24:03 -07001177void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1178 display->clearDesiredActiveModeState();
1179 if (isDisplayActiveLocked(display)) {
1180 mScheduler->setModeChangePending(false);
1181 }
Ady Abraham53852a52019-05-28 18:07:44 -07001182}
1183
Ady Abraham690f4612021-07-01 23:24:03 -07001184void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1185 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1186 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001187 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001188 updatePhaseConfiguration(refreshRate);
1189}
1190
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001191void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001192 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001193
Marin Shalamanovdd594312021-11-09 16:37:37 +01001194 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1195
Ady Abraham690f4612021-07-01 23:24:03 -07001196 for (const auto& iter : mDisplays) {
1197 const auto& display = iter.second;
1198 if (!display || !display->isInternal()) {
1199 continue;
1200 }
1201
1202 // Store the local variable to release the lock.
1203 const auto desiredActiveMode = display->getDesiredActiveMode();
1204 if (!desiredActiveMode) {
1205 // No desired active mode pending to be applied
1206 continue;
1207 }
1208
1209 if (!isDisplayActiveLocked(display)) {
1210 // display is no longer the active display, so abort the mode change
1211 clearDesiredActiveModeState(display);
1212 continue;
1213 }
1214
1215 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1216 if (!desiredMode) {
1217 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1218 desiredActiveMode->mode->getId().value());
1219 clearDesiredActiveModeState(display);
1220 continue;
1221 }
1222
1223 const auto refreshRate = desiredMode->getFps();
1224 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1225 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1226 to_string(display->getId()).c_str());
1227
1228 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001229 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001230 desiredActiveModeChangeDone(display);
1231 continue;
1232 }
1233
1234 // Desired active mode was set, it is different than the mode currently in use, however
1235 // allowed modes might have changed by the time we process the refresh.
1236 // Make sure the desired mode is still allowed
1237 const auto displayModeAllowed =
1238 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1239 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001240 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001241 continue;
1242 }
1243
1244 // TODO(b/142753666) use constrains
1245 hal::VsyncPeriodChangeConstraints constraints;
1246 constraints.desiredTimeNanos = systemTime();
1247 constraints.seamlessRequired = false;
1248 hal::VsyncPeriodChangeTimeline outTimeline;
1249
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001250 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1251 display->initiateModeChange(*desiredActiveMode,
1252 constraints, &outTimeline));
1253
Ady Abraham690f4612021-07-01 23:24:03 -07001254 if (status != NO_ERROR) {
1255 // initiateModeChange may fail if a hotplug event is just about
1256 // to be sent. We just log the error in this case.
1257 ALOGW("initiateModeChange failed: %d", status);
1258 continue;
1259 }
1260 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1261
Marin Shalamanovdd594312021-11-09 16:37:37 +01001262 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001263 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001264 mSetActiveModePending = true;
1265 } else {
1266 // Updating the internal state should be done outside the loop,
1267 // because it can recreate a DisplayDevice and modify mDisplays
1268 // which will invalidate the iterator.
1269 displayToUpdateImmediately = display->getPhysicalId();
1270 }
1271 }
1272
1273 if (displayToUpdateImmediately) {
1274 updateInternalStateWithChangedMode();
1275
1276 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1277 const auto desiredActiveMode = display->getDesiredActiveMode();
1278 if (desiredActiveMode &&
1279 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1280 desiredActiveModeChangeDone(display);
1281 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001282 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001283}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001284
Alec Mouridea1ac52021-06-23 18:12:18 -07001285void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001286 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001287 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001288 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001289 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001290 for (const auto& [_, display] : mDisplays) {
1291 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001292 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001293 }
1294 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001295 });
1296
1297 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001298}
1299
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001300std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1301 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001302
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001303 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001304 // filter out all wide color modes. The typical reason why this happens is that the
1305 // hardware is not good enough to support GPU composition of wide color, and thus the
1306 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001307 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1308 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001309 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1310 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001311 }
Michael Wright28f24d02016-07-12 13:30:53 -07001312
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001313 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001314}
1315
Daniel Solomon42d04562019-01-20 21:03:19 -08001316status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001317 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001318 if (!displayToken) {
1319 return BAD_VALUE;
1320 }
1321
Dominik Laskowski3c363242022-04-07 10:44:12 -07001322 Mutex::Autolock lock(mStateLock);
1323
1324 const auto display = getDisplayDeviceLocked(displayToken);
1325 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001326 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001327 }
1328
Dominik Laskowski3c363242022-04-07 10:44:12 -07001329 const auto connectionType = display->getConnectionType();
1330 if (connectionType != ui::DisplayConnectionType::Internal) {
1331 return INVALID_OPERATION;
1332 }
1333
1334 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1335 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001336 return NO_ERROR;
1337}
1338
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001339status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001340 if (!displayToken) {
1341 return BAD_VALUE;
1342 }
1343
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001344 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001345 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001346 if (!display) {
1347 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1348 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001349 return NAME_NOT_FOUND;
1350 }
1351
1352 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001353 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1354 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001355 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001356 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001357
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001358 const auto modes = getDisplayColorModes(*display);
1359 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1360
1361 if (mode < ColorMode::NATIVE || !exists) {
1362 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1363 decodeColorMode(mode).c_str(), mode, displayToken.get());
1364 return BAD_VALUE;
1365 }
1366
1367 display->getCompositionDisplay()->setColorProfile(
1368 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1369
1370 return NO_ERROR;
1371 });
1372
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001373 // TODO(b/195698395): Propagate error.
1374 future.wait();
1375 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001376}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001377
Kriti Dang7defaf32021-11-15 11:55:43 +01001378status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001379 auto future = mScheduler->schedule(
1380 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1381
1382 *outSupport = future.get();
1383 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001384}
1385
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001386status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1387 ui::DisplayModeId modeId) {
1388 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001389 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001390 const auto display = getDisplayDeviceLocked(displayToken);
1391 if (!display) {
1392 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1393 return NAME_NOT_FOUND;
1394 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001395
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001396 if (display->isVirtual()) {
1397 ALOGE("%s: Invalid operation on virtual display", whence);
1398 return INVALID_OPERATION;
1399 }
1400
1401 const auto displayId = display->getPhysicalId();
1402 const auto mode = display->getMode(DisplayModeId{modeId});
1403 if (!mode) {
1404 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1405 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001406 return BAD_VALUE;
1407 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001408
1409 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001410 });
1411 return future.get();
1412}
1413
1414status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001415 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001416 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001417 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1418 return getHwComposer().clearBootDisplayMode(*displayId);
1419 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001420 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001421 return BAD_VALUE;
1422 }
1423 });
1424 return future.get();
1425}
1426
Galia Peycheva5492cb52019-10-30 14:13:16 +01001427void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001428 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001429 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001430 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1431 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1432 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001433 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001434 }
1435 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001436}
1437
Galia Peycheva5492cb52019-10-30 14:13:16 +01001438void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001439 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001440 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001441 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001442 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001443 getHwComposer().setContentType(*displayId, type);
1444 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001445 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001446 }
1447 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001448}
1449
Svetoslavd85084b2014-03-20 10:28:31 -07001450status_t SurfaceFlinger::clearAnimationFrameStats() {
1451 Mutex::Autolock _l(mStateLock);
1452 mAnimFrameTracker.clearStats();
1453 return NO_ERROR;
1454}
1455
1456status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1457 Mutex::Autolock _l(mStateLock);
1458 mAnimFrameTracker.getStats(outStats);
1459 return NO_ERROR;
1460}
1461
Kriti Dang49ad4132021-01-08 11:49:56 +01001462status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1463 const std::vector<ui::Hdr>& hdrTypes) {
1464 Mutex::Autolock lock(mStateLock);
1465
1466 auto display = getDisplayDeviceLocked(displayToken);
1467 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001468 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001469 return NAME_NOT_FOUND;
1470 }
1471
1472 display->overrideHdrTypes(hdrTypes);
1473 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1474 return NO_ERROR;
1475}
1476
Tej Singhe2751772021-04-06 22:05:29 -07001477status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1478 *success = mTimeStats->onPullAtom(atomId, pulledData);
1479 return NO_ERROR;
1480}
1481
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001482status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1483 ui::PixelFormat* outFormat,
1484 ui::Dataspace* outDataspace,
1485 uint8_t* outComponentMask) const {
1486 if (!outFormat || !outDataspace || !outComponentMask) {
1487 return BAD_VALUE;
1488 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001489
1490 Mutex::Autolock lock(mStateLock);
1491
1492 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1493 if (!displayId) {
1494 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001495 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001496
1497 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001498 outDataspace, outComponentMask);
1499}
1500
Kevin DuBois74e53772018-11-19 10:52:38 -08001501status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1502 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001503 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001504 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001505 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001506 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1507 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1508 componentMask, maxFrames);
1509 } else {
1510 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1511 return NAME_NOT_FOUND;
1512 }
1513 });
1514
1515 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001516}
1517
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001518status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1519 uint64_t maxFrames, uint64_t timestamp,
1520 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001521 Mutex::Autolock lock(mStateLock);
1522
1523 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1524 if (!displayId) {
1525 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001526 }
1527
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001528 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001529}
1530
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001531status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1532 if (!outSupported) {
1533 return BAD_VALUE;
1534 }
1535 *outSupported = getRenderEngine().supportsProtectedContent();
1536 return NO_ERROR;
1537}
1538
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001539status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1540 bool* outIsWideColorDisplay) const {
1541 if (!displayToken || !outIsWideColorDisplay) {
1542 return BAD_VALUE;
1543 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001544
1545 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001546 const auto display = getDisplayDeviceLocked(displayToken);
1547 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001548 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001549 }
Peiyong Linff84a152019-05-17 18:36:19 -07001550
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001551 *outIsWideColorDisplay =
1552 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001553 return NO_ERROR;
1554}
1555
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001556status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001557 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001558 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001559
Dominik Laskowski6505f792019-09-18 11:10:05 -07001560 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001561 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001562 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001563 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001564
Dominik Laskowski756b7892021-08-04 12:53:59 -07001565 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001566 return NO_ERROR;
1567}
1568
1569status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001570 Mutex::Autolock lock(mStateLock);
Ady Abrahame90dd522020-12-29 12:08:45 -08001571 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(when);
Ady Abraham56b42a42020-12-28 16:48:48 -08001572 const auto expectedPresent = calculateExpectedPresentTime(stats);
Ady Abraham9c53ee72020-07-22 21:16:18 -07001573 return mScheduler->injectVSync(when, /*expectedVSyncTime=*/expectedPresent,
1574 /*deadlineTimestamp=*/expectedPresent)
1575 ? NO_ERROR
1576 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001577}
1578
Huihong Luo05539a12022-02-23 10:29:40 -08001579status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001580 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001581 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001582 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001583 mDrawingState.traverseInZOrder([&](Layer* layer) {
1584 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1585 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001586 });
1587
1588 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001589 return NO_ERROR;
1590}
1591
Peiyong Linc6780972018-10-28 15:24:08 -07001592status_t SurfaceFlinger::getCompositionPreference(
1593 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1594 Dataspace* outWideColorGamutDataspace,
1595 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001596 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001597 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001598 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001599 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001600 return NO_ERROR;
1601}
1602
Dan Stozaec460082018-12-17 15:35:09 -08001603status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1604 const sp<IBinder>& stopLayerHandle,
1605 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001606 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001607 return BAD_VALUE;
1608 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001609
1610 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1611 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001612 return NO_ERROR;
1613}
1614
Dan Stozaec460082018-12-17 15:35:09 -08001615status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001616 if (!listener) {
1617 return BAD_VALUE;
1618 }
Dan Stozaec460082018-12-17 15:35:09 -08001619 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001620 return NO_ERROR;
1621}
Dan Gittik57e63c52019-01-18 16:37:54 +00001622
Alec Mouria9a68a62021-03-04 19:14:50 -08001623status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001624 if (!listener) {
1625 return BAD_VALUE;
1626 }
1627
Alec Mouria9a68a62021-03-04 19:14:50 -08001628 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001629 return NO_ERROR;
1630}
1631
1632status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1633 if (!listener) {
1634 return BAD_VALUE;
1635 }
1636 mFpsReporter->removeListener(listener);
1637 return NO_ERROR;
1638}
1639
Galia Peycheva8f04b302021-04-27 13:25:38 +02001640status_t SurfaceFlinger::addTunnelModeEnabledListener(
1641 const sp<gui::ITunnelModeEnabledListener>& listener) {
1642 if (!listener) {
1643 return BAD_VALUE;
1644 }
1645
1646 mTunnelModeEnabledReporter->addListener(listener);
1647 return NO_ERROR;
1648}
1649
1650status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1651 const sp<gui::ITunnelModeEnabledListener>& listener) {
1652 if (!listener) {
1653 return BAD_VALUE;
1654 }
1655
1656 mTunnelModeEnabledReporter->removeListener(listener);
1657 return NO_ERROR;
1658}
1659
Dan Gittik57e63c52019-01-18 16:37:54 +00001660status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1661 bool* outSupport) const {
1662 if (!displayToken || !outSupport) {
1663 return BAD_VALUE;
1664 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001665
1666 Mutex::Autolock lock(mStateLock);
1667
Dan Gittik57e63c52019-01-18 16:37:54 +00001668 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1669 if (!displayId) {
1670 return NAME_NOT_FOUND;
1671 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001672 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001673 return NO_ERROR;
1674}
1675
Alec Mouricdf16792021-12-10 13:16:06 -08001676bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1677 bool hasHdrLayers = false;
1678 mDrawingState.traverse([&,
1679 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1680 hasHdrLayers |= (layer->isVisible() &&
1681 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1682 isHdrDataspace(layer->getDataSpace()));
1683 });
1684 return hasHdrLayers;
1685}
1686
John Reck22be6962021-03-10 12:59:54 -05001687status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1688 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001689 if (!displayToken) {
1690 return BAD_VALUE;
1691 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001692
Dominik Laskowski756b7892021-08-04 12:53:59 -07001693 const char* const whence = __func__;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001694 return ftl::Future(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001695 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001696 const bool supportsDisplayBrightnessCommand =
1697 getHwComposer().getComposer()->isSupported(
1698 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1699 // If we support applying display brightness as a command, then we also support
1700 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001701 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001702 auto compositionDisplay = display->getCompositionDisplay();
1703 float currentDimmingRatio =
1704 compositionDisplay->editState().sdrWhitePointNits /
1705 compositionDisplay->editState().displayBrightnessNits;
1706 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1707 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001708 FTL_FAKE_GUARD(kMainThreadContext,
1709 display->stageBrightness(brightness.displayBrightness));
1710
Alec Mouri6da0e272022-02-07 12:45:57 -08001711 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1712 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001713 scheduleComposite(FrameHint::kNone);
1714 } else {
1715 scheduleCommit(FrameHint::kNone);
1716 }
1717 return ftl::yield<status_t>(OK);
1718 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001719 return getHwComposer()
1720 .setDisplayBrightness(display->getPhysicalId(),
1721 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001722 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001723 Hwc2::Composer::DisplayBrightnessOptions{
1724 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001725 }
Alec Mouricdf16792021-12-10 13:16:06 -08001726
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001727 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001728 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001729 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001730 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001731 }))
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001732 .then([](ftl::Future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001733 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001734}
1735
John Reck88270902021-03-18 11:27:35 -04001736status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1737 const sp<gui::IHdrLayerInfoListener>& listener) {
1738 if (!displayToken) {
1739 return BAD_VALUE;
1740 }
1741
1742 Mutex::Autolock lock(mStateLock);
1743
1744 const auto display = getDisplayDeviceLocked(displayToken);
1745 if (!display) {
1746 return NAME_NOT_FOUND;
1747 }
1748 const auto displayId = display->getId();
1749 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1750 if (!hdrInfoReporter) {
1751 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1752 }
1753 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001754
1755
1756 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001757 return OK;
1758}
1759
1760status_t SurfaceFlinger::removeHdrLayerInfoListener(
1761 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1762 if (!displayToken) {
1763 return BAD_VALUE;
1764 }
1765
1766 Mutex::Autolock lock(mStateLock);
1767
1768 const auto display = getDisplayDeviceLocked(displayToken);
1769 if (!display) {
1770 return NAME_NOT_FOUND;
1771 }
1772 const auto displayId = display->getId();
1773 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1774 if (hdrInfoReporter) {
1775 hdrInfoReporter->removeListener(listener);
1776 }
1777 return OK;
1778}
1779
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001780status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001781 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001782 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001783
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001784 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001785 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001786 }
1787
1788 return NO_ERROR;
1789}
1790
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001791status_t SurfaceFlinger::getDisplayDecorationSupport(
1792 const sp<IBinder>& displayToken,
1793 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001794 if (!displayToken || !outSupport) {
1795 return BAD_VALUE;
1796 }
1797
1798 Mutex::Autolock lock(mStateLock);
1799
1800 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1801 if (!displayId) {
1802 return NAME_NOT_FOUND;
1803 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001804 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001805 return NO_ERROR;
1806}
1807
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001808// ----------------------------------------------------------------------------
1809
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001810sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001811 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001812 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001813 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1814 ? mSfConnectionHandle
1815 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001816
Ady Abraham62f216c2020-10-13 19:07:23 -07001817 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001818}
1819
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001820void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001821 if (hint == FrameHint::kActive) {
1822 mScheduler->resetIdleTimer();
1823 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001824 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001825 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001826}
1827
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001828void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1829 mMustComposite = true;
1830 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001831}
1832
1833void SurfaceFlinger::scheduleRepaint() {
1834 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001835 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001836}
1837
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001838void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001839 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001840}
1841
Ady Abraham2492a022020-07-24 11:09:55 -07001842nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001843 if (const auto display = getDefaultDisplayDeviceLocked()) {
1844 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001845 }
1846
Marin Shalamanov045b7002021-01-07 16:56:24 +01001847 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001848}
1849
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001850void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1851 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001852 const std::string tracePeriod = [vsyncPeriod]() {
1853 if (ATRACE_ENABLED() && vsyncPeriod) {
1854 std::stringstream ss;
1855 ss << "(" << *vsyncPeriod << ")";
1856 return ss.str();
1857 }
1858 return std::string();
1859 }();
1860 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001861
Steven Thomas3cfac282017-02-06 12:29:30 -08001862 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001863 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1864 if (displayId) {
1865 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1866 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001867 display->onVsync(timestamp);
1868 }
1869
Dominik Laskowski075d3172018-05-24 15:50:06 -07001870 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001871 return;
1872 }
1873
Ady Abrahame1166472021-07-15 10:56:06 -07001874 const bool isActiveDisplay =
1875 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1876 if (!isActiveDisplay) {
1877 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001878 return;
1879 }
1880
Alec Mourif8e689c2019-05-20 18:32:22 -07001881 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001882 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001883 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001884 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001885 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001886}
1887
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001888void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001889 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1890 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001891}
1892
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001893void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1894 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001895 const bool connected = connection == hal::Connection::CONNECTED;
1896 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001897
Steven Thomasb02664d2017-07-26 18:48:28 -07001898 // Only lock if we're not on the main thread. This function is normally
1899 // called on a hwbinder thread, but for the primary display it's called on
1900 // the main thread with the state lock already held, so don't attempt to
1901 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001902 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001903
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001904 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001905
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001906 if (std::this_thread::get_id() == mMainThreadId) {
1907 // Process all pending hot plug events immediately if we are on the main thread.
1908 processDisplayHotplugEventsLocked();
1909 }
1910
Lloyd Piqueba04e622017-12-14 17:11:26 -08001911 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001912}
1913
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001914void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1915 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001916 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001917 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001918
1919 if (timeline.refreshRequired) {
1920 scheduleComposite(FrameHint::kNone);
1921 }
Ady Abraham7159f572019-10-11 11:10:18 -07001922}
1923
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001924void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001925 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001926 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1927}
1928
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001929void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001930 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001931 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001932}
1933
Yichi Chen3401b562022-01-17 15:42:35 +08001934void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001935 ATRACE_CALL();
1936 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001937}
1938
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001939void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001940 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001941
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001942 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001943 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001944 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001945
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001946 if (const auto display = getDefaultDisplayDeviceLocked();
1947 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001948 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001949 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001950 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001951}
1952
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001953SurfaceFlinger::FenceWithFenceTime SurfaceFlinger::previousFrameFence() {
Ady Abrahamccf4b472021-05-11 19:53:01 -07001954 const auto now = systemTime();
1955 const auto vsyncPeriod = mScheduler->getDisplayStatInfo(now).vsyncPeriod;
1956 const bool expectedPresentTimeIsTheNextVsync = mExpectedPresentTime - now <= vsyncPeriod;
1957 return expectedPresentTimeIsTheNextVsync ? mPreviousPresentFences[0]
1958 : mPreviousPresentFences[1];
Alec Mouri6d414b52020-03-17 11:18:05 -07001959}
1960
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001961bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001962 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001963 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001964
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001965 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001966 return false;
1967 }
1968
Dan Stoza59083052020-04-28 10:13:20 -07001969 const status_t status = fence->wait(graceTimeMs);
1970 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1971 // which calls wait(0) again internally
1972 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001973}
1974
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001975nsecs_t SurfaceFlinger::previousFramePresentTime() {
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001976 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001977
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001978 if (fence == FenceTime::NO_FENCE) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001979 return Fence::SIGNAL_TIME_INVALID;
1980 }
1981
1982 return fence->getSignalTime();
1983}
1984
Ady Abraham56b42a42020-12-28 16:48:48 -08001985nsecs_t SurfaceFlinger::calculateExpectedPresentTime(DisplayStatInfo stats) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001986 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham8cb21882020-08-26 18:22:05 -07001987 return mVsyncModulator->getVsyncConfig().sfOffset > 0 ? stats.vsyncTime
1988 : stats.vsyncTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001989}
1990
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001991bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1992 FTL_FAKE_GUARD(kMainThreadContext) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001993 // calculate the expected present time once and use the cached
1994 // value throughout this frame to make sure all layers are
1995 // seeing this same value.
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001996 if (expectedVsyncTime >= frameTime) {
1997 mExpectedPresentTime = expectedVsyncTime;
Snild Dolkow819636c2021-01-22 14:42:08 +01001998 } else {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001999 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(frameTime);
Snild Dolkow819636c2021-01-22 14:42:08 +01002000 mExpectedPresentTime = calculateExpectedPresentTime(stats);
2001 }
2002
2003 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002004 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07002005
Ady Abraham893c99d2021-04-30 16:00:23 -07002006 const auto vsyncIn = [&] {
2007 if (!ATRACE_ENABLED()) return 0.f;
2008 return (mExpectedPresentTime - systemTime()) / 1e6f;
2009 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002010 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
2011 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002012
Dan Stoza28d46a52020-04-28 09:54:54 -07002013 // When Backpressure propagation is enabled we want to give a small grace period
2014 // for the present fence to fire instead of just giving up on this frame to handle cases
2015 // where present fence is just about to get signaled.
2016 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002017 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002018
2019 // Pending frames may trigger backpressure propagation.
2020 const TracedOrdinal<bool> framePending = {"PrevFramePending",
2021 previousFramePending(graceTimeForPresentFenceMs)};
2022
2023 // Frame missed counts for metrics tracking.
2024 // A frame is missed if the prior frame is still pending. If no longer pending,
2025 // then we still count the frame as missed if the predicted present time
2026 // was further in the past than when the fence actually fired.
2027
2028 // Add some slop to correct for drift. This should generally be
2029 // smaller than a typical frame duration, but should not be so small
2030 // that it reports reasonable drift as a missed frame.
Ady Abrahame90dd522020-12-29 12:08:45 -08002031 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(systemTime());
Dan Stoza28d46a52020-04-28 09:54:54 -07002032 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
2033 const nsecs_t previousPresentTime = previousFramePresentTime();
2034 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2035 framePending ||
2036 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002037 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002038 previousPresentTime - frameMissedSlop))};
2039 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2040 mHadDeviceComposition && frameMissed};
2041 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2042 mHadClientComposition && frameMissed};
2043
2044 if (frameMissed) {
2045 mFrameMissedCount++;
2046 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002047 }
2048
2049 if (hwcFrameMissed) {
2050 mHwcFrameMissedCount++;
2051 }
2052
2053 if (gpuFrameMissed) {
2054 mGpuFrameMissedCount++;
2055 }
2056
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002057 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002058 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002059 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002060 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002061 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002062 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002063 }
2064
2065 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002066 // the mode, hence we update SF.
2067 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002068 {
2069 Mutex::Autolock lock(mStateLock);
2070 updateInternalStateWithChangedMode();
2071 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002072 }
2073
John Reck2ec53912020-07-07 16:53:55 -07002074 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002075 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002076 scheduleCommit(FrameHint::kNone);
2077 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002078 }
2079 }
2080
Matt Buckley50c44062022-01-17 20:48:10 +00002081 // Save this once per commit + composite to ensure consistency
2082 mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession();
2083 if (mPowerHintSessionEnabled) {
2084 nsecs_t vsyncPeriod;
2085 {
2086 Mutex::Autolock lock(mStateLock);
2087 vsyncPeriod = getVsyncPeriodFromHWC();
2088 }
2089 mPowerAdvisor->setCommitStart(frameTime);
2090 mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime);
2091 const nsecs_t idealSfWorkDuration =
2092 mVsyncModulator->getVsyncConfig().sfWorkDuration.count();
2093 // Frame delay is how long we should have minus how long we actually have
2094 mPowerAdvisor->setFrameDelay(idealSfWorkDuration - (mExpectedPresentTime - frameTime));
2095 mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration);
2096 mPowerAdvisor->setTargetWorkDuration(vsyncPeriod);
2097
2098 // Send early hint here to make sure there's not another frame pending
2099 if (mPowerHintSessionMode.early) {
2100 // Send a rough prediction for this frame based on last frame's timing info
2101 mPowerAdvisor->sendPredictedWorkDuration();
2102 }
2103 }
2104
Dan Stoza28d46a52020-04-28 09:54:54 -07002105 if (mTracingEnabledChanged) {
Vishnu Nair7891e962021-11-11 12:07:21 -08002106 mLayerTracingEnabled = mLayerTracing.isEnabled();
Dan Stoza28d46a52020-04-28 09:54:54 -07002107 mTracingEnabledChanged = false;
2108 }
2109
Ady Abraham29d0da32020-07-16 18:39:33 -07002110 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002111 Mutex::Autolock lock(mStateLock);
2112 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002113 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002114 }
2115 }
2116
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002117 // Composite if transactions were committed, or if requested by HWC.
2118 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002119 {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002120 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(stats.vsyncPeriod));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002121
chaviw6b9ffea2021-11-08 09:25:48 -06002122 bool needsTraversal = false;
2123 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002124 needsTraversal |= commitCreatedLayers();
2125 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002126 }
2127
2128 const bool shouldCommit =
2129 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2130 if (shouldCommit) {
2131 commitTransactions();
2132 }
2133
2134 if (transactionFlushNeeded()) {
2135 setTransactionFlags(eTransactionFlushNeeded);
2136 }
2137
2138 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002139 mustComposite |= latchBuffers();
2140
chaviw6b9ffea2021-11-08 09:25:48 -06002141 // This has to be called after latchBuffers because we want to include the layers that have
2142 // been latched in the commit callback
2143 if (!needsTraversal) {
2144 // Invoke empty transaction callbacks early.
2145 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2146 } else {
2147 // Invoke OnCommit callbacks.
2148 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2149 }
2150
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002151 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002152 }
2153
2154 // Layers need to get updated (in the previous line) before we can use them for
2155 // choosing the refresh rate.
2156 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2157 // and may eventually call to ~Layer() if it holds the last reference
2158 {
2159 Mutex::Autolock _l(mStateLock);
2160 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002161 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002162 }
2163
Dan Stoza28d46a52020-04-28 09:54:54 -07002164 updateCursorAsync();
2165 updateInputFlinger();
2166
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002167 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2168 // This will block and tracing should only be enabled for debugging.
2169 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
2170 }
2171
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002172 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002173
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002174 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002175}
2176
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002177void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2178 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002179 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002180
Lloyd Piqueab039b52019-02-13 14:22:42 -08002181 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002182 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002183 refreshArgs.outputs.reserve(displays.size());
Matt Buckley50c44062022-01-17 20:48:10 +00002184 std::vector<DisplayId> displayIds;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002185 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002186 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Matt Buckley50c44062022-01-17 20:48:10 +00002187 displayIds.push_back(display->getId());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002188 }
Matt Buckley50c44062022-01-17 20:48:10 +00002189 mPowerAdvisor->setDisplays(displayIds);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002190 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002191 if (auto layerFE = layer->getCompositionEngineLayerFE())
2192 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002193 });
Tianhao Yao67dd7122022-02-22 17:48:33 +00002194
2195 if (DOES_CONTAIN_BORDER) {
2196 refreshArgs.borderInfoList.clear();
2197 mDrawingState.traverse([&refreshArgs](Layer* layer) {
2198 if (layer->isBorderEnabled()) {
2199 compositionengine::BorderRenderInfo info;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00002200 info.width = layer->getBorderWidth();
2201 info.color = layer->getBorderColor();
Tianhao Yao67dd7122022-02-22 17:48:33 +00002202 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2203 info.layerIds.push_back(ilayer->getSequence());
2204 });
2205 refreshArgs.borderInfoList.emplace_back(std::move(info));
2206 }
2207 });
2208 }
2209
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002210 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002211 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002212 if (auto layerFE = layer->getCompositionEngineLayerFE())
2213 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002214 }
2215
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002216 refreshArgs.outputColorSetting = useColorManagement
2217 ? mDisplayColorSetting
2218 : compositionengine::OutputColorSetting::kUnmanaged;
2219 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2220 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002221
2222 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002223 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002224 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002225 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002226
2227 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2228 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2229 mDrawingState.colorMatrixChanged = false;
2230 }
2231
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002232 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002233
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002234 if (mDebugFlashDelay != 0) {
2235 refreshArgs.devOptForceClientComposition = true;
2236 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002237 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002238
Ady Abraham43065bd2021-12-10 17:22:15 -08002239 const auto expectedPresentTime = mExpectedPresentTime.load();
2240 const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
Ady Abrahamcaba2982021-06-16 16:45:04 -07002241 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2242 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002243 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002244 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002245 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002246
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002247 // Store the present time just before calling to the composition engine so we could notify
2248 // the scheduler.
2249 const auto presentTime = systemTime();
2250
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002251 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002252
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002253 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002254
Matt Buckley50c44062022-01-17 20:48:10 +00002255 // Send a power hint hint after presentation is finished
2256 if (mPowerHintSessionEnabled) {
2257 if (mPowerHintSessionMode.late) {
2258 mPowerAdvisor->sendActualWorkDuration();
2259 }
2260 }
2261
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002262 if (mScheduler->onPostComposition(presentTime)) {
2263 scheduleComposite(FrameHint::kNone);
2264 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002265
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002266 postFrame();
2267 postComposition();
2268
Midas Chien50f52e22020-09-26 17:57:42 +08002269 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002270
Vishnu Nair9cf89262022-02-26 09:17:49 -08002271 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2272 TimeStats::ClientCompositionRecord clientCompositionRecord;
2273 for (const auto& [_, display] : displays) {
2274 const auto& state = display->getCompositionDisplay()->getState();
2275 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2276 mHadDeviceComposition |= state.usesDeviceComposition;
2277 mReusedClientComposition |= state.reusedClientComposition;
2278 clientCompositionRecord.predicted |=
2279 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2280 clientCompositionRecord.predictionSucceeded |=
2281 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002282 }
2283
Vishnu Nair9cf89262022-02-26 09:17:49 -08002284 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2285 clientCompositionRecord.reused = mReusedClientComposition;
2286 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2287 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2288
Yichi Chen28dee2c2020-07-06 21:24:14 +08002289 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002290 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2291 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002292
David Sodman7e4ae112018-02-09 15:02:28 -08002293 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002294 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002295 // This will block and should only be used for debugging.
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002296 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
Vishnu Nairdf529052019-06-07 14:53:14 -07002297 }
Robert Carr167bdde2021-07-28 11:26:51 -07002298
2299 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002300 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002301
2302 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002303 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002304 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002305
Matt Buckley50c44062022-01-17 20:48:10 +00002306 if (mPowerHintSessionEnabled) {
2307 mPowerAdvisor->setCompositeEnd(systemTime());
Matt Buckleyef51fba2021-10-12 19:30:12 +00002308 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002309}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002310
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002311void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002312 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002313
Vishnu Nair4351ad52019-02-11 14:13:02 -08002314 if (mVisibleRegionsDirty) {
2315 computeLayerBounds();
2316 }
2317
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002318 for (auto& layer : mLayersPendingRefresh) {
2319 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002320 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002321 invalidateLayerStack(layer, visibleReg);
2322 }
2323 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002324}
2325
Ana Krulece588e312018-09-18 12:32:24 -07002326void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2327 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002328 // Update queue of past composite+present times and determine the
2329 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002330 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002331 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002332 while (!getBE().mCompositePresentTimes.empty()) {
2333 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002334 // Cached values should have been updated before calling this method,
2335 // which helps avoid duplicate syscalls.
2336 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2337 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2338 break;
2339 }
2340 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002341 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002342 }
2343
2344 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002345 while (getBE().mCompositePresentTimes.size() > 16) {
2346 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002347 }
2348
Ana Krulece588e312018-09-18 12:32:24 -07002349 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002350}
2351
Ana Krulece588e312018-09-18 12:32:24 -07002352void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2353 nsecs_t compositeToPresentLatency) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002354 // Avoid division by 0 by defaulting to 60Hz
2355 const auto vsyncPeriod = stats.vsyncPeriod ?: (60_Hz).getPeriodNsecs();
2356
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002357 // Integer division and modulo round toward 0 not -inf, so we need to
2358 // treat negative and positive offsets differently.
Ady Abraham8287e852020-08-12 14:44:58 -07002359 nsecs_t idealLatency = (mVsyncConfiguration->getCurrentConfigs().late.sfOffset > 0)
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002360 ? (vsyncPeriod -
2361 (mVsyncConfiguration->getCurrentConfigs().late.sfOffset % vsyncPeriod))
2362 : ((-mVsyncConfiguration->getCurrentConfigs().late.sfOffset) % vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002363
Ady Abraham8287e852020-08-12 14:44:58 -07002364 // Just in case mVsyncConfiguration->getCurrentConfigs().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002365 if (idealLatency <= 0) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002366 idealLatency = vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002367 }
2368
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002369 // Snap the latency to a value that removes scheduling jitter from the
2370 // composition and present times, which often have >1ms of jitter.
2371 // Reducing jitter is important if an app attempts to extrapolate
2372 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002373 // Snapping also allows an app to precisely calculate
Ady Abraham8287e852020-08-12 14:44:58 -07002374 // mVsyncConfiguration->getCurrentConfigs().late.sf with (presentLatency % interval).
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002375 const nsecs_t bias = vsyncPeriod / 2;
2376 const int64_t extraVsyncs = ((compositeToPresentLatency - idealLatency + bias) / vsyncPeriod);
Ady Abraham8d7e7842022-02-03 01:42:45 +00002377 const nsecs_t snappedCompositeToPresentLatency =
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002378 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002379
David Sodman99974d22017-11-28 12:04:33 -08002380 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002381 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002382 getBE().mCompositorTiming.interval = vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002383 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002384}
2385
John Reck49d9ad32022-02-23 19:03:31 -05002386bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002387 // Treat all layers as non-HDR if:
2388 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2389 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2390 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2391 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2392 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002393 return false;
2394 }
2395 if (mIgnoreHdrCameraLayers) {
2396 auto buffer = layer->getBuffer();
2397 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2398 return false;
2399 }
2400 }
2401 return true;
2402}
2403
ramindani06e518e2022-03-14 18:47:53 +00002404ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2405 bool isPrimary) const {
2406 const auto id = PhysicalDisplayId::tryCast(displayId);
2407 if (!id) {
2408 return ui::ROTATION_0;
2409 }
2410 if (getHwComposer().getComposer()->isSupported(
2411 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2412 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2413 case Hwc2::AidlTransform::ROT_90:
2414 return ui::ROTATION_90;
2415 case Hwc2::AidlTransform::ROT_180:
2416 return ui::ROTATION_180;
2417 case Hwc2::AidlTransform::ROT_270:
2418 return ui::ROTATION_270;
2419 default:
2420 return ui::ROTATION_0;
2421 }
2422 }
2423
2424 if (isPrimary) {
2425 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2426 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2427 case Values::ORIENTATION_90:
2428 return ui::ROTATION_90;
2429 case Values::ORIENTATION_180:
2430 return ui::ROTATION_180;
2431 case Values::ORIENTATION_270:
2432 return ui::ROTATION_270;
2433 default:
2434 break;
2435 }
2436 }
2437 return ui::ROTATION_0;
2438}
2439
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002440void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002441 ATRACE_CALL();
2442 ALOGV("postComposition");
2443
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002444 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002445
2446 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002447 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002448 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002449 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002450 ->getRenderSurface()
2451 ->getClientTargetAcquireFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002452 } else {
2453 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2454 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002455
Ady Abrahambe0f9482019-04-24 15:41:53 -07002456 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002457 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002458 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002459 mPreviousPresentFences[0].fenceTime =
2460 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2461
Vishnu Nair9a69a042021-06-18 13:19:49 -07002462 nsecs_t now = systemTime();
2463
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002464 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2465 // information from previous' frame classification is already available when sending jank info
2466 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002467 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002468 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002469
Vishnu Nair9a69a042021-06-18 13:19:49 -07002470 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002471
Lloyd Piqueab039b52019-02-13 14:22:42 -08002472 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2473 // be sampled a little later than when we started doing work for this frame,
2474 // but that should be okay since updateCompositorTiming has snapping logic.
2475 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002476 mPreviousPresentFences[0].fenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002477 CompositorTiming compositorTiming;
2478 {
David Sodman99974d22017-11-28 12:04:33 -08002479 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2480 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002481 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002482
Robert Carrc747ad02021-06-11 14:01:24 -07002483 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002484 layer->onPostComposition(display, glCompositionDoneFenceTime,
2485 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002486 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002487 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002488
John Reck88270902021-03-18 11:27:35 -04002489 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2490 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002491 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002492 {
2493 Mutex::Autolock lock(mStateLock);
2494 if (mFpsReporter) {
2495 mFpsReporter->dispatchLayerFps();
2496 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002497
2498 if (mTunnelModeEnabledReporter) {
2499 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2500 }
John Reck88270902021-03-18 11:27:35 -04002501 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002502 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2503 if (reporter && reporter->hasListeners()) {
2504 if (const auto display = getDisplayDeviceLocked(displayId)) {
2505 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002506 }
2507 }
2508 }
Robert Carr167bdde2021-07-28 11:26:51 -07002509 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2510 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002511 }
2512
Robert Carr167bdde2021-07-28 11:26:51 -07002513 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2514 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2515 HdrLayerInfoReporter::HdrLayerInfo info;
2516 int32_t maxArea = 0;
2517 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2518 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002519 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002520 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002521 const auto* outputLayer =
2522 compositionDisplay->getOutputLayerForLayer(layerFe);
2523 if (outputLayer) {
2524 info.numberOfHdrLayers++;
2525 const auto displayFrame = outputLayer->getState().displayFrame;
2526 const int32_t area = displayFrame.width() * displayFrame.height();
2527 if (area > maxArea) {
2528 maxArea = area;
2529 info.maxW = displayFrame.width();
2530 info.maxH = displayFrame.height();
2531 }
John Reckdb1a16b2021-07-09 13:05:52 -04002532 }
John Reck88270902021-03-18 11:27:35 -04002533 }
2534 }
Robert Carr167bdde2021-07-28 11:26:51 -07002535 });
2536 listener->dispatchHdrLayerInfo(info);
2537 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002538 }
2539
Robert Carr167bdde2021-07-28 11:26:51 -07002540 mSomeDataspaceChanged = false;
2541 mVisibleRegionsWereDirtyThisFrame = false;
2542
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002543 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002544 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002545 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002546
Ady Abrahamed3290f2021-05-17 15:12:14 -07002547 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002548 mPreviousPresentFences[0].fenceTime->isValid()) {
2549 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002550 }
2551
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002552 const bool isDisplayConnected =
2553 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002554
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002555 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002556 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002557 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002558 }
2559 }
2560
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002561 if (mAnimCompositionPending) {
2562 mAnimCompositionPending = false;
2563
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002564 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2565 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002566 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002567 // The HWC doesn't support present fences, so use the refresh
2568 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002569 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002570 mAnimFrameTracker.setActualPresentTime(presentTime);
2571 }
2572 mAnimFrameTracker.advanceFrame();
2573 }
Dan Stozab90cf072015-03-05 11:05:59 -08002574
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002575 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002576
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002577 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002578
Alec Mouri717bcb62020-02-10 17:07:19 -08002579 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2580 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2581 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2582
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002583 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002584 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002585 return;
2586 }
2587
2588 nsecs_t currentTime = systemTime();
2589 if (mHasPoweredOff) {
2590 mHasPoweredOff = false;
2591 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002592 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002593 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002594 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2595 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002596 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002597 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002598 }
David Sodman4a36e932017-11-07 14:29:47 -08002599 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002600 }
David Sodman4a36e932017-11-07 14:29:47 -08002601 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002602
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002603 // Cleanup any outstanding resources due to rendering a prior frame.
2604 getRenderEngine().cleanupPostRender();
2605
Dan Stoza436ccf32018-06-21 12:10:12 -07002606 {
2607 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002608 if (mTexturePool.size() < mTexturePoolSize) {
2609 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002610 const size_t offset = mTexturePool.size();
2611 mTexturePool.resize(mTexturePoolSize);
2612 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2613 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002614 } else if (mTexturePool.size() > mTexturePoolSize) {
2615 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2616 const size_t offset = mTexturePoolSize;
2617 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2618 mTexturePool.resize(mTexturePoolSize);
2619 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002620 }
2621 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002622
Dan Stoza45de5ba2019-04-25 14:12:09 -07002623 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2624 // side-effect of getTotalSize(), so we check that again here
2625 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002626 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002627 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2628 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002629}
2630
chaviw79468ab2021-10-27 11:11:24 -05002631FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002632 const ui::Size maxSize = [this] {
2633 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002634
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002635 // The LayerTraceGenerator tool runs without displays.
2636 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002637
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002638 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2639 [](ui::Size size, const auto& pair) -> ui::Size {
2640 const auto& display = pair.second;
2641 return {std::max(size.getWidth(), display->getWidth()),
2642 std::max(size.getHeight(), display->getHeight())};
2643 });
2644 }();
chaviwb09c6552021-08-12 17:20:43 -05002645
2646 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2647 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002648 const float xMax = maxSize.getWidth() * 10.f;
2649 const float yMax = maxSize.getHeight() * 10.f;
2650
2651 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002652}
2653
2654void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002655 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002656 for (const auto& layer : mDrawingState.layersSortedByZ) {
2657 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002658 }
2659}
2660
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002661void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002662 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002663 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002664 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002665 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2666 logFrameStats();
2667 }
2668 }
2669}
2670
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002671void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002672 ATRACE_CALL();
2673
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002674 // Keep a copy of the drawing state (that is going to be overwritten
2675 // by commitTransactionsLocked) outside of mStateLock so that the side
2676 // effects of the State assignment don't happen with mStateLock held,
2677 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002678 State drawingState(mDrawingState);
2679
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002680 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002681 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682
Mathias Agopianca4d3602011-05-19 15:38:14 -07002683 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002684 // so we can call commitTransactionsLocked unconditionally.
2685 // We clear the flags with mStateLock held to guarantee that
2686 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002687 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002688 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002689
Mathias Agopianca4d3602011-05-19 15:38:14 -07002690 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002691}
2692
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002693std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2694 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002695 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2696 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002697
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002698 int attempt = 0;
2699 constexpr int kMaxAttempts = 3;
2700 do {
2701 hwcModes = getHwComposer().getModes(displayId);
2702 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2703 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2704
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002705 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2706 return mode.hwcId == *activeModeHwcId;
2707 };
2708
2709 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2710 break;
2711 }
2712 } while (++attempt < kMaxAttempts);
2713
2714 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002715 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002716 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002717 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002718
2719 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002720 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2721 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002722 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002723
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002724 ui::DisplayModeId nextModeId = 1 +
2725 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2726 [](ui::DisplayModeId max, const auto& pair) {
2727 return std::max(max, pair.first.value());
2728 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002729
2730 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002731 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002732 const DisplayModeId id{nextModeId++};
2733 newModes.try_emplace(id,
2734 DisplayMode::Builder(hwcMode.hwcId)
2735 .setId(id)
2736 .setPhysicalDisplayId(displayId)
2737 .setResolution({hwcMode.width, hwcMode.height})
2738 .setVsyncPeriod(hwcMode.vsyncPeriod)
2739 .setDpiX(hwcMode.dpiX)
2740 .setDpiY(hwcMode.dpiY)
2741 .setGroup(hwcMode.configGroup)
2742 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002743 }
2744
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002745 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002746 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002747 [](const auto& lhs, const auto& rhs) {
2748 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002749 });
2750
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002751 // Keep IDs if modes have not changed.
2752 const auto& modes = sameModes ? oldModes : newModes;
2753 const DisplayModePtr activeMode =
2754 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2755 return pair.second->getHwcId() == activeModeHwcId;
2756 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002757
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002758 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002759}
2760
Lloyd Piqueba04e622017-12-14 17:11:26 -08002761void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2762 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002763 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002764 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002765
Dominik Laskowski075d3172018-05-24 15:50:06 -07002766 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002767 continue;
2768 }
2769
Marin Shalamanova524a092020-07-27 21:39:55 +02002770 const auto displayId = info->id;
Dominik Laskowskieb627312022-04-07 09:13:16 -07002771 const auto token = mPhysicalDisplayTokens.get(displayId);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002772
Peiyong Line9d809e2020-04-14 13:10:48 -07002773 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002774 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002775
Dominik Laskowskieb627312022-04-07 09:13:16 -07002776 if (!token) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002777 ALOGV("Creating display %s", to_string(displayId).c_str());
2778
Dominik Laskowski075d3172018-05-24 15:50:06 -07002779 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002780 state.physical = {.id = displayId,
2781 .type = getHwComposer().getDisplayConnectionType(displayId),
2782 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002783 .deviceProductInfo = std::move(info->deviceProductInfo),
2784 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002785 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002786 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002787 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002788
2789 sp<IBinder> token = new BBinder();
2790 mCurrentState.displays.add(token, state);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002791 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002792 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002793 } else {
2794 ALOGV("Recreating display %s", to_string(displayId).c_str());
2795
Dominik Laskowskieb627312022-04-07 09:13:16 -07002796 auto& state = mCurrentState.displays.editValueFor(token->get());
2797 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
Marin Shalamanova903d032020-12-29 20:35:13 +01002798 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002799 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002800 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2801 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2802 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002803 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002804 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002805 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002806
Dominik Laskowskieb627312022-04-07 09:13:16 -07002807 if (const ssize_t index = mCurrentState.displays.indexOfKey(token->get()); index >= 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002808 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2809 mInterceptor->saveDisplayDeletion(state.sequenceId);
2810 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002811 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002812
2813 mPhysicalDisplayTokens.erase(displayId);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002814 }
2815
2816 processDisplayChangesLocked();
2817 }
2818
2819 mPendingHotplugEvents.clear();
2820}
2821
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002822void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002823 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2824 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002825 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2826 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002827}
2828
Lloyd Pique99d3da52018-01-22 17:48:03 -08002829sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002830 const wp<IBinder>& displayToken,
2831 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002832 const DisplayDeviceState& state,
2833 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002834 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002835 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002836 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002837 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002838 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002839 creationArgs.hasWideColorGamut = false;
2840 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002841
Dominik Laskowski55c85402020-01-21 16:25:47 -08002842 if (const auto& physical = state.physical) {
2843 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002844 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002845 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002846 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2847 getKernelIdleTimerProperties(compositionDisplay->getId());
2848
Ady Abraham3efa3942021-06-24 19:01:25 -07002849 scheduler::RefreshRateConfigs::Config config =
2850 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2851 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002852 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002853 .idleTimerTimeout = idleTimerTimeoutMs,
2854 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002855 creationArgs.refreshRateConfigs =
2856 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2857 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002858 }
2859
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002860 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002861 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002862
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002863 if (useColorManagement) {
2864 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2865 for (ColorMode colorMode : modes) {
2866 if (isWideColorMode(colorMode)) {
2867 creationArgs.hasWideColorGamut = true;
2868 }
2869
2870 std::vector<RenderIntent> renderIntents =
2871 getHwComposer().getRenderIntents(*id, colorMode);
2872 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002873 }
2874 }
tangrobin6753a022018-08-10 10:58:54 +08002875 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002876
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002877 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2878 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2879 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002880 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002881
Lloyd Pique90c115d2018-09-18 21:39:42 -07002882 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002883 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002884 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002885
Lloyd Pique99d3da52018-01-22 17:48:03 -08002886 // Make sure that composition can never be stalled by a virtual display
2887 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002888 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002889 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002890 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2891 }
2892
Dominik Laskowski718f9602019-11-09 20:01:35 -08002893 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002894 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2895 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002896
Lloyd Pique99d3da52018-01-22 17:48:03 -08002897 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002898 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002899
Lloyd Pique9370a482019-10-03 17:58:30 -07002900 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002901
Ady Abraham8565ad22021-06-22 17:45:44 -07002902 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002903
2904 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002905 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002906 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002907 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002908 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002909 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002910 display->getCompositionDisplay()->setColorProfile(
2911 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2912 RenderIntent::COLORIMETRIC,
2913 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002914 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002915 FTL_FAKE_GUARD(kMainThreadContext,
2916 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002917 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002918 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002919
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002920 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002921 display->setProjection(state.orientation, state.layerStackSpaceRect,
2922 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002923 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002924 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002925
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002926 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002927}
2928
Marin Shalamanovae685592020-02-12 17:12:22 +01002929void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2930 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002931 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002932 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2933 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002934 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002935 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2936 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002937 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002938 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002939 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002940 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002941 int format;
2942 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002943 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002944 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002945 } else {
2946 // Virtual displays without a surface are dormant:
2947 // they have external state (layer stack, projection,
2948 // etc.) but no internal state (i.e. a DisplayDevice).
2949 return;
2950 }
2951
2952 compositionengine::DisplayCreationArgsBuilder builder;
2953 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002954 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002955 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002956 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002957 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002958
Marin Shalamanov045b7002021-01-07 16:56:24 +01002959 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002960 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002961 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002962 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002963 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002964 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002965
2966 sp<compositionengine::DisplaySurface> displaySurface;
2967 sp<IGraphicBufferProducer> producer;
2968 sp<IGraphicBufferProducer> bqProducer;
2969 sp<IGraphicBufferConsumer> bqConsumer;
2970 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2971
Marin Shalamanovae685592020-02-12 17:12:22 +01002972 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002973 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2974 LOG_FATAL_IF(!displayId);
2975 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2976 bqProducer, bqConsumer, state.displayName);
2977 displaySurface = surface;
2978 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002979 } else {
2980 ALOGE_IF(state.surface != nullptr,
2981 "adding a supported display, but rendering "
2982 "surface is provided (%p), ignoring it",
2983 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002984 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2985 LOG_FATAL_IF(!displayId);
2986 displaySurface =
2987 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002988 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002989 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002990 producer = bqProducer;
2991 }
2992
Marin Shalamanov700e6392020-02-12 20:22:26 +01002993 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002994 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2995 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002996 if (display->isPrimary()) {
2997 initScheduler(display);
2998 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002999 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003000 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01003001 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07003002
3003 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01003004}
3005
3006void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08003007 auto display = getDisplayDeviceLocked(displayToken);
3008 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01003009 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003010
3011 if (display->isVirtual()) {
3012 releaseVirtualDisplay(display->getVirtualId());
3013 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003014 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01003015 }
3016 }
3017
3018 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08003019
3020 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07003021 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08003022 // Destroy the display without holding the mStateLock.
3023 // This is a temporary solution until we can manage transaction queues without
3024 // holding the mStateLock.
3025 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
3026 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
3027 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
3028 // ends up running on the main thread causing a deadlock since setTransactionstate
3029 // will try to acquire the mStateLock. Instead we extend the lifetime of
3030 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
3031 // The display will be disconnected and removed from the mDisplays list so it will
3032 // not be accessible.
3033 }));
3034 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003035}
3036
3037void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
3038 const DisplayDeviceState& currentState,
3039 const DisplayDeviceState& drawingState) {
3040 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3041 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003042
3043 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01003044 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02003045 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003046
Marin Shalamanovae685592020-02-12 17:12:22 +01003047 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3048 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003049 if (display->isVirtual()) {
3050 releaseVirtualDisplay(display->getVirtualId());
3051 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003052 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003053
Marin Shalamanovae685592020-02-12 17:12:22 +01003054 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003055
Marin Shalamanov700e6392020-02-12 20:22:26 +01003056 if (const auto& physical = currentState.physical) {
3057 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3058 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003059
Marin Shalamanovae685592020-02-12 17:12:22 +01003060 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003061
Marin Shalamanov700e6392020-02-12 20:22:26 +01003062 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003063 const auto display = getDisplayDeviceLocked(displayToken);
3064 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003065
3066 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003067 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003068 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003069 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003070 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003071 return;
3072 }
3073
3074 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3075 if (currentState.layerStack != drawingState.layerStack) {
3076 display->setLayerStack(currentState.layerStack);
3077 }
Evan Rosky2239b372021-05-20 13:43:47 -07003078 if (currentState.flags != drawingState.flags) {
3079 display->setFlags(currentState.flags);
3080 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003081 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003082 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3083 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3084 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3085 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003086 if (isDisplayActiveLocked(display)) {
3087 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003088 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003089 }
3090 if (currentState.width != drawingState.width ||
3091 currentState.height != drawingState.height) {
3092 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003093
Ady Abrahamed3290f2021-05-17 15:12:14 -07003094 if (isDisplayActiveLocked(display)) {
3095 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003096 }
3097 }
3098 }
3099}
Ady Abraham3efa3942021-06-24 19:01:25 -07003100void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003101 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003102 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003103 updatePhaseConfiguration(refreshRate);
3104 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003105}
Marin Shalamanovae685592020-02-12 17:12:22 +01003106
Lloyd Pique347200f2017-12-14 17:00:15 -08003107void SurfaceFlinger::processDisplayChangesLocked() {
3108 // here we take advantage of Vector's copy-on-write semantics to
3109 // improve performance by skipping the transaction entirely when
3110 // know that the lists are identical
3111 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3112 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3113 if (!curr.isIdenticalTo(draw)) {
3114 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003115
3116 // find the displays that were removed
3117 // (ie: in drawing state but not in current state)
3118 // also handle displays that changed
3119 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003120 for (size_t i = 0; i < draw.size(); i++) {
3121 const wp<IBinder>& displayToken = draw.keyAt(i);
3122 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003123 if (j < 0) {
3124 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003125 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003126 } else {
3127 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003128 const DisplayDeviceState& currentState = curr[j];
3129 const DisplayDeviceState& drawingState = draw[i];
3130 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003131 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003132 }
3133
3134 // find displays that were added
3135 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003136 for (size_t i = 0; i < curr.size(); i++) {
3137 const wp<IBinder>& displayToken = curr.keyAt(i);
3138 if (draw.indexOfKey(displayToken) < 0) {
3139 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003140 }
3141 }
3142 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003143
3144 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003145}
3146
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003147void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3148 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003149 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3150 if (displayTransactionNeeded) {
3151 processDisplayChangesLocked();
3152 processDisplayHotplugEventsLocked();
3153 }
Robert Carrb552ff52021-06-11 13:35:54 -07003154 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155
Robert Carre450fb52021-06-11 13:21:09 -07003156 if (mSomeChildrenChanged) {
3157 mVisibleRegionsDirty = true;
3158 mSomeChildrenChanged = false;
3159 }
3160
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003161 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003162 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003163 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003164 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003165 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003166 // the hint is set before we acquire a buffer from the surface texture.
3167 //
3168 // NOTE: layer transactions have taken place already, so we use their
3169 // drawing state. However, SurfaceFlinger's own transaction has not
3170 // happened yet, so we must use the current state layer list
3171 // (soon to become the drawing state list).
3172 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003173 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003174 ui::LayerStack layerStack;
3175
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003176 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003177 // NOTE: we rely on the fact that layers are sorted by
3178 // layerStack first (so we don't have to traverse the list
3179 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003180 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3181 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003182 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003183
3184 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003185 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003186 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3187 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003188 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003189
3190 // Pick the primary display if another display mirrors the layer.
3191 if (hintDisplay) {
3192 hintDisplay = nullptr;
3193 break;
3194 }
3195
3196 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003197 }
3198 }
Chet Haase91d25932013-04-11 15:24:55 -07003199
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003200 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003201 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3202 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003203
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003204 // could be null when this layer is using a layerStack
3205 // that is not visible on any display. Also can occur at
3206 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003207 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003208 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003209
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003210 layer->updateTransformHint(hintDisplay->getTransformHint());
Robert Carr2047fae2016-11-28 14:09:09 -08003211 });
Mathias Agopian84300952012-11-21 16:02:13 -08003212 }
3213
Robert Carr1f0a16a2016-10-24 16:27:39 -07003214 if (mLayersAdded) {
3215 mLayersAdded = false;
3216 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003217 mVisibleRegionsDirty = true;
3218 }
3219
3220 // some layers might have been removed, so
3221 // we need to update the regions they're exposing.
3222 if (mLayersRemoved) {
3223 mLayersRemoved = false;
3224 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003225 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003226 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003227 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003228 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003229 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003230 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003231 }
Robert Carr2047fae2016-11-28 14:09:09 -08003232 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233 }
3234
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003235 doCommitTransactions();
3236 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3237 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003238}
3239
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003240void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003241 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003242 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003243 return;
3244 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003245
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003246 std::vector<WindowInfo> windowInfos;
3247 std::vector<DisplayInfo> displayInfos;
3248 bool updateWindowInfo = false;
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003249 if (mVisibleRegionsDirty || mInputInfoChanged) {
3250 mInputInfoChanged = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003251 updateWindowInfo = true;
3252 buildWindowInfos(windowInfos, displayInfos);
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003253 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003254 if (!updateWindowInfo && mInputWindowCommands.empty()) {
3255 return;
3256 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003257 BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
3258 windowInfos = std::move(windowInfos),
3259 displayInfos = std::move(displayInfos),
3260 inputWindowCommands =
3261 std::move(mInputWindowCommands),
3262 inputFlinger = mInputFlinger, this]() {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003263 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3264 if (updateWindowInfo) {
3265 mWindowInfosListenerInvoker->windowInfosChanged(windowInfos, displayInfos,
3266 inputWindowCommands.syncInputWindows);
3267 } else if (inputWindowCommands.syncInputWindows) {
3268 // If the caller requested to sync input windows, but there are no
3269 // changes to input windows, notify immediately.
3270 windowInfosReported();
3271 }
3272 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3273 inputFlinger->setFocusedWindow(focusRequest);
3274 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003275 }});
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003276
Arthur Hung6cbb9752019-09-05 16:38:18 +08003277 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003278}
3279
Alec Mouricdf16792021-12-10 13:16:06 -08003280void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3281 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3282 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3283 if (!supportsDisplayBrightnessCommand) {
3284 return;
3285 }
3286
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003287 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003288 if (const auto brightness = display->getStagedBrightness(); brightness) {
3289 if (!needsComposite) {
3290 const status_t error =
3291 getHwComposer()
3292 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003293 display->getCompositionDisplay()
3294 ->getState()
3295 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003296 Hwc2::Composer::DisplayBrightnessOptions{
3297 .applyImmediately = true})
3298 .get();
3299
3300 ALOGE_IF(error != NO_ERROR,
3301 "Error setting display brightness for display %s: %d (%s)",
3302 display->getDebugName().c_str(), error, strerror(error));
3303 }
3304 display->persistBrightness(needsComposite);
3305 }
3306 }
3307}
3308
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003309void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3310 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003311 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3312
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003313 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003314 const auto layerStack = display->getLayerStack();
3315 const auto info = display->getInputInfo();
3316
3317 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003318 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003319 continue;
3320 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003321
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003322 // If the layer stack is mirrored on multiple displays, the first display that is configured
3323 // to receive input takes precedence.
3324 auto& otherInfo = it->second;
3325 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003326 ALOGW_IF(display->receivesInput(),
3327 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003328 layerStack.id);
3329 } else {
3330 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003331 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003332 }
Robert Carr720e5062018-07-30 17:45:14 -07003333
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003334 static size_t sNumWindowInfos = 0;
3335 outWindowInfos.reserve(sNumWindowInfos);
3336 sNumWindowInfos = 0;
3337
Robert Carr720e5062018-07-30 17:45:14 -07003338 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003339 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003340
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003341 // Do not create WindowInfos for windows on displays that cannot receive input.
3342 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3343 const auto& info = opt->get();
3344 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003345 }
Robert Carr720e5062018-07-30 17:45:14 -07003346 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003347
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003348 sNumWindowInfos = outWindowInfos.size();
3349
3350 outDisplayInfos.reserve(displayInputInfos.size());
3351 for (const auto& [_, info] : displayInputInfos) {
3352 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003353 }
Robert Carr720e5062018-07-30 17:45:14 -07003354}
3355
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003356void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003357 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003358 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003359 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003360 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003361 }
3362 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003363
3364 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003365}
3366
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003367void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003368 // If this is called from the main thread mStateLock must be locked before
3369 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003370 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003371
3372 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003373
3374 const auto display = getDefaultDisplayDeviceLocked();
3375 if (!display || mBootStage != BootStage::FINISHED) {
3376 return;
3377 }
3378 ATRACE_CALL();
3379
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003380 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3381 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003382 return;
3383 }
3384
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003385 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003386}
3387
Ady Abraham62a0be22020-12-08 16:54:10 -08003388void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3389 PhysicalDisplayId displayId = [&]() {
3390 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3391 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3392 }();
3393
3394 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3395}
3396
Ady Abraham3efa3942021-06-24 19:01:25 -07003397void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003398 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003399 // If the scheduler is already initialized, this means that we received
3400 // a hotplug(connected) on the primary display. In that case we should
3401 // update the scheduler with the most recent display information.
3402 ALOGW("Scheduler already initialized, updating instead");
3403 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003404 return;
3405 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003406 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003407 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3408 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003409
Marin Shalamanova903d032020-12-29 20:35:13 +01003410 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003411 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003412
Dominik Laskowski068173d2021-08-11 17:22:59 -07003413 using Feature = scheduler::Feature;
3414 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003415
Dominik Laskowski068173d2021-08-11 17:22:59 -07003416 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3417 features |= Feature::kContentDetection;
3418 }
3419 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3420 features |= Feature::kTracePredictedVsync;
3421 }
3422 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003423 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003424 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003425 }
3426
Dominik Laskowski068173d2021-08-11 17:22:59 -07003427 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3428 static_cast<ISchedulerCallback&>(*this),
3429 features);
3430 {
3431 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003432 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003433 features |= Feature::kKernelIdleTimer;
3434 }
3435
3436 mScheduler->createVsyncSchedule(features);
3437 mScheduler->setRefreshRateConfigs(std::move(configs));
3438 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003439 setVsyncEnabled(false);
3440 mScheduler->startTimers();
3441
Ady Abraham9c53ee72020-07-22 21:16:18 -07003442 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003443 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003444 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003445 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003446 /*workDuration=*/configs.late.appWorkDuration,
3447 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003448 impl::EventThread::InterceptVSyncsCallback());
3449 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003450 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3451 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3452 /*readyDuration=*/configs.late.sfWorkDuration,
3453 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003454 mInterceptor->saveVSyncEvent(timestamp);
3455 });
3456
Dominik Laskowski756b7892021-08-04 12:53:59 -07003457 mScheduler->initVsync(mScheduler->getVsyncDispatch(), *mFrameTimeline->getTokenManager(),
3458 configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003459
3460 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003461 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003462 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003463 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003464 // initialization, so that the EventThreads always contain a reference to a
3465 // prior configuration.
3466 //
3467 // This is a bit hacky, but this avoids a back-pointer into the main SF
3468 // classes from EventThread, and there should be no run-time binder cost
3469 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003470 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003471}
3472
Marin Shalamanov5801c942020-12-17 17:00:13 +01003473void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3474 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003475 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003476 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003477}
3478
Ady Abraham55fa7272020-09-30 19:19:27 -07003479void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3480 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003481 mScheduler->setDuration(mAppConnectionHandle,
3482 /*workDuration=*/config.appWorkDuration,
3483 /*readyDuration=*/config.sfWorkDuration);
3484 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003485 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3486 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003487 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003488}
3489
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003490void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003491 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003492
Lloyd Pique58e24a32019-08-01 15:50:14 -07003493 if (!mLayersPendingRemoval.isEmpty()) {
3494 // Notify removed layers now that they can't be drawn from
3495 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003496 // Ensure any buffers set to display on any children are released.
3497 if (l->isRemovedFromCurrentState()) {
3498 l->latchAndReleaseBuffer();
3499 }
3500
chaviw6852bff2022-04-19 17:35:11 -05003501 // If a layer has a parent, we allow it to out-live it's handle
3502 // with the idea that the parent holds a reference and will eventually
3503 // be cleaned up. However no one cleans up the top-level so we do so
3504 // here.
3505 if (l->isAtRoot()) {
3506 l->setIsAtRoot(false);
3507 mCurrentState.layersSortedByZ.remove(l);
3508 }
3509
Lloyd Pique58e24a32019-08-01 15:50:14 -07003510 // If the layer has been removed and has no parent, then it will not be reachable
3511 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3512 // ensure we can copy its current to drawing state.
3513 if (!l->getParent()) {
3514 mOffscreenLayers.emplace(l.get());
3515 }
3516 }
3517 mLayersPendingRemoval.clear();
3518 }
3519
3520 // If this transaction is part of a window animation then the next frame
3521 // we composite should be considered an animation as well.
3522 mAnimCompositionPending = mAnimTransactionPending;
3523
3524 mDrawingState = mCurrentState;
3525 // clear the "changed" flags in current state
3526 mCurrentState.colorMatrixChanged = false;
3527
Robert Carra70e91c2021-06-11 13:59:52 -07003528 if (mVisibleRegionsDirty) {
3529 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3530 rootLayer->commitChildList();
3531 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003532 }
Robert Carra70e91c2021-06-11 13:59:52 -07003533
Lloyd Pique58e24a32019-08-01 15:50:14 -07003534 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003535 if (mNumClones > 0) {
3536 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3537 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003538}
3539
chaviw74d90ad2019-04-26 14:45:26 -07003540void SurfaceFlinger::commitOffscreenLayers() {
3541 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003542 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003543 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3544 layer->doTransaction(0);
3545 layer->commitChildList();
3546 }
chaviw74d90ad2019-04-26 14:45:26 -07003547 });
3548 }
3549}
3550
Chia-I Wuab0c3192017-08-01 11:29:00 -07003551void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003552 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003553 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003554 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003555 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003556 }
3557 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003558}
3559
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003560bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003561 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003562
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003563 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003564
Mathias Agopian4fec8732012-06-29 14:12:52 -07003565 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003566 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003567 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003568
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003569 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3570
Eric Penner51c59cd2014-07-28 19:51:58 -07003571 // Store the set of layers that need updates. This set must not change as
3572 // buffers are being latched, as this could result in a deadlock.
3573 // Example: Two producers share the same command stream and:
3574 // 1.) Layer 0 is latched
3575 // 2.) Layer 0 gets a new frame
3576 // 2.) Layer 1 gets a new frame
3577 // 3.) Layer 1 is latched.
3578 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3579 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003580 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003581 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3582 const uint32_t flags = layer->doTransaction(0);
3583 if (flags & Layer::eVisibleRegion) {
3584 mVisibleRegionsDirty = true;
3585 }
3586 }
Robert Carrb552ff52021-06-11 13:35:54 -07003587
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003588 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003589 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003590 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003591 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003592 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003593 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003594 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003595 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003596 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003597 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003598 }
Robert Carr2047fae2016-11-28 14:09:09 -08003599 });
Robert Carrb552ff52021-06-11 13:35:54 -07003600 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003601
chaviw49a108c2019-08-12 11:23:06 -07003602 // The client can continue submitting buffers for offscreen layers, but they will not
3603 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3604 // layers to ensure dequeueBuffer doesn't block indefinitely.
3605 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003606 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003607 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3608 }
3609
Lloyd Piquef2c79392018-12-20 16:23:33 -08003610 if (!mLayersWithQueuedFrames.empty()) {
3611 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3612 // writes to Layer current state. See also b/119481871
3613 Mutex::Autolock lock(mStateLock);
3614
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003615 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003616 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003617 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003618 newDataLatched = true;
3619 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003620 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003621 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003622 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003623
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003624 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003625
3626 // If we will need to wake up at some time in the future to deal with a
3627 // queued frame that shouldn't be displayed during this vsync period, wake
3628 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003629 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003630 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003631 }
3632
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003633 // enter boot animation on first buffer latch
3634 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3635 ALOGI("Enter boot animation");
3636 mBootStage = BootStage::BOOTANIMATION;
3637 }
3638
Robert Carr6a0382d2021-07-01 15:57:17 -07003639 if (mNumClones > 0) {
3640 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3641 }
chaviw74b03172019-08-19 11:09:03 -07003642
Dan Stoza6b9454d2014-11-07 16:00:59 -08003643 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003644 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003645}
3646
Robert Carrc0df3122019-04-11 13:18:21 -07003647status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003648 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003649 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003650 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003651 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003652 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003653 static_cast<void>(mScheduler->schedule([=] {
3654 ALOGE("Dumping random sampling of on-screen layers: ");
3655 mDrawingState.traverse([&](Layer *layer) {
3656 // Aim to dump about 200 layers to avoid totally trashing
3657 // logcat. On the other hand, if there really are 4096 layers
3658 // something has gone totally wrong its probably the most
3659 // useful information in logcat.
3660 if (rand() % 20 == 13) {
3661 ALOGE("Layer: %s", layer->getName().c_str());
3662 }
3663 });
3664 for (Layer* offscreenLayer : mOffscreenLayers) {
3665 if (rand() % 20 == 13) {
3666 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3667 }
3668 }
3669 }));
arthurhungdba591c2021-02-08 17:28:49 +08003670 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003671 }
3672
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003673 {
3674 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3675 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3676 }
arthurhungdba591c2021-02-08 17:28:49 +08003677
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003678 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003679 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003680 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003681 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003682 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003683 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003684 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003685 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003686
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003687 setTransactionFlags(eTransactionNeeded);
3688 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003689}
3690
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003691uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003692 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003693}
3694
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003695uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3696 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003697}
3698
Dominik Laskowski94000c42022-03-17 12:55:14 -07003699void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003700 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003701 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003702
3703 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003704 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003705 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003706}
3707
Ady Abraham9dada822022-02-03 10:26:59 -08003708bool SurfaceFlinger::stopTransactionProcessing(
3709 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3710 applyTokensWithUnsignaledTransactions) const {
3711 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3712 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3713 // then we should have only one applyToken for processing.
3714 // so we can stop further transactions on this applyToken.
3715 return !applyTokensWithUnsignaledTransactions.empty();
3716 }
3717
3718 return false;
3719}
3720
ramindani9eff2492022-03-23 00:28:26 +00003721int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3722 std::vector<TransactionState>& transactions,
3723 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3724 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3725 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3726 applyTokensWithUnsignaledTransactions,
3727 /*tryApplyUnsignaled*/ true);
3728}
3729
Robert Carr79dc06a2022-02-22 15:28:59 -08003730int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003731 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003732 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003733 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3734 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003735 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003736 auto it = mPendingTransactionQueues.begin();
3737 while (it != mPendingTransactionQueues.end()) {
3738 auto& [applyToken, transactionQueue] = *it;
3739 while (!transactionQueue.empty()) {
3740 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3741 ATRACE_NAME("stopTransactionProcessing");
3742 break;
3743 }
3744
3745 auto& transaction = transactionQueue.front();
3746 const auto ready =
Robert Carr4c1b6462021-12-21 10:30:50 -08003747 transactionIsReadyToBeApplied(transaction,
3748 transaction.frameTimelineInfo,
3749 transaction.isAutoTimestamp,
3750 transaction.desiredPresentTime,
3751 transaction.originUid, transaction.states,
3752 bufferLayersReadyToPresent, transactions.size(),
3753 tryApplyUnsignaled);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003754 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3755 if (ready == TransactionReadiness::NotReady) {
3756 setTransactionFlags(eTransactionFlushNeeded);
3757 break;
3758 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003759 if (ready == TransactionReadiness::NotReadyBarrier) {
3760 transactionsPendingBarrier++;
3761 setTransactionFlags(eTransactionFlushNeeded);
3762 break;
3763 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003764 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003765 const bool frameNumberChanged = state.bufferData->flags.test(
3766 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003767 if (frameNumberChanged) {
3768 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3769 } else {
3770 // Barrier function only used for BBQ which always includes a frame number
3771 bufferLayersReadyToPresent[state.surface] =
3772 std::numeric_limits<uint64_t>::max();
3773 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003774 });
3775 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3776 if (appliedUnsignaled) {
3777 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3778 }
3779
3780 transactions.emplace_back(std::move(transaction));
3781 transactionQueue.pop();
3782 }
3783
3784 if (transactionQueue.empty()) {
3785 it = mPendingTransactionQueues.erase(it);
3786 mTransactionQueueCV.broadcast();
3787 } else {
3788 it = std::next(it, 1);
3789 }
3790 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003791 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003792}
3793
Vishnu Nair7891e962021-11-11 12:07:21 -08003794bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003795 // to prevent onHandleDestroyed from being called while the lock is held,
3796 // we must keep a copy of the transactions (specifically the composer
3797 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003798 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003799 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003800 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003801 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003802 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003803 Mutex::Autolock _l(mStateLock);
3804 {
3805 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003806
Robert Carr79dc06a2022-02-22 15:28:59 -08003807 int lastTransactionsPendingBarrier = 0;
3808 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003809 // First collect transactions from the pending transaction queues.
3810 // We are not allowing unsignaled buffers here as we want to
3811 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003812 transactionsPendingBarrier =
3813 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3814 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003815
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003816 // Second, collect transactions from the transaction queue.
3817 // Here as well we are not allowing unsignaled buffers for the same
3818 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003819 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003820 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003821 const bool pendingTransactions =
3822 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003823 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003824 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003825 if (pendingTransactions) {
3826 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003827 return TransactionReadiness::NotReady;
3828 }
3829
Robert Carr4c1b6462021-12-21 10:30:50 -08003830 return transactionIsReadyToBeApplied(transaction, transaction.frameTimelineInfo,
Ady Abraham9dada822022-02-03 10:26:59 -08003831 transaction.isAutoTimestamp,
3832 transaction.desiredPresentTime,
3833 transaction.originUid, transaction.states,
3834 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003835 transactions.size(),
3836 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003837 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003838 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003839 if (ready != TransactionReadiness::Ready) {
3840 if (ready == TransactionReadiness::NotReadyBarrier) {
3841 transactionsPendingBarrier++;
3842 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003843 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003844 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003845 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003846 const bool frameNumberChanged = state.bufferData->flags.test(
3847 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003848 if (frameNumberChanged) {
3849 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3850 } else {
3851 // Barrier function only used for BBQ which always includes a frame number.
3852 // This value only used for barrier logic.
3853 bufferLayersReadyToPresent[state.surface] =
3854 std::numeric_limits<uint64_t>::max();
3855 }
Xiang Wang76236e12022-03-22 17:25:30 +00003856 });
Ady Abraham9dada822022-02-03 10:26:59 -08003857 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003858 }
ramindani4d48f902021-09-20 21:07:45 +00003859 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003860 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003861 }
Arthur Hung58144272021-01-16 03:43:53 +00003862
Robert Carr79dc06a2022-02-22 15:28:59 -08003863 // Transactions with a buffer pending on a barrier may be on a different applyToken
3864 // than the transaction which satisfies our barrier. In fact this is the exact use case
3865 // that the primitive is designed for. This means we may first process
3866 // the barrier dependent transaction, determine it ineligible to complete
3867 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3868 // The barrier dependent transaction was eligible to be presented in this frame
3869 // but we would have prevented it without case. To fix this we continually
3870 // loop through flushPendingTransactionQueues until we perform an iteration
3871 // where the number of transactionsPendingBarrier doesn't change. This way
3872 // we can continue to resolve dependency chains of barriers as far as possible.
3873 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3874 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3875 transactionsPendingBarrier =
3876 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3877 applyTokensWithUnsignaledTransactions,
3878 /*tryApplyUnsignaled*/ false);
3879 }
3880
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003881 // We collected all transactions that could apply without latching unsignaled buffers.
3882 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3883 // transactions that were not applied and try to apply them unsignaled.
3884 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003885 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3886 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003887 }
3888
Vishnu Nair7891e962021-11-11 12:07:21 -08003889 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003890 }
ramindani4d48f902021-09-20 21:07:45 +00003891 }
3892}
3893
Vishnu Nair7891e962021-11-11 12:07:21 -08003894bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3895 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003896 bool needsTraversal = false;
3897 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003898 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003899 needsTraversal |=
3900 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3901 transaction.displays, transaction.flags,
3902 transaction.inputWindowCommands,
3903 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3904 transaction.buffer, transaction.postTime,
3905 transaction.permissions, transaction.hasListenerCallbacks,
3906 transaction.listenerCallbacks, transaction.originPid,
3907 transaction.originUid, transaction.id);
3908 if (transaction.transactionCommittedSignal) {
3909 mTransactionCommittedSignals.emplace_back(
3910 std::move(transaction.transactionCommittedSignal));
3911 }
3912 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003913
Dominik Laskowski46471e62022-01-14 15:34:03 -08003914 if (mTransactionTracing) {
3915 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003916 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003917 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003918}
3919
3920bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003921 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003922 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003923}
3924
Ady Abraham8db10102021-03-15 17:19:23 -07003925bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3926 // The amount of time SF can delay a frame if it is considered early based
3927 // on the VsyncModulator::VsyncConfig::appWorkDuration
3928 constexpr static std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3929
3930 const auto currentVsyncPeriod = mScheduler->getDisplayStatInfo(systemTime()).vsyncPeriod;
3931 const auto earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
3932
3933 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3934 if (!prediction.has_value()) {
3935 return false;
3936 }
3937
3938 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3939 kEarlyLatchMaxThreshold.count()) {
3940 return false;
3941 }
3942
3943 return prediction->presentTime >= expectedPresentTime &&
3944 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3945}
Ady Abraham9dada822022-02-03 10:26:59 -08003946bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003947 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003948 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3949 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3950 return false;
3951 }
Ady Abraham8db10102021-03-15 17:19:23 -07003952
Ady Abraham9dada822022-02-03 10:26:59 -08003953 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3954 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3955 return true;
3956 }
3957
3958 // We only want to latch unsignaled when a single layer is updated in this
3959 // transaction (i.e. not a blast sync transaction).
3960 if (numStates != 1) {
3961 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3962 return false;
3963 }
3964
Ady Abraham2739e832022-02-14 17:42:00 -08003965 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3966 if (totalTXapplied > 0) {
3967 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3968 __func__, totalTXapplied);
3969 return false;
3970 }
3971
3972 // We don't want to latch unsignaled if are in early / client composition
3973 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3974 // or window animations being slow.
3975 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3976 if (!isDefaultVsyncConfig) {
3977 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3978 __func__);
3979 return false;
3980 }
Ady Abraham9dada822022-02-03 10:26:59 -08003981 }
3982
3983 if (!layer->simpleBufferUpdate(state)) {
3984 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3985 return false;
3986 }
3987
3988 ALOGV("%s: true", __func__);
3989 return true;
3990}
3991
Robert Carr4c1b6462021-12-21 10:30:50 -08003992auto SurfaceFlinger::transactionIsReadyToBeApplied(TransactionState& transaction,
Ady Abraham43752eb2021-03-04 16:24:25 -08003993 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003994 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003995 const std::unordered_map<
3996 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003997 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003998 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003999 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08004000 // Do not present if the desiredPresentTime has not passed unless it is more than one second
4001 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08004002 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08004003 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004004 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08004005 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08004006 }
4007
Ady Abraham5690bda2021-03-12 15:01:18 -08004008 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
4009 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08004010 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08004011 }
4012
Ady Abraham8db10102021-03-15 17:19:23 -07004013 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
4014 // present time of this transaction.
4015 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
4016 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08004017 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07004018 }
4019
Ady Abraham9dada822022-02-03 10:26:59 -08004020 bool fenceUnsignaled = false;
Robert Carr4c1b6462021-12-21 10:30:50 -08004021 auto queueProcessTime = systemTime();
Marissa Wall713b63f2018-10-17 15:42:43 -07004022 for (const ComposerState& state : states) {
4023 const layer_state_t& s = state.state;
Robert Carr4c1b6462021-12-21 10:30:50 -08004024
Ady Abrahamf20c1922020-12-21 18:39:01 -08004025 sp<Layer> layer = nullptr;
4026 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07004027 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004028 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08004029 ALOGW("Transaction with buffer, but no Layer?");
4030 continue;
4031 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08004032 if (!layer) {
4033 continue;
4034 }
Ady Abraham43752eb2021-03-04 16:24:25 -08004035
Robert Carr79dc06a2022-02-22 15:28:59 -08004036 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
4037 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
4038 const bool willApplyBarrierFrame =
4039 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
4040 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
4041 if (!willApplyBarrierFrame) {
4042 ATRACE_NAME("NotReadyBarrier");
4043 return TransactionReadiness::NotReadyBarrier;
4044 }
4045 }
4046
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004047 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08004048 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08004049 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
4050 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08004051
4052 const bool acquireFenceChanged = s.bufferData &&
4053 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
4054 s.bufferData->acquireFence;
4055 fenceUnsignaled = fenceUnsignaled ||
4056 (acquireFenceChanged &&
4057 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
4058
4059 if (fenceUnsignaled && !allowLatchUnsignaled) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004060 if (!transaction.sentFenceTimeoutWarning &&
4061 queueProcessTime - transaction.queueTime > std::chrono::nanoseconds(4s).count()) {
4062 transaction.sentFenceTimeoutWarning = true;
4063 auto listener = s.bufferData->releaseBufferListener;
4064 if (listener) {
4065 listener->onTransactionQueueStalled();
4066 }
4067 }
4068
Ady Abraham9dada822022-02-03 10:26:59 -08004069 ATRACE_NAME("fence unsignaled");
4070 return TransactionReadiness::NotReady;
4071 }
4072
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004073 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08004074 // If backpressure is enabled and we already have a buffer to commit, keep the
4075 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004076 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4077 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004078 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004079 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004080 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004081 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004082 }
4083 }
Ady Abraham9dada822022-02-03 10:26:59 -08004084 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004085}
4086
arthurhungf1b7c7b2021-03-03 17:42:23 +08004087void SurfaceFlinger::queueTransaction(TransactionState& state) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004088 state.queueTime = systemTime();
4089
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004090 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004091
arthurhungf1b7c7b2021-03-03 17:42:23 +08004092 // Generate a CountDownLatch pending state if this is a synchronous transaction.
4093 if ((state.flags & eSynchronous) || state.inputWindowCommands.syncInputWindows) {
4094 state.transactionCommittedSignal = std::make_shared<CountDownLatch>(
Arthur Hung2274a312021-04-28 15:13:06 +00004095 (state.inputWindowCommands.syncInputWindows
4096 ? (CountDownLatch::eSyncInputWindows | CountDownLatch::eSyncTransaction)
4097 : CountDownLatch::eSyncTransaction));
arthurhungf1b7c7b2021-03-03 17:42:23 +08004098 }
4099
ramindani4d48f902021-09-20 21:07:45 +00004100 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004101 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4102
Ady Abrahame46243a2021-02-23 19:33:49 -08004103 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004104 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4105 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004106 return TransactionSchedule::Late;
4107 }(state.flags);
4108
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004109 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4110
4111 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004112}
4113
arthurhungf1b7c7b2021-03-03 17:42:23 +08004114void SurfaceFlinger::waitForSynchronousTransaction(
4115 const CountDownLatch& transactionCommittedSignal) {
4116 // applyTransactionState is called on the main SF thread. While a given process may wish
4117 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4118 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004119 if (!transactionCommittedSignal.wait_until(
4120 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004121 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004122 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004123}
Ady Abrahame46243a2021-02-23 19:33:49 -08004124
Arthur Hung2274a312021-04-28 15:13:06 +00004125void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004126 for (auto it = mTransactionCommittedSignals.begin();
4127 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004128 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004129 it = mTransactionCommittedSignals.erase(it);
4130 } else {
4131 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004132 }
4133 }
4134}
4135
chaviw308ddba2020-08-11 16:23:51 -07004136status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004137 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004138 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4139 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004140 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004141 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004142 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004143
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004144 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004145 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4146 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004147 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4148 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004149 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004150 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004151 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004152 }
4153
Leon Scroggins9a20f722021-12-28 14:43:12 +00004154 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004155 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004156 }
4157
Robert Carrde6d7b42022-01-07 18:23:06 -08004158 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004159 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4160 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4161 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004162 }
4163
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004164 const int64_t postTime = systemTime();
4165
4166 IPCThreadState* ipc = IPCThreadState::self();
4167 const int originPid = ipc->getCallingPid();
4168 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004169 TransactionState state{frameTimelineInfo, states,
4170 displays, flags,
4171 applyToken, inputWindowCommands,
4172 desiredPresentTime, isAutoTimestamp,
4173 uncacheBuffer, postTime,
4174 permissions, hasListenerCallbacks,
4175 listenerCallbacks, originPid,
4176 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004177
4178 // Check for incoming buffer updates and increment the pending buffer count.
4179 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4180 mBufferCountTracker.increment(state.surface->localBinder());
4181 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004182
Dominik Laskowski46471e62022-01-14 15:34:03 -08004183 if (mTransactionTracing) {
4184 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004185 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004186 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004187
arthurhungf1b7c7b2021-03-03 17:42:23 +08004188 // Check the pending state to make sure the transaction is synchronous.
4189 if (state.transactionCommittedSignal) {
4190 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004191 }
4192
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004193 return NO_ERROR;
4194}
Marissa Wall713b63f2018-10-17 15:42:43 -07004195
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004196bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004197 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004198 const Vector<DisplayState>& displays, uint32_t flags,
4199 const InputWindowCommands& inputWindowCommands,
4200 const int64_t desiredPresentTime, bool isAutoTimestamp,
4201 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004202 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004203 bool hasListenerCallbacks,
4204 const std::vector<ListenerCallbacks>& listenerCallbacks,
4205 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004206 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004207 for (const DisplayState& display : displays) {
4208 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004209 }
4210
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004211 // start and end registration for listeners w/ no surface so they can get their callback. Note
4212 // that listeners with SurfaceControls will start registration during setClientStateLocked
4213 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004214 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004215 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004216 }
4217
Marissa Walle2ffb422018-10-12 11:33:52 -07004218 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004219 for (int i = 0; i < states.size(); i++) {
4220 ComposerState& state = states.editItemAt(i);
4221 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004222 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004223 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004224 if (const auto layer = fromHandle(state.state.surface).promote()) {
4225 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004226 mScheduler->recordLayerHistory(layer.get(),
4227 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004228 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004229 }
4230 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004231 }
4232
Marissa Walle2ffb422018-10-12 11:33:52 -07004233 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004234
Robert Carrde6d7b42022-01-07 18:23:06 -08004235 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004236 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4237 } else if (!inputWindowCommands.empty()) {
4238 ALOGE("Only privileged callers are allowed to send input commands.");
4239 }
chaviw273171b2018-12-26 11:46:30 -08004240
Marissa Wall947d34e2019-03-29 14:03:53 -07004241 if (uncacheBuffer.isValid()) {
4242 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004243 }
4244
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004245 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4246 // anyway. This can be used as a flush mechanism for previous async transactions.
4247 // Empty animation transaction can be used to simulate back-pressure, so also force a
4248 // transaction for empty animation transactions.
4249 if (transactionFlags == 0 &&
4250 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004251 transactionFlags = eTransactionNeeded;
4252 }
4253
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004254 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004255 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004256 if (mInterceptor->isEnabled()) {
4257 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004258 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004259 }
4260
Arthur Hung58144272021-01-16 03:43:53 +00004261 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4262 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4263 if (transactionFlags & eTraversalNeeded) {
4264 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004265 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004266 }
Arthur Hung58144272021-01-16 03:43:53 +00004267 if (transactionFlags) {
4268 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004269 }
4270
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004271 if (flags & eAnimation) {
4272 mAnimTransactionPending = true;
4273 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004274 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004275
4276 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004277}
4278
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004279uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4280 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4281 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004282
Mathias Agopiane57f2922012-08-09 16:29:12 -07004283 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004284 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4285
4286 const uint32_t what = s.what;
4287 if (what & DisplayState::eSurfaceChanged) {
4288 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4289 state.surface = s.surface;
4290 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004291 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004292 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004293 if (what & DisplayState::eLayerStackChanged) {
4294 if (state.layerStack != s.layerStack) {
4295 state.layerStack = s.layerStack;
4296 flags |= eDisplayTransactionNeeded;
4297 }
4298 }
Evan Rosky2239b372021-05-20 13:43:47 -07004299 if (what & DisplayState::eFlagsChanged) {
4300 if (state.flags != s.flags) {
4301 state.flags = s.flags;
4302 flags |= eDisplayTransactionNeeded;
4303 }
4304 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004305 if (what & DisplayState::eDisplayProjectionChanged) {
4306 if (state.orientation != s.orientation) {
4307 state.orientation = s.orientation;
4308 flags |= eDisplayTransactionNeeded;
4309 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004310 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4311 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004312 flags |= eDisplayTransactionNeeded;
4313 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004314 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4315 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004316 flags |= eDisplayTransactionNeeded;
4317 }
4318 }
4319 if (what & DisplayState::eDisplaySizeChanged) {
4320 if (state.width != s.width) {
4321 state.width = s.width;
4322 flags |= eDisplayTransactionNeeded;
4323 }
4324 if (state.height != s.height) {
4325 state.height = s.height;
4326 flags |= eDisplayTransactionNeeded;
4327 }
4328 }
4329
Mathias Agopiane57f2922012-08-09 16:29:12 -07004330 return flags;
4331}
4332
Steven Thomasd4071902020-03-24 16:02:53 -07004333bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004334 IPCThreadState* ipc = IPCThreadState::self();
4335 const int pid = ipc->getCallingPid();
4336 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004337 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004338 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4339 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004340 return false;
4341 }
4342 return true;
4343}
4344
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004345uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004346 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004347 int64_t desiredPresentTime, bool isAutoTimestamp,
4348 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004349 layer_state_t& s = composerState.state;
4350 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004351
4352 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004353 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004354 // Starts a registration but separates the callback ids according to callback type. This
4355 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004356 // note that startRegistration will not re-register if the listener has
4357 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004358
4359 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4360 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004361 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004362 }
4363
4364 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4365 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004366 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004367 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004368 }
4369
arthurhungdba591c2021-02-08 17:28:49 +08004370 const uint64_t what = s.what;
4371 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004372 sp<Layer> layer = nullptr;
4373 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004374 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004375 } else {
4376 // The client may provide us a null handle. Treat it as if the layer was removed.
4377 ALOGW("Attempt to set client state with a null layer handle");
4378 }
chaviw8b3871a2017-11-01 17:41:01 -07004379 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004380 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004381 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004382 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004383 }
chaviw8b3871a2017-11-01 17:41:01 -07004384 return 0;
4385 }
4386
Valerie Hau871d6352020-01-29 08:44:02 -08004387 // Only set by BLAST adapter layers
4388 if (what & layer_state_t::eProducerDisconnect) {
4389 layer->onDisconnect();
4390 }
4391
chaviw8b3871a2017-11-01 17:41:01 -07004392 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004393 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004394 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004395 }
chaviw8b3871a2017-11-01 17:41:01 -07004396 }
4397 if (what & layer_state_t::eLayerChanged) {
4398 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004399 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004400 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004401 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004402 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004403 mCurrentState.layersSortedByZ.removeAt(idx);
4404 mCurrentState.layersSortedByZ.add(layer);
4405 // we need traversal (state changed)
4406 // AND transaction (list changed)
4407 flags |= eTransactionNeeded|eTraversalNeeded;
4408 }
chaviw8b3871a2017-11-01 17:41:01 -07004409 } else {
4410 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004411 flags |= eTransactionNeeded|eTraversalNeeded;
4412 }
4413 }
chaviw8b3871a2017-11-01 17:41:01 -07004414 }
4415 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004416 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004417 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004418 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4419 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004420 if (p == nullptr) {
4421 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004422 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004423 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004424 mCurrentState.layersSortedByZ.removeAt(idx);
4425 mCurrentState.layersSortedByZ.add(layer);
4426 // we need traversal (state changed)
4427 // AND transaction (list changed)
4428 flags |= eTransactionNeeded|eTraversalNeeded;
4429 }
4430 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004431 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004432 flags |= eTransactionNeeded|eTraversalNeeded;
4433 }
chaviw8b3871a2017-11-01 17:41:01 -07004434 }
4435 }
4436 if (what & layer_state_t::eSizeChanged) {
4437 if (layer->setSize(s.w, s.h)) {
4438 flags |= eTraversalNeeded;
4439 }
4440 }
4441 if (what & layer_state_t::eAlphaChanged) {
4442 if (layer->setAlpha(s.alpha))
4443 flags |= eTraversalNeeded;
4444 }
4445 if (what & layer_state_t::eColorChanged) {
4446 if (layer->setColor(s.color))
4447 flags |= eTraversalNeeded;
4448 }
Peiyong Lind3788632018-09-18 16:01:31 -07004449 if (what & layer_state_t::eColorTransformChanged) {
4450 if (layer->setColorTransform(s.colorTransform)) {
4451 flags |= eTraversalNeeded;
4452 }
4453 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004454 if (what & layer_state_t::eBackgroundColorChanged) {
4455 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4456 flags |= eTraversalNeeded;
4457 }
4458 }
chaviw8b3871a2017-11-01 17:41:01 -07004459 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004460 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004461 }
4462 if (what & layer_state_t::eTransparentRegionChanged) {
4463 if (layer->setTransparentRegionHint(s.transparentRegion))
4464 flags |= eTraversalNeeded;
4465 }
4466 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004467 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004468 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004469 if (what & layer_state_t::eCornerRadiusChanged) {
4470 if (layer->setCornerRadius(s.cornerRadius))
4471 flags |= eTraversalNeeded;
4472 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004473 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004474 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4475 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004476 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004477 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4478 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004479 if (what & layer_state_t::eRenderBorderChanged) {
Tianhao Yao10cea3c2022-03-30 01:37:22 +00004480 if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00004481 flags |= eTraversalNeeded;
4482 }
4483 }
chaviw8b3871a2017-11-01 17:41:01 -07004484 if (what & layer_state_t::eLayerStackChanged) {
4485 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4486 // We only allow setting layer stacks for top level layers,
4487 // everything else inherits layer stack from its parent.
4488 if (layer->hasParent()) {
4489 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004490 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004491 } else if (idx < 0) {
4492 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004493 "that also does not appear in the top level layer list. Something"
4494 " has gone wrong.",
4495 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004496 } else if (layer->setLayerStack(s.layerStack)) {
4497 mCurrentState.layersSortedByZ.removeAt(idx);
4498 mCurrentState.layersSortedByZ.add(layer);
4499 // we need traversal (state changed)
4500 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004501 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004502 }
4503 }
Marissa Wall61c58622018-07-18 10:12:20 -07004504 if (what & layer_state_t::eTransformChanged) {
4505 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4506 }
4507 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4508 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4509 flags |= eTraversalNeeded;
4510 }
4511 if (what & layer_state_t::eCropChanged) {
4512 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4513 }
Marissa Wall61c58622018-07-18 10:12:20 -07004514 if (what & layer_state_t::eDataspaceChanged) {
4515 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4516 }
4517 if (what & layer_state_t::eHdrMetadataChanged) {
4518 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4519 }
4520 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4521 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4522 }
4523 if (what & layer_state_t::eApiChanged) {
4524 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4525 }
4526 if (what & layer_state_t::eSidebandStreamChanged) {
4527 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4528 }
Robert Carr720e5062018-07-30 17:45:14 -07004529 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004530 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4531 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004532 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004533 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004534 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004535 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004536
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004537 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4538 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004539 // The transaction will be received on the Task layer and needs to be applied to all
4540 // child layers. Child layers that are added at a later point will obtain the game mode
4541 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004542 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004543 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004544
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004545 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4546 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004547 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4548 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4549 flags |= eTraversalNeeded;
4550 }
4551 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004552 if (what & layer_state_t::eShadowRadiusChanged) {
4553 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4554 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004555 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004556 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004557 flags |= eTraversalNeeded;
4558 }
4559 }
Steven Thomas3172e202020-01-06 19:25:30 -08004560 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004561 const auto compatibility =
4562 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4563 const auto strategy =
4564 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004565
Robert Carrde6d7b42022-01-07 18:23:06 -08004566 if (layer->setFrameRate(
4567 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4568 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004569 }
Steven Thomas3172e202020-01-06 19:25:30 -08004570 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004571 if (what & layer_state_t::eFixedTransformHintChanged) {
4572 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4573 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4574 }
4575 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004576 if (what & layer_state_t::eAutoRefreshChanged) {
4577 layer->setAutoRefresh(s.autoRefresh);
4578 }
Sally Qi421ffb02022-03-21 19:41:33 -07004579 if (what & layer_state_t::eDimmingEnabledChanged) {
4580 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4581 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004582 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004583 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4584 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004585 }
4586 }
John Reckcdb4ed72021-02-04 13:39:33 -05004587 if (what & layer_state_t::eStretchChanged) {
4588 if (layer->setStretchEffect(s.stretchEffect)) {
4589 flags |= eTraversalNeeded;
4590 }
4591 }
chaviwf3f40fe2021-04-27 15:54:02 -05004592 if (what & layer_state_t::eBufferCropChanged) {
4593 if (layer->setBufferCrop(s.bufferCrop)) {
4594 flags |= eTraversalNeeded;
4595 }
4596 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004597 if (what & layer_state_t::eDestinationFrameChanged) {
4598 if (layer->setDestinationFrame(s.destinationFrame)) {
4599 flags |= eTraversalNeeded;
4600 }
4601 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004602 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004603 if (layer->setDropInputMode(s.dropInputMode)) {
4604 flags |= eTraversalNeeded;
4605 mInputInfoChanged = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004606 }
4607 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004608 // This has to happen after we reparent children because when we reparent to null we remove
4609 // child layers from current state and remove its relative z. If the children are reparented in
4610 // the same transaction, then we have to make sure we reparent the children first so we do not
4611 // lose its relative z order.
4612 if (what & layer_state_t::eReparent) {
4613 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004614 auto parentHandle = (s.parentSurfaceControlForChild)
4615 ? s.parentSurfaceControlForChild->getHandle()
4616 : nullptr;
4617 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004618 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004619 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004620 mCurrentState.layersSortedByZ.remove(layer);
4621 }
4622 flags |= eTransactionNeeded | eTraversalNeeded;
4623 }
4624 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004625 std::vector<sp<CallbackHandle>> callbackHandles;
4626 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4627 for (auto& [listener, callbackIds] : filteredListeners) {
4628 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4629 }
4630 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004631
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004632 if (what & layer_state_t::eBufferChanged) {
4633 std::shared_ptr<renderengine::ExternalTexture> buffer =
4634 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4635 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4636 dequeueBufferTimestamp, frameTimelineInfo)) {
4637 flags |= eTraversalNeeded;
4638 }
Ady Abraham8db10102021-03-15 17:19:23 -07004639 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4640 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004641 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004642
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004643 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004644 // Do not put anything that updates layer state or modifies flags after
4645 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004646 return flags;
4647}
4648
chaviw273171b2018-12-26 11:46:30 -08004649uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004650 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004651 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004652}
4653
Vishnu Nair84125ac2021-12-02 08:47:48 -08004654status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4655 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4656 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004657 if (!mirrorFromHandle) {
4658 return NAME_NOT_FOUND;
4659 }
4660
4661 sp<Layer> mirrorLayer;
4662 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004663 {
4664 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004665 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004666 if (!mirrorFrom) {
4667 return NAME_NOT_FOUND;
4668 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004669 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004670 if (result != NO_ERROR) {
4671 return result;
4672 }
4673
Robert Carr6a0382d2021-07-01 15:57:17 -07004674 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004675 }
4676
Ady Abraham9f0a4002020-10-05 15:47:26 -07004677 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004678 if (mTransactionTracing) {
4679 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4680 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004681 }
4682 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004683 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004684}
4685
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004686status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004687 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4688 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004689 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4690 "Expected only one of parentLayer or parentHandle to be non-null. "
4691 "Programmer error?");
4692
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004693 status_t result = NO_ERROR;
4694
4695 sp<Layer> layer;
4696
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004697 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004698 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004699 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004700 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004701 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4702 if (pendingBufferCounter) {
4703 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004704 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004705 pendingBufferCounter);
4706 }
4707 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004708 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004709 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004710 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004711 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004712 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004713 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004714 default:
4715 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004716 break;
4717 }
4718
Dan Stoza7d89d062015-04-30 13:29:25 -07004719 if (result != NO_ERROR) {
4720 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004721 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004722
Vishnu Nair858a3b42022-01-12 20:42:28 -08004723 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004724 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4725 if (parentHandle != nullptr && parent == nullptr) {
4726 ALOGE("Invalid parent handle %p.", parentHandle.get());
4727 addToRoot = false;
4728 }
4729 if (parentLayer != nullptr) {
4730 addToRoot = false;
4731 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004732
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004733 int parentId = -1;
4734 // We can safely promote the layer in binder thread because we have a strong reference
4735 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4736 sp<Layer> parentSp = parent.promote();
4737 if (parentSp != nullptr) {
4738 parentId = parentSp->getSequence();
4739 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004740 if (mTransactionTracing) {
4741 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4742 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004743 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004744
Vishnu Nair047fb332021-12-09 09:54:36 -08004745 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4746 if (result != NO_ERROR) {
4747 return result;
4748 }
4749
Ady Abraham9f0a4002020-10-05 15:47:26 -07004750 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004751 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004752}
4753
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004754status_t SurfaceFlinger::createBufferQueueLayer(LayerCreationArgs& args, PixelFormat& format,
Evan Roskya1f1e152019-01-24 16:17:46 -08004755 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004756 sp<IGraphicBufferProducer>* gbp,
4757 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004758 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004759 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004760 case PIXEL_FORMAT_TRANSPARENT:
4761 case PIXEL_FORMAT_TRANSLUCENT:
4762 format = PIXEL_FORMAT_RGBA_8888;
4763 break;
4764 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004765 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004766 break;
4767 }
4768
chaviwb4c6e582019-08-16 14:35:07 -07004769 sp<BufferQueueLayer> layer;
chaviwb4c6e582019-08-16 14:35:07 -07004770 args.textureName = getNewTexture();
4771 {
4772 // Grab the SF state lock during this since it's the only safe way to access
4773 // RenderEngine when creating a BufferLayerConsumer
4774 // TODO: Check if this lock is still needed here
4775 Mutex::Autolock lock(mStateLock);
4776 layer = getFactory().createBufferQueueLayer(args);
4777 }
4778
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004779 status_t err = layer->setDefaultBufferProperties(0, 0, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004780 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004781 *handle = layer->getHandle();
4782 *gbp = layer->getProducer();
4783 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004784 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004785
Marissa Wallfd668622018-05-10 10:21:13 -07004786 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004787 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004788}
4789
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004790status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004791 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004792 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004793 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004794 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004795 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004796}
4797
Vishnu Nair84125ac2021-12-02 08:47:48 -08004798status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004799 sp<Layer>* outLayer) {
4800 *outLayer = getFactory().createEffectLayer(args);
4801 *handle = (*outLayer)->getHandle();
4802 return NO_ERROR;
4803}
4804
Vishnu Nair84125ac2021-12-02 08:47:48 -08004805status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004806 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004807 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004808 *handle = (*outLayer)->getHandle();
4809 return NO_ERROR;
4810}
4811
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004812void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004813 mLayersPendingRemoval.add(layer);
4814 mLayersRemoved = true;
4815 setTransactionFlags(eTransactionNeeded);
4816}
4817
Vishnu Nairf9096652021-07-20 18:49:42 -07004818void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004819 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004820 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004821 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004822 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004823 if (mTransactionTracing) {
4824 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004825 }
Rob Carr4bba3702018-10-08 21:53:30 +00004826}
4827
Mathias Agopianb60314a2012-04-10 22:09:54 -07004828// ---------------------------------------------------------------------------
4829
Andy McFadden13a082e2012-08-24 10:16:42 -07004830void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004831 const auto display = getDefaultDisplayDeviceLocked();
4832 if (!display) return;
4833
4834 const sp<IBinder> token = display->getDisplayToken().promote();
4835 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004836
Jesse Hall01e29052013-02-19 16:13:35 -08004837 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004838 Vector<ComposerState> state;
4839 Vector<DisplayState> displays;
4840 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004841 d.what = DisplayState::eDisplayProjectionChanged |
4842 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004843 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004844 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004845 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004846 d.orientedDisplaySpaceRect.makeInvalid();
4847 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004848 d.width = 0;
4849 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004850 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004851
Vishnu Nair9a69a042021-06-18 13:19:49 -07004852 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004853
4854 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004855 // It should be on the main thread, apply it directly.
4856 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004857 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004858 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004859
Peiyong Lin65248e02020-04-18 21:15:07 -07004860 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004861 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004862 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004863 mActiveDisplayTransformHint = display->getTransformHint();
Brian Andersond0010582017-03-07 13:20:31 -08004864 // Use phase of 0 since phase is not known.
4865 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004866 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004867 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004868}
4869
4870void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004871 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004872 static_cast<void>(
4873 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004874}
4875
Peiyong Lin65248e02020-04-18 21:15:07 -07004876void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004877 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004878 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004879 return;
4880 }
4881
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004882 const auto displayId = display->getPhysicalId();
4883 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004884
Peiyong Lin65248e02020-04-18 21:15:07 -07004885 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004886 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004887 return;
4888 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004889
Ady Abraham4f960d12021-10-13 16:59:49 -07004890 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4891 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4892 activeDisplay->isPoweredOn()) {
4893 ALOGW("Trying to change power mode on non active display while the active display is ON");
4894 }
4895
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004896 display->setPowerMode(mode);
4897
Lloyd Pique4dccc412018-01-22 17:21:36 -08004898 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004899 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004900 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004901 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004902 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004903 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004904 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004905 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004906 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004907 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4908 // We can merge the syscall later.
4909 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4910 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4911 }
Martin Liu4a322352020-03-24 21:30:38 +08004912 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4913 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4914 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004915 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004916 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004917 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004918 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004919 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004920 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004921
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004922 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004923 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004924 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004925 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004926 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004927 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4928 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004929 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004930 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4931 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4932 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004933 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004934 mScheduler->disableHardwareVsync(true);
4935 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004936 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004937
Ady Abraham27c70212019-06-11 10:52:26 -07004938 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004939 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004940
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004941 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004942 mVisibleRegionsDirty = true;
4943 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004944 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004945 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004946 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004947 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004948 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004949 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004950 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004951 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004952 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004953 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004954 mScheduler->disableHardwareVsync(true);
4955 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004956 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004957 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004958 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004959 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004960 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004961 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004962
Ady Abrahamadc914c2021-10-13 17:04:27 -07004963 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004964 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004965 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004966 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004967 }
4968
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004969 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004970}
4971
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004972void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004973 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004974 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004975 if (!display) {
4976 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4977 displayToken.get());
4978 } else if (display->isVirtual()) {
4979 ALOGW("Attempt to set power mode %d for virtual display", mode);
4980 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004981 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004982 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004983 });
4984
4985 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004986}
4987
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004988status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004989 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004990
Mathias Agopianbd115332013-04-18 16:41:04 -07004991 IPCThreadState* ipc = IPCThreadState::self();
4992 const int pid = ipc->getCallingPid();
4993 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004994
Mathias Agopianbd115332013-04-18 16:41:04 -07004995 if ((uid != AID_SHELL) &&
4996 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004997 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4998 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004999 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08005000 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005001 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005002 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005003 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07005004 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005005 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005006 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
5007 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
5008 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08005009 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005010 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
5011 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005012 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005013 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005014 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005015 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005016
Dominik Laskowskic2867142019-01-21 11:33:38 -08005017 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005018
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005019 bool dumpLayers = true;
5020 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005021 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005022 if (!lock.locked()) {
5023 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
5024 strerror(-lock.status), lock.status);
5025 }
5026
5027 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
5028 (it->second)(args, asProto, result);
5029 dumpLayers = false;
5030 } else if (!asProto) {
5031 dumpAllLocked(args, result);
5032 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08005033 }
5034
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005035 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005036 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05005037 LayersTraceProto* layersTrace = traceFileProto.add_entry();
5038 LayersProto layersProto = dumpProtoFromMainThread();
5039 layersTrace->mutable_layers()->Swap(&layersProto);
5040 dumpDisplayProto(*layersTrace);
5041
Dominik Laskowski46470112019-08-02 13:13:11 -07005042 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05005043 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07005044 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07005045 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05005046 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07005047 result.append(LayerProtoParser::layerTreeToString(layerTree));
5048 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07005049 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07005050 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07005051 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005052 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005053 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005054 return NO_ERROR;
5055}
5056
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005057status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08005058 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005059 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005060 if (mTransactionTracing) {
5061 mTransactionTracing->writeToFile();
5062 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005063 }
5064
5065 return doDump(fd, DumpArgs(), asProto);
5066}
5067
Dominik Laskowskic2867142019-01-21 11:33:38 -08005068void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005069 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005070 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005071}
5072
Dominik Laskowskic2867142019-01-21 11:33:38 -08005073void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07005074 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005075
Dominik Laskowskic2867142019-01-21 11:33:38 -08005076 if (args.size() > 1) {
5077 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08005078 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005079 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005080 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005081 }
Robert Carr2047fae2016-11-28 14:09:09 -08005082 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005083 } else {
5084 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005085 }
5086}
5087
Dominik Laskowskic2867142019-01-21 11:33:38 -08005088void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005089 const bool clearAll = args.size() < 2;
5090 const auto name = clearAll ? String8() : String8(args[1]);
5091
Edgar Arriaga844fa672020-01-16 14:21:42 -08005092 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005093 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005094 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005095 }
Robert Carr2047fae2016-11-28 14:09:09 -08005096 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005097
Svetoslavd85084b2014-03-20 10:28:31 -07005098 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005099}
5100
Dominik Laskowskic2867142019-01-21 11:33:38 -08005101void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5102 mTimeStats->parseArgs(asProto, args, result);
5103}
5104
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005105void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5106 mFrameTimeline->parseArgs(args, result);
5107}
5108
Jamie Gennis6547ff42013-07-16 20:12:42 -07005109void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005110 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005111 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005112 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005113
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005114 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005115}
5116
Yiwei Zhang5434a782018-12-05 18:06:32 -08005117void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005118 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005119
Yiwei Zhang5434a782018-12-05 18:06:32 -08005120 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5121 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005122 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5123 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005124 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5125 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5126 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005127 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005128}
5129
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005130void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005131 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005132
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005133 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005134 result.append("\n");
5135
Ady Abraham8287e852020-08-12 14:44:58 -07005136 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005137 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005138 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005139 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005140
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005141 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5142 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005143
Ana Krulecc2870422019-01-29 19:00:58 -08005144 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005145 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005146 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5147 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005148}
5149
Dan Stoza269dc4d2021-01-15 15:07:43 -08005150void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5151 for (const auto& [token, display] : mDisplays) {
5152 const auto compositionDisplay = display->getCompositionDisplay();
5153 compositionDisplay->dumpPlannerInfo(args, result);
5154 }
5155}
5156
Yiwei Zhang5434a782018-12-05 18:06:32 -08005157void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5158 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005159 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5160 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005161 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005162 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005163 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005164 }
David Sodman4a36e932017-11-07 14:29:47 -08005165 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005166 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005167 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005168 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5169 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005170}
5171
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005172void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5173 for (const auto& [token, display] : mDisplays) {
5174 display->getCompositionDisplay()->dump(result);
5175 result += '\n';
5176 }
5177}
5178
5179void SurfaceFlinger::dumpDisplays(std::string& result) const {
5180 for (const auto& [token, display] : mDisplays) {
5181 display->dump(result);
5182 result += '\n';
5183 }
5184}
5185
Yiwei Zhang5434a782018-12-05 18:06:32 -08005186void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005187 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005188 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005189 if (!displayId) {
5190 continue;
5191 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005192 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005193 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005194 continue;
5195 }
5196
Yiwei Zhang5434a782018-12-05 18:06:32 -08005197 StringAppendF(&result,
5198 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5199 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005200 uint8_t port;
5201 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005202 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005203 result.append("no identification data\n");
5204 continue;
5205 }
5206
5207 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005208 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005209 continue;
5210 }
5211
5212 const auto edid = parseEdid(data);
5213 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005214 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005215 continue;
5216 }
5217
Yiwei Zhang5434a782018-12-05 18:06:32 -08005218 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005219 result.append(edid->displayName.data(), edid->displayName.length());
5220 result.append("\"\n");
5221 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005222}
5223
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005224void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5225 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005226 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005227 uint8_t port;
5228 DisplayIdentificationData data;
5229
5230 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5231 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5232 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5233 }
5234}
5235
Yiwei Zhang5434a782018-12-05 18:06:32 -08005236void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005237 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005238 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5239 StringAppendF(&result, "DisplayColorSetting: %s\n",
5240 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005241
5242 // TODO: print out if wide-color mode is active or not
5243
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005244 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005245 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005246 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005247 continue;
5248 }
5249
Yiwei Zhang5434a782018-12-05 18:06:32 -08005250 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005251 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005252 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005253 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005254 }
5255
Lloyd Pique32cbe282018-10-19 13:09:22 -07005256 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005257 StringAppendF(&result, " Current color mode: %s (%d)\n",
5258 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005259 }
5260 result.append("\n");
5261}
5262
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005263LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005264 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005265 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005266 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005267 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005268
chaviw1d044282017-09-27 12:19:28 -07005269 return layersProto;
5270}
5271
chaviw0a398992021-08-13 10:13:01 -05005272void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005273 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005274 DisplayProto* displayProto = layersTraceProto.add_displays();
5275 displayProto->set_id(display->getId().value);
5276 displayProto->set_name(display->getDisplayName());
5277 displayProto->set_layer_stack(display->getLayerStack().id);
5278 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5279 [&]() { return displayProto->mutable_size(); });
5280 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5281 return displayProto->mutable_layer_stack_space_rect();
5282 });
5283 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5284 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005285 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005286 }
5287}
5288
Alec Mouri6b9e9912020-01-21 10:50:24 -08005289void SurfaceFlinger::dumpHwc(std::string& result) const {
5290 getHwComposer().dump(result);
5291}
5292
Vishnu Nair0f085c62019-08-30 08:49:12 -07005293void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5294 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5295 // it.
5296 LayerProto* rootProto = layersProto.add_layers();
5297 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5298 rootProto->set_id(offscreenRootLayerId);
5299 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005300 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005301
5302 for (Layer* offscreenLayer : mOffscreenLayers) {
5303 // Add layer as child of the fake root
5304 rootProto->add_children(offscreenLayer->sequence);
5305
5306 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005307 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005308 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005309 }
5310}
5311
Vishnu Nair8406fd72019-07-30 11:29:31 -07005312LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005313 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005314}
5315
Vishnu Nair0f085c62019-08-30 08:49:12 -07005316void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005317 auto future = mScheduler->schedule([this] {
5318 std::string result;
5319 for (Layer* offscreenLayer : mOffscreenLayers) {
5320 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5321 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5322 }
5323 return result;
5324 });
5325
Vishnu Nair0f085c62019-08-30 08:49:12 -07005326 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005327 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005328}
5329
Dominik Laskowskic2867142019-01-21 11:33:38 -08005330void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5331 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005332 Colorizer colorizer(colorize);
5333
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005334 // figure out if we're stuck somewhere
5335 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005336 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005337 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5338
5339 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005340 * Dump library configuration.
5341 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005342
5343 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005344 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005345 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005346 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005347 result.append("\n");
5348
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005349 result.append("\nDisplay identification data:\n");
5350 dumpDisplayIdentificationData(result);
5351
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005352 result.append("\nWide-Color information:\n");
5353 dumpWideColorInfo(result);
5354
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005355 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005356 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005357 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005358 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005359 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005360
Andy McFadden41d67d72014-04-25 16:58:34 -07005361 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005362 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005363 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005364 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005365 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005366
Dan Stozab90cf072015-03-05 11:05:59 -08005367 dumpStaticScreenStats(result);
5368 result.append("\n");
5369
Alec Mouri40189b02019-03-05 15:07:54 -08005370 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5371 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5372 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005373
Andy McFadden4803b742012-09-24 19:07:20 -07005374 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005375 * Dump the visible layer list
5376 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005377 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005378 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005379 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005380
Chia-I Wu2f884132018-09-13 15:17:58 -07005381 {
Lloyd Pique207def92019-02-28 16:09:52 -08005382 StringAppendF(&result, "Composition layers\n");
5383 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005384 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005385 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005386
5387 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5388 layer->getDebugName() ? layer->getDebugName()
5389 : "<unknown>");
5390 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005391 });
5392 }
5393
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005394 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005395 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005396 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005397 dumpDisplays(result);
5398 dumpCompositionDisplays(result);
5399 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005400
5401 mCompositionEngine->dump(result);
5402
5403 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005404 * Dump SurfaceFlinger global state
5405 */
5406
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005407 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005408 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005409 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005410
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005411 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005412
Robert Carrbeba6f02021-02-10 21:06:27 -08005413 result.append("ClientCache state:\n");
5414 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005415 DebugEGLImageTracker::getInstance()->dump(result);
5416
Dominik Laskowski075d3172018-05-24 15:50:06 -07005417 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005418 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5419 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005420 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5421 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005422 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005423 StringAppendF(&result,
5424 " transaction-flags : %08x\n"
5425 " gpu_to_cpu_unsupported : %d\n",
5426 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005427
Marin Shalamanov045b7002021-01-07 16:56:24 +01005428 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005429 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005430 if (const auto activeMode = display->getActiveMode()) {
5431 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005432
5433 const auto dpi = activeMode->getDpi();
5434 xDpi = base::StringPrintf("%.2f", dpi.x);
5435 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005436 } else {
5437 fps = "unknown";
5438 xDpi = "unknown";
5439 yDpi = "unknown";
5440 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005441 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005442 " refresh-rate : %s\n"
5443 " x-dpi : %s\n"
5444 " y-dpi : %s\n",
5445 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005446 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005447
Yiwei Zhang5434a782018-12-05 18:06:32 -08005448 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005449
Dan Stozae22aec72016-08-01 13:20:59 -07005450 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005451 * Tracing state
5452 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005453 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005454
5455 result.append("\nTransaction tracing: ");
5456 if (mTransactionTracing) {
5457 result.append("enabled\n");
5458 mTransactionTracing->dump(result);
5459 } else {
5460 result.append("disabled\n");
5461 }
5462 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005463
5464 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005465 * HWC layer minidump
5466 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005467 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005468 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005469 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005470 continue;
5471 }
5472
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005473 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5474 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005475 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005476
5477 const DisplayDevice& ref = *display;
5478 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005479 result.append("\n");
5480 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005481
Ady Abraham2790e9f2021-04-28 13:14:20 -07005482 {
5483 DumpArgs plannerArgs;
5484 plannerArgs.add(); // first argument is ignored
5485 plannerArgs.add(String16("--layers"));
5486 dumpPlannerInfo(plannerArgs, result);
5487 }
5488
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005489 /*
5490 * Dump HWComposer state
5491 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005492 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005493 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005494 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005495 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005496 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005497 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005498
5499 /*
5500 * Dump gralloc state
5501 */
5502 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5503 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005504
rnleea2ecd832021-07-29 13:58:30 -07005505 /*
5506 * Dump flag/property manager state
5507 */
Robert Carr9b623c32022-03-21 15:55:22 -07005508 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005509
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005510 result.append(mTimeStats->miniDump());
5511 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005512}
5513
chaviw17ac24b2021-01-28 18:50:05 -08005514mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5515 if (saturation == 1) {
5516 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005517 }
5518
chaviw17ac24b2021-01-28 18:50:05 -08005519 float3 luminance{0.213f, 0.715f, 0.072f};
5520 luminance *= 1.0f - saturation;
5521 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5522 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5523 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5524 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5525 return saturationMatrix;
5526}
5527
5528void SurfaceFlinger::updateColorMatrixLocked() {
5529 mat4 colorMatrix =
5530 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5531
Chia-I Wu28f320b2018-05-03 11:02:56 -07005532 if (mCurrentState.colorMatrix != colorMatrix) {
5533 mCurrentState.colorMatrix = colorMatrix;
5534 mCurrentState.colorMatrixChanged = true;
5535 setTransactionFlags(eTransactionNeeded);
5536 }
5537}
5538
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005539status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005540#pragma clang diagnostic push
5541#pragma clang diagnostic error "-Wswitch-enum"
5542 switch (static_cast<ISurfaceComposerTag>(code)) {
5543 // These methods should at minimum make sure that the client requested
5544 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005545 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005546 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005547 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005548 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005549 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5550 // permission dynamically. Don't use the permission cache for this check.
5551 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005552 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005553 IPCThreadState* ipc = IPCThreadState::self();
5554 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5555 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005556 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005557 }
Robert Carr1db73f62016-12-21 12:58:51 -08005558 return OK;
5559 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005560 // The following calls are currently used by clients that do not
5561 // request necessary permissions. However, they do not expose any secret
5562 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005563 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005564 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005565 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005566 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005567 // Calling setTransactionState is safe, because you need to have been
5568 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005569 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005570 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005571 return OK;
5572 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005573 case BOOT_FINISHED:
5574 // Used by apps to hook Choreographer to SurfaceFlinger.
5575 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005576 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005577 case CREATE_DISPLAY:
5578 case DESTROY_DISPLAY:
5579 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5580 case GET_PHYSICAL_DISPLAY_IDS:
5581 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005582 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005583 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005584 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005585 case GET_DISPLAY_STATE:
5586 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005587 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005588 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005589 case GET_DISPLAY_NATIVE_PRIMARIES:
5590 case SET_ACTIVE_COLOR_MODE:
5591 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005592 case CLEAR_BOOT_DISPLAY_MODE:
5593 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5594 case SET_AUTO_LOW_LATENCY_MODE:
5595 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005596 case CAPTURE_LAYERS:
5597 case CAPTURE_DISPLAY:
5598 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005599 case CLEAR_ANIMATION_FRAME_STATS:
5600 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005601 case OVERRIDE_HDR_TYPES:
5602 case ON_PULL_ATOM:
5603 case ENABLE_VSYNC_INJECTIONS:
5604 case INJECT_VSYNC:
5605 case GET_LAYER_DEBUG_INFO:
5606 case GET_COLOR_MANAGEMENT:
5607 case GET_COMPOSITION_PREFERENCE:
5608 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5609 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005610 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005611 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005612 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005613 case ADD_REGION_SAMPLING_LISTENER:
5614 case REMOVE_REGION_SAMPLING_LISTENER:
5615 case ADD_FPS_LISTENER:
5616 case REMOVE_FPS_LISTENER:
5617 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5618 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5619 case ADD_WINDOW_INFOS_LISTENER:
5620 case REMOVE_WINDOW_INFOS_LISTENER:
5621 case SET_DESIRED_DISPLAY_MODE_SPECS:
5622 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005623 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5624 case SET_DISPLAY_BRIGHTNESS:
5625 case ADD_HDR_LAYER_INFO_LISTENER:
5626 case REMOVE_HDR_LAYER_INFO_LISTENER:
5627 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005628 case SET_GLOBAL_SHADOW_SETTINGS:
5629 case GET_DISPLAY_DECORATION_SUPPORT:
5630 case SET_FRAME_RATE:
5631 case SET_OVERRIDE_FRAME_RATE:
5632 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005633 case ADD_TRANSACTION_TRACE_LISTENER:
5634 case GET_GPU_CONTEXT_PRIORITY:
5635 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005636 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005637 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005638 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005639
5640 // These codes are used for the IBinder protocol to either interrogate the recipient
5641 // side of the transaction for its canonical interface descriptor or to dump its state.
5642 // We let them pass by default.
5643 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5644 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5645 code == IBinder::SYSPROPS_TRANSACTION) {
5646 return OK;
5647 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005648 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005649 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005650 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005651 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5652 return OK;
5653 }
5654 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5655 return PERMISSION_DENIED;
5656#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005657}
5658
Ana Krulec13be8ad2018-08-21 02:43:56 +00005659status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5660 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005661 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5662 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005663 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005664
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005665 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5666 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005667 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005668 IPCThreadState* ipc = IPCThreadState::self();
5669 const int uid = ipc->getCallingUid();
5670 if (CC_UNLIKELY(uid != AID_SYSTEM
5671 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005672 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005673 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005674 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005675 return PERMISSION_DENIED;
5676 }
5677 int n;
5678 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005679 case 1000: // Unused.
5680 case 1001:
5681 return NAME_NOT_FOUND;
5682 case 1002: // Toggle flashing on surface damage.
5683 if (const int delay = data.readInt32(); delay > 0) {
5684 mDebugFlashDelay = delay;
5685 } else {
5686 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5687 }
5688 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005689 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005690 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005691 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005692 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005693 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005694 case 1005: { // Force commit ahead of next VSYNC.
5695 Mutex::Autolock lock(mStateLock);
5696 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5697 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005698 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005699 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005700 case 1007: // Unused.
5701 return NAME_NOT_FOUND;
5702 case 1008: // Toggle forced GPU composition.
5703 mDebugDisableHWC = data.readInt32() != 0;
5704 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005705 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005706 case 1009: // Toggle use of transform hint.
5707 mDebugDisableTransformHint = data.readInt32() != 0;
5708 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005709 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005710 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005711 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005712 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005713 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005714 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005715 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005716 return NO_ERROR;
5717 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005718 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005719 if (!display) {
5720 return NAME_NOT_FOUND;
5721 }
5722
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005723 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005724 return NO_ERROR;
5725 }
5726 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005727 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005728 // daltonize
5729 n = data.readInt32();
5730 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005731 case 1:
5732 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5733 break;
5734 case 2:
5735 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5736 break;
5737 case 3:
5738 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5739 break;
5740 default:
5741 mDaltonizer.setType(ColorBlindnessType::None);
5742 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005743 }
5744 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005745 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005746 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005747 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005748 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005749
5750 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005751 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005752 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005753 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005754 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005755 // apply a color matrix
5756 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005757 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005758 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005759 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005760 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005761 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005762 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005763 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005764 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005765 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005766 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005767
5768 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5769 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005770 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005771 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5772 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5773 }
5774
Chia-I Wu28f320b2018-05-03 11:02:56 -07005775 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005776 return NO_ERROR;
5777 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005778 case 1016: { // Unused.
5779 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005780 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005781 case 1017: {
5782 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005783 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005784 return NO_ERROR;
5785 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005786 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005787 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005788 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005789 return NO_ERROR;
5790 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005791 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005792 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005793 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005794 return NO_ERROR;
5795 }
Irvel468051e2016-06-13 16:44:44 -07005796 case 1020: { // Layer updates interceptor
5797 n = data.readInt32();
5798 if (n) {
5799 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005800 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005801 }
5802 else{
5803 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005804 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005805 }
5806 return NO_ERROR;
5807 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005808 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005809 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005810 static_cast<void>(
5811 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005812 return NO_ERROR;
5813 }
Romain Guy0147a172017-06-01 13:53:56 -07005814 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005815 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005816 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005817
Chia-I Wu28f320b2018-05-03 11:02:56 -07005818 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005819 return NO_ERROR;
5820 }
Romain Guy54f154a2017-10-24 21:40:32 +01005821 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005822 int32_t colorMode;
5823
Chia-I Wu0d711262018-05-21 15:19:35 -07005824 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005825 if (data.readInt32(&colorMode) == NO_ERROR) {
5826 mForceColorMode = static_cast<ColorMode>(colorMode);
5827 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005828 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005829 return NO_ERROR;
5830 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005831 // Deprecate, use 1030 to check whether the device is color managed.
5832 case 1024: {
5833 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005834 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005835 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005836 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005837 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005838 if (n == 1) {
5839 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005840 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005841 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005842 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005843 int64_t startingTime =
5844 (fixedStartingTime) ? fixedStartingTime : systemTime();
5845 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005846 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005847 mLayerTracing.notify("start", startingTime);
5848 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005849 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005850 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005851 } else if (n == 2) {
5852 std::string filename = std::string(data.readCString());
5853 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5854 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005855 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005856 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005857 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005858 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005859 mTracingEnabledChanged = tracingEnabledChanged;
5860 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005861 return NO_ERROR;
5862 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005863 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005864 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005865 return NO_ERROR;
5866 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005867 // Is a DisplayColorSetting supported?
5868 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005869 const auto display = getDefaultDisplayDevice();
5870 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005871 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005872 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005873
5874 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5875 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005876 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005877 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005878 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005879 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005880 reply->writeBool(true);
5881 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005882 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005883 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005884 break;
5885 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005886 reply->writeBool(
5887 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005888 break;
5889 }
5890 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005891 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005892 case 1028: { // Unused.
5893 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005894 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005895 // Set buffer size for SF tracing (value in KB)
5896 case 1029: {
5897 n = data.readInt32();
5898 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5899 ALOGW("Invalid buffer size: %d KB", n);
5900 reply->writeInt32(BAD_VALUE);
5901 return BAD_VALUE;
5902 }
5903
5904 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005905 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005906 reply->writeInt32(NO_ERROR);
5907 return NO_ERROR;
5908 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005909 // Is device color managed?
5910 case 1030: {
5911 reply->writeBool(useColorManagement);
5912 return NO_ERROR;
5913 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005914 // Override default composition data space
5915 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5916 // && adb shell stop zygote && adb shell start zygote
5917 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5918 // adb shell stop zygote && adb shell start zygote
5919 case 1031: {
5920 Mutex::Autolock _l(mStateLock);
5921 n = data.readInt32();
5922 if (n) {
5923 n = data.readInt32();
5924 if (n) {
5925 Dataspace dataspace = static_cast<Dataspace>(n);
5926 if (!validateCompositionDataspace(dataspace)) {
5927 return BAD_VALUE;
5928 }
5929 mDefaultCompositionDataspace = dataspace;
5930 }
5931 n = data.readInt32();
5932 if (n) {
5933 Dataspace dataspace = static_cast<Dataspace>(n);
5934 if (!validateCompositionDataspace(dataspace)) {
5935 return BAD_VALUE;
5936 }
5937 mWideColorGamutCompositionDataspace = dataspace;
5938 }
5939 } else {
5940 // restore composition data space.
5941 mDefaultCompositionDataspace = defaultCompositionDataspace;
5942 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5943 }
5944 return NO_ERROR;
5945 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005946 // Set trace flags
5947 case 1033: {
5948 n = data.readUint32();
5949 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005950 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005951 reply->writeInt32(NO_ERROR);
5952 return NO_ERROR;
5953 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005954 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005955 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005956 switch (n = data.readInt32()) {
5957 case 0:
5958 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005959 FTL_FAKE_GUARD(mStateLock,
5960 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005961 break;
5962 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005963 reply->writeBool(
5964 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005965 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005966 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005967 });
5968
5969 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005970 return NO_ERROR;
5971 }
Ady Abraham34392f72019-04-10 11:29:27 -07005972 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005973 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005974
Dominik Laskowskif1833852021-03-23 15:06:50 -07005975 const auto display = [&]() -> sp<IBinder> {
5976 uint64_t value;
5977 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005978 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005979 }
5980
Dominik Laskowskif1833852021-03-23 15:06:50 -07005981 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5982 return getPhysicalDisplayToken(*id);
5983 }
5984
5985 ALOGE("Invalid physical display ID");
5986 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005987 }();
5988
Shiyong Li2bcece92021-08-30 20:38:50 +00005989 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005990 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005991 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5992 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005993 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005994 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5995 // manager frame rate policy a new policy which allows switching between all refresh
5996 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005997 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005998 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005999 return mScheduler
6000 ->schedule([this] {
6001 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006002 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006003
Dominik Laskowski756b7892021-08-04 12:53:59 -07006004 // This is a little racy, but not in a way that hurts anything. As
6005 // we grab the defaultMode from the display manager policy, we could
6006 // be setting a new display manager policy, leaving us using a stale
6007 // defaultMode. The defaultMode doesn't matter for the override
6008 // policy though, since we set allowGroupSwitching to true, so it's
6009 // not a problem.
6010 scheduler::RefreshRateConfigs::Policy overridePolicy;
6011 overridePolicy.defaultMode = display->refreshRateConfigs()
6012 .getDisplayManagerPolicy()
6013 .defaultMode;
6014 overridePolicy.allowGroupSwitching = true;
6015 constexpr bool kOverridePolicy = true;
6016 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
6017 kOverridePolicy);
6018 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006019 .get();
6020 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07006021 return mScheduler
6022 ->schedule([this] {
6023 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006024 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07006025 constexpr bool kOverridePolicy = true;
6026 return setDesiredDisplayModeSpecsInternal(display, {},
6027 kOverridePolicy);
6028 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006029 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07006030 }
Ady Abraham07e54702020-04-16 15:05:37 -07006031 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02006032 // Inject a hotplug connected event for the primary display. This will deallocate and
6033 // reallocate the display state including framebuffers.
6034 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006035 const hal::HWDisplayId hwcId =
6036 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
6037
6038 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02006039 return NO_ERROR;
6040 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07006041 // Modify the max number of display frames stored within FrameTimeline
6042 case 1038: {
6043 n = data.readInt32();
6044 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
6045 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
6046 return BAD_VALUE;
6047 }
6048 if (n == 0) {
6049 // restore to default
6050 mFrameTimeline->reset();
6051 return NO_ERROR;
6052 }
6053 mFrameTimeline->setMaxDisplayFrames(n);
6054 return NO_ERROR;
6055 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07006056 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07006057 PhysicalDisplayId displayId = [&]() {
6058 Mutex::Autolock lock(mStateLock);
6059 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6060 }();
6061
6062 auto inUid = static_cast<uid_t>(data.readInt32());
6063 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08006064 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
6065 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07006066 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08006067 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006068 // Toggle caching feature
6069 // First argument is an int32 - nonzero enables caching and zero disables caching
6070 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6071 // caching to a particular physical display
6072 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006073 auto future = mScheduler->schedule([&] {
6074 n = data.readInt32();
6075 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6076 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6077 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6078 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6079 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6080 return NAME_NOT_FOUND;
6081 }
6082 }
6083 {
6084 Mutex::Autolock lock(mStateLock);
6085 mLayerCachingEnabled = n != 0;
6086 for (const auto& [_, display] : mDisplays) {
6087 if (!inputId || *inputId == display->getPhysicalId()) {
6088 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006089 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006090 }
6091 }
6092 return OK;
6093 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006094
Dominik Laskowski756b7892021-08-04 12:53:59 -07006095 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006096 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006097 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006098 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006099 return NO_ERROR;
6100 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006101 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006102 if (mTransactionTracing) {
6103 if (data.readInt32()) {
6104 // Transaction tracing is always running but allow the user to temporarily
6105 // increase the buffer when actively debugging.
6106 mTransactionTracing->setBufferSize(
6107 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6108 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006109 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006110 mTransactionTracing->setBufferSize(
6111 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006112 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006113 }
6114 reply->writeInt32(NO_ERROR);
6115 return NO_ERROR;
6116 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006117 case 1042: { // Write layers trace or transaction trace to file
6118 if (mTransactionTracing) {
6119 mTransactionTracing->writeToFile();
6120 }
6121 if (mLayerTracingEnabled) {
6122 mLayerTracing.writeToFile();
6123 }
6124 reply->writeInt32(NO_ERROR);
6125 return NO_ERROR;
6126 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006127 }
6128 }
6129 return err;
6130}
6131
Ady Abrahama09852a2020-02-20 14:23:42 -08006132void SurfaceFlinger::kernelTimerChanged(bool expired) {
6133 static bool updateOverlay =
6134 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006135 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006136
6137 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006138 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006139 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006140 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006141 if (!display) {
6142 ALOGW("%s: default display is null", __func__);
6143 return;
6144 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006145 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006146
6147 const auto desiredActiveMode = display->getDesiredActiveMode();
6148 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6149 ? std::make_optional(desiredActiveMode->mode->getId())
6150 : std::nullopt;
6151
6152 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6153
Ady Abraham1b11bc62021-06-03 19:51:19 -07006154 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006155 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006156 }
6157 }));
6158}
6159
ramindani32cf0602022-03-02 02:30:29 +00006160std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6161SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6162 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6163 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6164 const auto timeout = getIdleTimerTimeout(displayId);
6165 if (isKernelIdleTimerHwcSupported) {
6166 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6167 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6168 // In order to decide if we can use the HWC api for idle timer
6169 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6170 // without relying on hasDisplayCapability.
6171 // hasDisplayCapability relies on DisplayCapabilities
6172 // which are updated after we set the PowerMode::ON.
6173 // DISPLAY_IDLE_TIMER is a display driver property
6174 // and is available before the PowerMode::ON
6175 return {KernelIdleTimerController::HwcApi, timeout};
6176 }
6177 return {std::nullopt, timeout};
6178 }
6179 if (getKernelIdleTimerSyspropConfig(displayId)) {
6180 return {KernelIdleTimerController::Sysprop, timeout};
6181 }
6182
6183 return {std::nullopt, timeout};
6184}
6185
6186void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6187 KernelIdleTimerController controller,
6188 PhysicalDisplayId displayId) {
6189 switch (controller) {
6190 case KernelIdleTimerController::HwcApi: {
6191 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6192 break;
6193 }
6194 case KernelIdleTimerController::Sysprop: {
6195 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6196 break;
6197 }
6198 }
6199}
6200
Ana Krulecb9afd792020-06-11 13:16:15 -07006201void SurfaceFlinger::toggleKernelIdleTimer() {
6202 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6203
Ady Abraham3efa3942021-06-24 19:01:25 -07006204 const auto display = getDefaultDisplayDeviceLocked();
6205 if (!display) {
6206 ALOGW("%s: default display is null", __func__);
6207 return;
6208 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006209
Ady Abrahame9316b72021-09-24 17:04:36 -07006210 // If the support for kernel idle timer is disabled for the active display,
6211 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006212 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6213 display->refreshRateConfigs().kernelIdleTimerController();
6214 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006215 return;
6216 }
6217
Ady Abraham3efa3942021-06-24 19:01:25 -07006218 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006219
Ana Krulecb9afd792020-06-11 13:16:15 -07006220 switch (action) {
6221 case KernelIdleTimerAction::TurnOff:
6222 if (mKernelIdleTimerEnabled) {
6223 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006224 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6225 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6226 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006227 mKernelIdleTimerEnabled = false;
6228 }
6229 break;
6230 case KernelIdleTimerAction::TurnOn:
6231 if (!mKernelIdleTimerEnabled) {
6232 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006233 const std::chrono::milliseconds timeout =
6234 display->refreshRateConfigs().getIdleTimerTimeout();
6235 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6236 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006237 mKernelIdleTimerEnabled = true;
6238 }
6239 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006240 }
6241}
6242
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006243// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6244class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006245public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006246 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6247 ~WindowDisconnector() {
6248 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006249 }
6250
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006251private:
6252 ANativeWindow* mWindow;
6253 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006254};
6255
chaviw93df2ea2019-04-30 16:45:12 -07006256static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6257 switch (colorMode) {
6258 case ColorMode::DISPLAY_P3:
6259 case ColorMode::BT2100_PQ:
6260 case ColorMode::BT2100_HLG:
6261 case ColorMode::DISPLAY_BT2020:
6262 return Dataspace::DISPLAY_P3;
6263 default:
6264 return Dataspace::V0_SRGB;
6265 }
6266}
6267
chaviwf5bb97b2021-04-28 15:35:37 -05006268static bool hasCaptureBlackoutContentPermission() {
6269 IPCThreadState* ipc = IPCThreadState::self();
6270 const int pid = ipc->getCallingPid();
6271 const int uid = ipc->getCallingUid();
6272 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6273 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6274}
6275
chaviw4b9d5e12020-08-04 18:30:35 -07006276static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6277 IPCThreadState* ipc = IPCThreadState::self();
6278 const int pid = ipc->getCallingPid();
6279 const int uid = ipc->getCallingUid();
6280 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6281 return OK;
6282 }
6283
6284 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6285 // itself, we allow it to continue.
6286 if (captureArgs.uid == uid) {
6287 return OK;
6288 }
6289
6290 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6291 return PERMISSION_DENIED;
6292}
6293
Peiyong Lin05cc0112020-10-14 16:16:37 -07006294status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6295 static constexpr int kFifoPriority = 2;
6296 static constexpr int kOtherPriority = 0;
6297
6298 struct sched_param param = {0};
6299 int sched_policy;
6300 if (enabled) {
6301 sched_policy = SCHED_FIFO;
6302 param.sched_priority = kFifoPriority;
6303 } else {
6304 sched_policy = SCHED_OTHER;
6305 param.sched_priority = kOtherPriority;
6306 }
6307
6308 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6309 return -errno;
6310 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006311
6312 return NO_ERROR;
6313}
6314
6315status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6316 static const unsigned int kUclampMin =
6317 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6318
6319 if (!kUclampMin) {
6320 // uclamp.min set to 0 (default), skip setting
6321 return NO_ERROR;
6322 }
6323
6324 // Currently, there is no wrapper in bionic: b/183240349.
6325 struct sched_attr {
6326 uint32_t size;
6327 uint32_t sched_policy;
6328 uint64_t sched_flags;
6329 int32_t sched_nice;
6330 uint32_t sched_priority;
6331 uint64_t sched_runtime;
6332 uint64_t sched_deadline;
6333 uint64_t sched_period;
6334 uint32_t sched_util_min;
6335 uint32_t sched_util_max;
6336 };
6337
6338 sched_attr attr = {};
6339 attr.size = sizeof(attr);
6340
6341 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6342 attr.sched_util_min = enabled ? kUclampMin : 0;
6343 attr.sched_util_max = 1024;
6344
6345 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6346 return -errno;
6347 }
6348
Peiyong Lin05cc0112020-10-14 16:16:37 -07006349 return NO_ERROR;
6350}
6351
chaviwd2432892020-07-24 17:42:39 -07006352status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006353 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006354 ATRACE_CALL();
6355
chaviw4b9d5e12020-08-04 18:30:35 -07006356 status_t validate = validateScreenshotPermissions(args);
6357 if (validate != OK) {
6358 return validate;
6359 }
6360
chaviwd2432892020-07-24 17:42:39 -07006361 if (!args.displayToken) return BAD_VALUE;
6362
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006363 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006364 ui::LayerStack layerStack;
6365 ui::Size reqSize(args.width, args.height);
6366 ui::Dataspace dataspace;
6367 {
6368 Mutex::Autolock lock(mStateLock);
6369 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6370 if (!display) return NAME_NOT_FOUND;
6371 displayWeak = display;
6372 layerStack = display->getLayerStack();
6373
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006374 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006375 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006376 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006377 }
6378
arthurhung79e81aa2020-08-28 00:09:19 +08006379 // The dataspace is depended on the color mode of display, that could use non-native mode
6380 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6381 // and failed if display is not in native mode. This provide a way to force using native
6382 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006383 dataspace = args.dataspace;
6384 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006385 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6386 dataspace = pickDataspaceFromColorMode(colorMode);
6387 }
chaviwd2432892020-07-24 17:42:39 -07006388 }
6389
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006390 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006391 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006392 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006393 });
6394
chaviw4b9d5e12020-08-04 18:30:35 -07006395 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6396 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006397 };
chaviw03900772020-08-18 12:34:51 -07006398
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006399 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6400 args.pixelFormat, args.allowProtected, args.grayscale,
6401 captureListener);
6402 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006403}
6404
Dominik Laskowskif1833852021-03-23 15:06:50 -07006405status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006406 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006407 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006408 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006409 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006410 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006411 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006412 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006413
Dominik Laskowskif1833852021-03-23 15:06:50 -07006414 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006415 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006416 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006417 }
6418
chaviw93df2ea2019-04-30 16:45:12 -07006419 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006420 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006421 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006422
chaviw426b5c02020-07-27 11:20:15 -07006423 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006424 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6425 }
6426
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006427 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006428 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006429 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006430 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006431 });
chaviw93df2ea2019-04-30 16:45:12 -07006432
Marin Shalamanov1c434292020-06-12 01:47:29 +02006433 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006434 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006435 };
6436
Sally Qi59a9f502021-10-12 18:53:23 +00006437 if (captureListener == nullptr) {
6438 ALOGE("capture screen must provide a capture listener callback");
6439 return BAD_VALUE;
6440 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006441
6442 constexpr bool kAllowProtected = false;
6443 constexpr bool kGrayscale = false;
6444
6445 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6446 ui::PixelFormat::RGBA_8888, kAllowProtected, kGrayscale,
6447 captureListener);
6448 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006449}
6450
chaviw3efadb12020-07-27 10:07:15 -07006451status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006452 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006453 ATRACE_CALL();
6454
chaviw4b9d5e12020-08-04 18:30:35 -07006455 status_t validate = validateScreenshotPermissions(args);
6456 if (validate != OK) {
6457 return validate;
6458 }
6459
Marin Shalamanov1c434292020-06-12 01:47:29 +02006460 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006461 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006462 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006463 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006464 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006465
6466 // Call this before holding mStateLock to avoid any deadlocking.
6467 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6468
Robert Carrc0df3122019-04-11 13:18:21 -07006469 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006470 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006471
Vishnu Nairf9096652021-07-20 18:49:42 -07006472 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006473 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006474 ALOGE("captureLayers called with an invalid or removed parent");
6475 return NAME_NOT_FOUND;
6476 }
6477
chaviwf5bb97b2021-04-28 15:35:37 -05006478 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006479 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006480 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6481 return PERMISSION_DENIED;
6482 }
6483
Robert Carr6a160312021-05-17 12:08:20 -07006484 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006485 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006486 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006487 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006488 }
6489
chaviw3efadb12020-07-27 10:07:15 -07006490 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006491 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006492 crop.bottom = parentSourceBounds.getHeight();
6493 }
6494
chaviw17ac24b2021-01-28 18:50:05 -08006495 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006496 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6497 // crop was not specified, or an invalid frame scale was provided.
6498 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006499 }
chaviw17ac24b2021-01-28 18:50:05 -08006500 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006501
chaviw3efadb12020-07-27 10:07:15 -07006502 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006503 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006504 if (excludeLayer != nullptr) {
6505 excludeLayers.emplace(excludeLayer);
6506 } else {
6507 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6508 return NAME_NOT_FOUND;
6509 }
6510 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006511
arthurhung79e81aa2020-08-28 00:09:19 +08006512 // The dataspace is depended on the color mode of display, that could use non-native mode
6513 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6514 // and failed if display is not in native mode. This provide a way to force using native
6515 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006516 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006517 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006518
Chia-I Wu20261cb2018-08-23 12:55:44 -07006519 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006520 if (reqSize.width <= 0 || reqSize.height <= 0) {
6521 ALOGW("Failed to captureLayes: crop or scale too small");
6522 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006523 }
6524
chaviw79468ab2021-10-27 11:11:24 -05006525 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006526 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006527 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006528 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006529 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006530 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006531 });
6532
chaviw03900772020-08-18 12:34:51 -07006533 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006534 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6535 if (!layer->isVisible()) {
6536 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006537 } else if (args.childrenOnly && layer == parent.get()) {
6538 return;
6539 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006540 return;
chaviwa76b2712017-09-20 12:02:26 -07006541 }
Robert Carr866455f2019-04-02 16:28:26 -07006542
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006543 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006544 while (p != nullptr) {
6545 if (excludeLayers.count(p) != 0) {
6546 return;
6547 }
6548 p = p->getParent();
6549 }
6550
chaviwa76b2712017-09-20 12:02:26 -07006551 visitor(layer);
6552 });
6553 };
Robert Carr108b2c72019-04-02 16:32:58 -07006554
Sally Qi59a9f502021-10-12 18:53:23 +00006555 if (captureListener == nullptr) {
6556 ALOGE("capture screen must provide a capture listener callback");
6557 return BAD_VALUE;
6558 }
6559
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006560 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6561 args.pixelFormat, args.allowProtected, args.grayscale,
6562 captureListener);
6563 return fenceStatus(future.get());
chaviwa76b2712017-09-20 12:02:26 -07006564}
6565
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006566ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Sally Qi59a9f502021-10-12 18:53:23 +00006567 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6568 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6569 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006570 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006571
Garfield Tan9c9c1912021-07-19 12:02:16 -07006572 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6573 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6574 ") that exceeds render target size limit.",
6575 bufferSize.getWidth(), bufferSize.getHeight());
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006576 return ftl::yield<FenceResult>(base::unexpected(BAD_VALUE)).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006577 }
6578
Peiyong Lin05cc0112020-10-14 16:16:37 -07006579 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6580 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6581 // A protected layer has no implication on whether it's secure, which is explicitly set by
6582 // application to avoid being screenshot or drawn via unsecure display.
6583 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6584 bool hasProtectedLayer = false;
6585 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006586 auto future = mScheduler->schedule([=]() {
6587 bool protectedLayerFound = false;
6588 traverseLayers([&](Layer* layer) {
6589 protectedLayerFound =
6590 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6591 });
6592 return protectedLayerFound;
6593 });
6594 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006595 }
6596
Richard Liucbcb8952020-04-08 10:51:55 +00006597 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6598 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006599 (hasProtectedLayer && allowProtected && supportsProtected
6600 ? GRALLOC_USAGE_PROTECTED
6601 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006602 sp<GraphicBuffer> buffer =
6603 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6604 static_cast<android_pixel_format>(reqPixelFormat),
6605 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006606
6607 const status_t bufferStatus = buffer->initCheck();
6608 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6609 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006610 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6611 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6612 renderengine::impl::ExternalTexture::Usage::
6613 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006614 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006615 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006616}
6617
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006618ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006619 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6620 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6621 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006622 ATRACE_CALL();
6623
chaviwf5bb97b2021-04-28 15:35:37 -05006624 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006625
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006626 auto future = mScheduler->schedule([=, renderAreaFuture = std::move(renderAreaFuture)]() mutable
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006627 -> ftl::SharedFuture<FenceResult> {
chaviw03900772020-08-18 12:34:51 -07006628 ScreenCaptureResults captureResults;
6629 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6630 if (!renderArea) {
6631 ALOGW("Skipping screen capture because of invalid render area.");
6632 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006633 captureListener->onScreenCaptureCompleted(captureResults);
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006634 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
chaviw03900772020-08-18 12:34:51 -07006635 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006636
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006637 ftl::SharedFuture<FenceResult> renderFuture;
chaviw03900772020-08-18 12:34:51 -07006638 renderArea->render([&] {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006639 renderFuture =
6640 renderScreenImpl(*renderArea, traverseLayers, buffer, canCaptureBlackoutContent,
6641 regionSampling, grayscale, captureResults);
chaviw03900772020-08-18 12:34:51 -07006642 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006643
6644 if (captureListener) {
6645 // TODO: The future returned by std::async blocks the main thread. Return a chain of
6646 // futures to the Binder thread instead.
Sally Qi59a9f502021-10-12 18:53:23 +00006647 std::async([=]() mutable {
6648 ATRACE_NAME("captureListener is nonnull!");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006649 auto fenceResult = renderFuture.get();
6650 // TODO(b/232535621): Change ScreenCaptureResults to store a FenceResult.
6651 captureResults.result = fenceStatus(fenceResult);
6652 captureResults.fence = std::move(fenceResult).value_or(Fence::NO_FENCE);
Sally Qi59a9f502021-10-12 18:53:23 +00006653 captureListener->onScreenCaptureCompleted(captureResults);
6654 });
6655 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006656 return renderFuture;
Sally Qi59a9f502021-10-12 18:53:23 +00006657 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006658
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006659 if (captureListener) {
6660 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
Sally Qi59a9f502021-10-12 18:53:23 +00006661 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006662
6663 // Flatten nested futures.
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006664 auto chain = ftl::Future(std::move(future)).then([](ftl::SharedFuture<FenceResult> future) {
6665 return future;
6666 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006667
6668 return chain.share();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006669}
6670
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006671ftl::SharedFuture<FenceResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006672 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006673 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6674 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6675 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006676 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006677
chaviw426b5c02020-07-27 11:20:15 -07006678 traverseLayers([&](Layer* layer) {
6679 captureResults.capturedSecureLayers =
6680 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6681 });
6682
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006683 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006684
chaviw426b5c02020-07-27 11:20:15 -07006685 // We allow the system server to take screenshots of secure layers for
6686 // use in situations like the Screen-rotation animation and place
6687 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006688 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006689 ALOGW("FB is protected: PERMISSION_DENIED");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006690 return ftl::yield<FenceResult>(base::unexpected(PERMISSION_DENIED)).share();
chaviw426b5c02020-07-27 11:20:15 -07006691 }
6692
Alec Mouria90a5702021-04-16 16:36:21 +00006693 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006694 auto dataspace = renderArea.getReqDataSpace();
6695 auto parent = renderArea.getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00006696 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07006697 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
6698 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
6699
Robert Carr12a3b9b2022-03-10 09:55:29 -08006700 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6701 Mutex::Autolock lock(mStateLock);
6702 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6703 return display.getLayerStack() == layerStack;
6704 });
6705 if (!display) {
6706 // If the layer is not on a display, use the dataspace for the default display.
6707 display = getDefaultDisplayDeviceLocked();
6708 }
6709
6710 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6711 dataspace = pickDataspaceFromColorMode(colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00006712 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07006713 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
6714 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08006715 }
6716 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006717
chaviwa76b2712017-09-20 12:02:26 -07006718 const auto reqWidth = renderArea.getReqWidth();
6719 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006720 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006721 const auto transform = renderArea.getTransform();
6722 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006723 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006724
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006725 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006726 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006727
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006728 // assume that bounds are never offset, and that they are the same as the
6729 // buffer bounds.
6730 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006731 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006732 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006733
Robert Carr12a3b9b2022-03-10 09:55:29 -08006734 clientCompositionDisplay.outputDataspace = dataspace;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006735 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006736 clientCompositionDisplay.renderIntent =
6737 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006738
chaviw17ac24b2021-01-28 18:50:05 -08006739 const float colorSaturation = grayscale ? 0 : 1;
6740 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6741
chaviw50da5042018-04-09 13:49:37 -07006742 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006743
Vishnu Nair9b079a22020-01-21 14:36:08 -08006744 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006745 fillLayer.source.buffer.buffer = nullptr;
6746 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006747 fillLayer.geometry.boundaries =
6748 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006749 fillLayer.alpha = half(alpha);
6750 clientCompositionLayers.push_back(fillLayer);
6751
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006752 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006753 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006754 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006755 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006756 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006757
Lloyd Piquef16688f2019-02-19 17:47:57 -08006758 Region clip(renderArea.getBounds());
6759 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6760 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006761 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006762 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006763 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006764 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006765 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006766 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006767 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006768 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006769 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6770 BlurSetting::Disabled
6771 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6772 BlurSetting::Enabled,
Sally Qidb653012022-05-04 13:12:22 -07006773 isHdrLayer(layer) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006774
Lloyd Piquef16688f2019-02-19 17:47:57 -08006775 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006776 std::vector<compositionengine::LayerFE::LayerSettings> results =
6777 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006778 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006779 for (auto& settings : results) {
6780 settings.geometry.positionTransform =
6781 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006782 // There's no need to process blurs when we're executing region sampling,
6783 // we're just trying to understand what we're drawing, and doing so without
6784 // blurs is already a pretty good approximation.
6785 if (regionSampling) {
6786 settings.backgroundBlurRadius = 0;
6787 }
Sally Qidb653012022-05-04 13:12:22 -07006788 captureResults.capturedHdrLayers |= isHdrLayer(layer);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006789 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006790
Yichi Chen40773d92020-04-01 10:10:18 +08006791 clientCompositionLayers.insert(clientCompositionLayers.end(),
6792 std::make_move_iterator(results.begin()),
6793 std::make_move_iterator(results.end()));
6794 renderedLayers.push_back(layer);
6795 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006796
chaviwa76b2712017-09-20 12:02:26 -07006797 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006798
Sally Qi59a9f502021-10-12 18:53:23 +00006799 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6800 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006801 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006802 std::back_inserter(clientRenderEngineLayers),
6803 [](compositionengine::LayerFE::LayerSettings& settings)
6804 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006805
Alec Mouri6338c9d2019-02-07 16:57:51 -08006806 // Use an empty fence for the buffer fence, since we just created the buffer so
6807 // there is no need for synchronization with the GPU.
6808 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006809 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006810
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006811 constexpr bool kUseFramebufferCache = false;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006812 auto chain =
6813 ftl::Future(getRenderEngine().drawLayers(clientCompositionDisplay,
6814 clientRenderEngineLayers, buffer,
6815 kUseFramebufferCache, std::move(bufferFence)))
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006816 .then(&toFenceResult);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006817
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006818 const auto future = chain.share();
Sally Qi59a9f502021-10-12 18:53:23 +00006819 for (auto* layer : renderedLayers) {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006820 layer->onLayerDisplayed(future);
Yichi Chen40773d92020-04-01 10:10:18 +08006821 }
Ady Abraham99599942021-01-27 20:27:23 -08006822
Peiyong Lin05cc0112020-10-14 16:16:37 -07006823 // Always switch back to unprotected context.
6824 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006825
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006826 return future;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006827}
6828
chaviwbf023a62021-06-07 16:00:06 -05006829void SurfaceFlinger::windowInfosReported() {
chaviw95ef3c42019-02-14 10:55:09 -08006830 Mutex::Autolock _l(mStateLock);
Arthur Hung2274a312021-04-28 15:13:06 +00006831 signalSynchronousTransactions(CountDownLatch::eSyncInputWindows);
chaviw95ef3c42019-02-14 10:55:09 -08006832}
chaviw5f21a5e2019-02-14 10:00:34 -08006833
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006834// ---------------------------------------------------------------------------
6835
Edgar Arriaga844fa672020-01-16 14:21:42 -08006836void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6837 layersSortedByZ.traverse(visitor);
6838}
6839
Dan Stoza412903f2017-04-27 13:42:17 -07006840void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6841 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006842}
6843
Dan Stoza412903f2017-04-27 13:42:17 -07006844void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6845 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006846}
6847
chaviw4b9d5e12020-08-04 18:30:35 -07006848void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006849 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006850 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006851 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006852 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006853 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006854 continue;
6855 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006856 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006857 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006858 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006859 return;
6860 }
chaviwa76b2712017-09-20 12:02:26 -07006861 if (!layer->isVisible()) {
6862 return;
6863 }
chaviw4b9d5e12020-08-04 18:30:35 -07006864 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6865 return;
6866 }
chaviwa76b2712017-09-20 12:02:26 -07006867 visitor(layer);
6868 });
6869 }
6870}
6871
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006872status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006873 const sp<DisplayDevice>& display,
6874 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006875 Mutex::Autolock lock(mStateLock);
6876
Ady Abrahamfb853662021-04-09 11:46:40 -07006877 if (mDebugDisplayModeSetByBackdoor) {
6878 // ignore this request as mode is overridden by backdoor
6879 return NO_ERROR;
6880 }
6881
Ady Abraham3efa3942021-06-24 19:01:25 -07006882 status_t setPolicyResult = overridePolicy
6883 ? display->refreshRateConfigs().setOverridePolicy(policy)
6884 : display->refreshRateConfigs().setDisplayManagerPolicy(*policy);
6885 if (setPolicyResult < 0) {
6886 return BAD_VALUE;
6887 }
6888 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6889 return NO_ERROR;
6890 }
6891
Ady Abraham3efa3942021-06-24 19:01:25 -07006892 scheduler::RefreshRateConfigs::Policy currentPolicy =
6893 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006894
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006895 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006896
Ana Krulecb9afd792020-06-11 13:16:15 -07006897 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6898 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006899 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006900 if (isDisplayActiveLocked(display)) {
6901 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6902 toggleKernelIdleTimer();
6903 } else {
6904 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6905 }
Ady Abraham838de062019-02-04 10:24:03 -08006906
Ady Abraham690f4612021-07-01 23:24:03 -07006907 const DisplayModePtr preferredDisplayMode = [&] {
6908 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6909 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6910 return schedulerMode;
6911 }
6912
6913 return display->getMode(currentPolicy.defaultMode);
6914 }();
6915
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006916 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006917 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006918
Ady Abraham690f4612021-07-01 23:24:03 -07006919 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006920 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006921 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006922 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006923 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006924 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006925 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006926 }
6927
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006928 return NO_ERROR;
6929}
6930
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006931status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6932 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6933 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6934 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006935 ATRACE_CALL();
6936
6937 if (!displayToken) {
6938 return BAD_VALUE;
6939 }
6940
Dominik Laskowski756b7892021-08-04 12:53:59 -07006941 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006942 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006943 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006944 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006945 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006946 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006947 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006948 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006949 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006950 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006951 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006952 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006953 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006954 {Fps::fromValue(primaryRefreshRateMin),
6955 Fps::fromValue(primaryRefreshRateMax)},
6956 {Fps::fromValue(appRequestRefreshRateMin),
6957 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006958 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006959
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006960 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006961 }
6962 });
6963
6964 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006965}
6966
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006967status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6968 ui::DisplayModeId* outDefaultMode,
6969 bool* outAllowGroupSwitching,
6970 float* outPrimaryRefreshRateMin,
6971 float* outPrimaryRefreshRateMax,
6972 float* outAppRequestRefreshRateMin,
6973 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006974 ATRACE_CALL();
6975
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006976 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006977 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006978 return BAD_VALUE;
6979 }
6980
6981 Mutex::Autolock lock(mStateLock);
6982 const auto display = getDisplayDeviceLocked(displayToken);
6983 if (!display) {
6984 return NAME_NOT_FOUND;
6985 }
6986
Ady Abraham3efa3942021-06-24 19:01:25 -07006987 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006988 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006989 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006990
6991 scheduler::RefreshRateConfigs::Policy policy =
6992 display->refreshRateConfigs().getDisplayManagerPolicy();
6993 *outDefaultMode = policy.defaultMode.value();
6994 *outAllowGroupSwitching = policy.allowGroupSwitching;
6995 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6996 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6997 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6998 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6999 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07007000}
7001
Vishnu Nairf9096652021-07-20 18:49:42 -07007002wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
7003 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07007004}
7005
Dominik Laskowski75848362019-11-11 17:57:20 -08007006void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007007 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07007008 if (!layer->isRemovedFromCurrentState()) {
7009 mScheduler->registerLayer(layer);
7010 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007011}
7012
7013void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
7014 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07007015 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07007016 if (!layer->isRemovedFromCurrentState()) {
7017 mScheduler->deregisterLayer(layer);
7018 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08007019 if (mTransactionTracing) {
7020 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08007021 }
Valerie Hauc5686802019-11-22 14:18:09 -08007022}
7023
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007024void SurfaceFlinger::onLayerUpdate() {
7025 scheduleCommit(FrameHint::kActive);
7026}
7027
Valerie Hauc5686802019-11-22 14:18:09 -08007028// WARNING: ONLY CALL THIS FROM LAYER DTOR
7029// Here we add children in the current state to offscreen layers and remove the
7030// layer itself from the offscreen layer list. Since
7031// this is the dtor, it is safe to access the current state. This keeps us
7032// from dangling children layers such that they are not reachable from the
7033// Drawing state nor the offscreen layer list
7034// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07007035void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08007036 for (auto& child : layer->getCurrentChildren()) {
7037 mOffscreenLayers.emplace(child.get());
7038 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007039 mOffscreenLayers.erase(layer);
7040}
7041
Robert Carr867be372021-06-29 17:36:02 -07007042void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
7043 mOffscreenLayers.erase(layer);
7044}
7045
Vishnu Nair08f6eae2019-11-26 14:01:39 -08007046status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
7047 float lightPosY, float lightPosZ,
7048 float lightRadius) {
7049 Mutex::Autolock _l(mStateLock);
7050 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
7051 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
7052 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
7053 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
7054 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
7055
7056 // these values are overridden when calculating the shadow settings for a layer.
7057 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
7058 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08007059 return NO_ERROR;
7060}
7061
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007062const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
7063 const {
7064 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
7065 // on the work to remove the table in that bug rather than adding more to
7066 // it.
7067 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007068 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
7069 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007070 };
7071 return genericLayerMetadataKeyMap;
7072}
7073
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007074status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7075 PhysicalDisplayId displayId = [&]() {
7076 Mutex::Autolock lock(mStateLock);
7077 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7078 }();
7079
7080 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7081 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7082 return NO_ERROR;
7083}
7084
Dominik Laskowski20134642020-04-20 22:36:44 -07007085void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007086 for (const auto& [ignored, display] : mDisplays) {
7087 if (display->isInternal()) {
7088 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007089 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007090 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007091}
7092
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007093status_t SurfaceFlinger::addTransactionTraceListener(
7094 const sp<gui::ITransactionTraceListener>& listener) {
7095 if (!listener) {
7096 return BAD_VALUE;
7097 }
7098
7099 mInterceptor->addTransactionTraceListener(listener);
7100
7101 return NO_ERROR;
7102}
7103
Huihong Luo02186fb2022-02-23 14:21:54 -08007104int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007105 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007106}
7107
Ady Abraham899dcdb2021-06-15 16:56:21 -07007108int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7109 std::chrono::nanoseconds presentLatency) {
7110 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7111 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007112 pipelineDepth++;
7113 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007114 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007115}
7116
Ady Abraham899dcdb2021-06-15 16:56:21 -07007117status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007118 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007119
7120 if (!getHwComposer().isHeadless()) {
7121 if (const auto display = getDefaultDisplayDevice()) {
7122 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007123 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007124 }
7125
7126 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007127 return NO_ERROR;
7128}
7129
rnleeed20fa42021-08-10 18:00:03 -07007130uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007131 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007132
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007133 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7134 refreshRate = *frameRateOverride;
7135 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007136 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007137 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007138 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007139 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007140
Ady Abraham899dcdb2021-06-15 16:56:21 -07007141 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7142}
7143
7144int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7145 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7146 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7147 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7148}
7149
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007150void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state) {
7151 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007152 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007153 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7154 return;
arthurhungdba591c2021-02-08 17:28:49 +08007155 }
7156
7157 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007158 bool addToRoot = state.addToRoot;
7159 if (state.initialParent != nullptr) {
7160 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007161 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007162 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007163 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007164 }
arthurhungdba591c2021-02-08 17:28:49 +08007165 }
7166
Garfield Tand712ad32021-10-27 13:44:22 -07007167 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007168 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007169 mCurrentState.layersSortedByZ.add(layer);
7170 } else if (parent == nullptr) {
7171 layer->onRemovedFromCurrentState();
7172 } else if (parent->isRemovedFromCurrentState()) {
7173 parent->addChild(layer);
7174 layer->onRemovedFromCurrentState();
7175 } else {
7176 parent->addChild(layer);
7177 }
7178
Ady Abraham1273ac12021-08-26 17:31:53 -07007179 layer->updateTransformHint(mActiveDisplayTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +08007180
Arthur Hung23e07502021-10-15 11:58:19 +00007181 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007182}
Ady Abraham562c2712021-05-07 15:10:42 -07007183
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007184void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007185 if (!mLumaSampling || !mRegionSamplingThread) {
7186 return;
7187 }
7188
Dominik Laskowski756b7892021-08-04 12:53:59 -07007189 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007190}
7191
Ady Abrahamed3290f2021-05-17 15:12:14 -07007192void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7193 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7194 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7195}
7196
7197void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7198 ATRACE_CALL();
7199
Ady Abrahamdb036a82021-07-16 14:18:34 -07007200 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7201 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7202 }
7203
Ady Abrahamed3290f2021-05-17 15:12:14 -07007204 if (!activeDisplay) {
7205 ALOGE("%s: activeDisplay is null", __func__);
7206 return;
7207 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007208 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007209 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007210 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007211 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007212 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007213 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007214 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007215
7216 // Update the kernel timer for the current active display, since the policy
7217 // for this display might have changed when it was not the active display.
7218 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007219}
7220
chaviw60c9d3e2021-06-04 12:52:17 -05007221status_t SurfaceFlinger::addWindowInfosListener(
7222 const sp<IWindowInfosListener>& windowInfosListener) const {
7223 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7224 return NO_ERROR;
7225}
7226
7227status_t SurfaceFlinger::removeWindowInfosListener(
7228 const sp<IWindowInfosListener>& windowInfosListener) const {
7229 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7230 return NO_ERROR;
7231}
7232
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007233std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7234 const BufferData& bufferData, const char* layerName) const {
7235 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7236 bool bufferSizeExceedsLimit = false;
7237 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7238 if (cacheIdChanged && bufferData.buffer != nullptr) {
7239 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7240 bufferData.buffer->getHeight());
7241 if (!bufferSizeExceedsLimit) {
7242 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7243 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7244 }
7245 } else if (cacheIdChanged) {
7246 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7247 } else if (bufferData.buffer != nullptr) {
7248 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7249 bufferData.buffer->getHeight());
7250 if (!bufferSizeExceedsLimit) {
7251 buffer = std::make_shared<
7252 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7253 renderengine::impl::ExternalTexture::
7254 Usage::READABLE);
7255 }
7256 }
7257 ALOGE_IF(bufferSizeExceedsLimit,
7258 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7259 "limit.",
7260 layerName);
7261 return buffer;
7262}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007263
7264bool SurfaceFlinger::commitCreatedLayers() {
7265 std::vector<LayerCreatedState> createdLayers;
7266 {
7267 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7268 createdLayers = std::move(mCreatedLayers);
7269 mCreatedLayers.clear();
7270 if (createdLayers.size() == 0) {
7271 return false;
7272 }
7273 }
7274
7275 Mutex::Autolock _l(mStateLock);
7276 for (const auto& createdLayer : createdLayers) {
7277 handleLayerCreatedLocked(createdLayer);
7278 }
7279 createdLayers.clear();
7280 mLayersAdded = true;
7281 return true;
7282}
Huihong Luof5029222021-12-16 14:33:46 -08007283
7284// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007285
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007286binder::Status SurfaceComposerAIDL::bootFinished() {
7287 status_t status = checkAccessPermission();
7288 if (status != OK) {
7289 return binderStatusFromStatusT(status);
7290 }
7291 mFlinger->bootFinished();
7292 return binder::Status::ok();
7293}
7294
7295binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7296 VsyncSource vsyncSource, EventRegistration eventRegistration,
7297 sp<IDisplayEventConnection>* outConnection) {
7298 sp<IDisplayEventConnection> conn =
7299 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration);
7300 if (conn == nullptr) {
7301 *outConnection = nullptr;
7302 return binderStatusFromStatusT(BAD_VALUE);
7303 } else {
7304 *outConnection = conn;
7305 return binder::Status::ok();
7306 }
7307}
7308
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007309binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
7310 const sp<Client> client = new Client(mFlinger);
7311 if (client->initCheck() == NO_ERROR) {
7312 *outClient = client;
7313 return binder::Status::ok();
7314 } else {
7315 *outClient = nullptr;
7316 return binderStatusFromStatusT(BAD_VALUE);
7317 }
7318}
7319
Huihong Luo07e72362022-02-14 14:26:04 -08007320binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7321 sp<IBinder>* outDisplay) {
7322 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007323 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007324 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007325 }
Huihong Luo37396db2022-02-15 10:43:00 -08007326 String8 displayName8 = String8::format("%s", displayName.c_str());
7327 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7328 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007329}
7330
7331binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7332 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007333 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007334 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007335 }
Huihong Luo37396db2022-02-15 10:43:00 -08007336 mFlinger->destroyDisplay(display);
7337 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007338}
7339
7340binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7341 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7342 std::vector<int64_t> displayIds;
7343 displayIds.reserve(physicalDisplayIds.size());
7344 for (auto item : physicalDisplayIds) {
7345 displayIds.push_back(static_cast<int64_t>(item.value));
7346 }
7347 *outDisplayIds = displayIds;
7348 return binder::Status::ok();
7349}
7350
7351binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7352 status_t status = checkAccessPermission();
7353 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007354 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007355 }
7356
7357 PhysicalDisplayId id;
7358 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7359 if (status == NO_ERROR) {
7360 *outDisplayId = id.value;
7361 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007362 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007363}
7364
7365binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7366 sp<IBinder>* outDisplay) {
7367 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7368 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7369 return binder::Status::ok();
7370}
7371
Huihong Luo37396db2022-02-15 10:43:00 -08007372binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7373 status_t status = checkAccessPermission();
7374 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007375 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007376 }
7377 mFlinger->setPowerMode(display, mode);
7378 return binder::Status::ok();
7379}
7380
Huihong Luo0a81aa32022-02-22 16:02:36 -08007381binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7382 std::vector<FrameEvent>* outSupported) {
7383 status_t status;
7384 if (!outSupported) {
7385 status = UNEXPECTED_NULL;
7386 } else {
7387 outSupported->clear();
7388 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7389 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007390 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007391}
7392
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007393binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7394 gui::DisplayStatInfo* outStatInfo) {
7395 DisplayStatInfo statInfo;
7396 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7397 if (status == NO_ERROR) {
7398 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7399 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7400 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007401 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007402}
7403
7404binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7405 gui::DisplayState* outState) {
7406 ui::DisplayState state;
7407 status_t status = mFlinger->getDisplayState(display, &state);
7408 if (status == NO_ERROR) {
7409 outState->layerStack = state.layerStack.id;
7410 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7411 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7412 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7413 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007414 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007415}
7416
Huihong Luoa79ddf42022-02-17 00:01:38 -08007417binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7418 gui::StaticDisplayInfo* outInfo) {
7419 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7420 ui::StaticDisplayInfo info;
7421 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7422 if (status == NO_ERROR) {
7423 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7424 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7425 outInfo->density = info.density;
7426 outInfo->secure = info.secure;
7427 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7428
7429 gui::DeviceProductInfo dinfo;
7430 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7431 dinfo.name = std::move(dpi->name);
7432 dinfo.manufacturerPnpId =
7433 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7434 dinfo.productId = dpi->productId;
7435 if (const auto* model =
7436 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7437 gui::DeviceProductInfo::ModelYear modelYear;
7438 modelYear.year = model->year;
7439 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7440 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7441 &dpi->manufactureOrModelDate)) {
7442 gui::DeviceProductInfo::ManufactureYear date;
7443 date.modelYear.year = manufacture->year;
7444 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7445 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7446 &dpi->manufactureOrModelDate)) {
7447 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7448 date.manufactureYear.modelYear.year = manufacture->year;
7449 date.week = manufacture->week;
7450 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7451 }
7452
7453 outInfo->deviceProductInfo = dinfo;
7454 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007455 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007456}
7457
Huihong Luo38603fd2022-02-21 14:32:54 -08007458binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7459 gui::DynamicDisplayInfo* outInfo) {
7460 ui::DynamicDisplayInfo info;
7461 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7462 if (status == NO_ERROR) {
7463 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7464 outInfo->supportedDisplayModes.clear();
7465 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7466 for (const auto& mode : info.supportedDisplayModes) {
7467 gui::DisplayMode outMode;
7468 outMode.id = mode.id;
7469 outMode.resolution.width = mode.resolution.width;
7470 outMode.resolution.height = mode.resolution.height;
7471 outMode.xDpi = mode.xDpi;
7472 outMode.yDpi = mode.yDpi;
7473 outMode.refreshRate = mode.refreshRate;
7474 outMode.appVsyncOffset = mode.appVsyncOffset;
7475 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7476 outMode.presentationDeadline = mode.presentationDeadline;
7477 outMode.group = mode.group;
7478 outInfo->supportedDisplayModes.push_back(outMode);
7479 }
7480
7481 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7482
7483 outInfo->supportedColorModes.clear();
7484 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7485 for (const auto& cmode : info.supportedColorModes) {
7486 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7487 }
7488
7489 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7490
7491 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7492 hdrCapabilities.supportedHdrTypes.clear();
7493 hdrCapabilities.supportedHdrTypes.reserve(
7494 info.hdrCapabilities.getSupportedHdrTypes().size());
7495 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7496 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7497 }
7498 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7499 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7500 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7501
7502 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7503 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7504 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7505 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007506 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007507}
7508
Huihong Luoca3d9a42022-02-22 11:07:34 -08007509binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7510 gui::DisplayPrimaries* outPrimaries) {
7511 ui::DisplayPrimaries primaries;
7512 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7513 if (status == NO_ERROR) {
7514 outPrimaries->red.X = primaries.red.X;
7515 outPrimaries->red.Y = primaries.red.Y;
7516 outPrimaries->red.Z = primaries.red.Z;
7517
7518 outPrimaries->green.X = primaries.green.X;
7519 outPrimaries->green.Y = primaries.green.Y;
7520 outPrimaries->green.Z = primaries.green.Z;
7521
7522 outPrimaries->blue.X = primaries.blue.X;
7523 outPrimaries->blue.Y = primaries.blue.Y;
7524 outPrimaries->blue.Z = primaries.blue.Z;
7525
7526 outPrimaries->white.X = primaries.white.X;
7527 outPrimaries->white.Y = primaries.white.Y;
7528 outPrimaries->white.Z = primaries.white.Z;
7529 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007530 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007531}
7532
7533binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7534 status_t status = checkAccessPermission();
7535 if (status == OK) {
7536 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7537 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007538 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007539}
7540
7541binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7542 int displayModeId) {
7543 status_t status = checkAccessPermission();
7544 if (status == OK) {
7545 status = mFlinger->setBootDisplayMode(display,
7546 static_cast<ui::DisplayModeId>(displayModeId));
7547 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007548 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007549}
7550
Huihong Luo37396db2022-02-15 10:43:00 -08007551binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7552 status_t status = checkAccessPermission();
7553 if (status == OK) {
7554 status = mFlinger->clearBootDisplayMode(display);
7555 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007556 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007557}
7558
7559binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7560 status_t status = checkAccessPermission();
7561 if (status == OK) {
7562 status = mFlinger->getBootDisplayModeSupport(outMode);
7563 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007564 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007565}
7566
7567binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7568 status_t status = checkAccessPermission();
7569 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007570 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007571 }
7572 mFlinger->setAutoLowLatencyMode(display, on);
7573 return binder::Status::ok();
7574}
7575
7576binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7577 status_t status = checkAccessPermission();
7578 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007579 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007580 }
7581 mFlinger->setGameContentType(display, on);
7582 return binder::Status::ok();
7583}
7584
Huihong Luof5029222021-12-16 14:33:46 -08007585binder::Status SurfaceComposerAIDL::captureDisplay(
7586 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7587 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007588 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007589}
7590
7591binder::Status SurfaceComposerAIDL::captureDisplayById(
7592 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7593 status_t status;
7594 IPCThreadState* ipc = IPCThreadState::self();
7595 const int uid = ipc->getCallingUid();
7596 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7597 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7598 status = mFlinger->captureDisplay(*id, captureListener);
7599 } else {
7600 status = PERMISSION_DENIED;
7601 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007602 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007603}
7604
7605binder::Status SurfaceComposerAIDL::captureLayers(
7606 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7607 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007608 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007609}
7610
Huihong Luo4ed1c912022-02-22 14:30:01 -08007611binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7612 status_t status = checkAccessPermission();
7613 if (status == OK) {
7614 status = mFlinger->clearAnimationFrameStats();
7615 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007616 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007617}
7618
7619binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7620 status_t status = checkAccessPermission();
7621 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007622 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007623 }
7624
7625 FrameStats stats;
7626 status = mFlinger->getAnimationFrameStats(&stats);
7627 if (status == NO_ERROR) {
7628 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7629 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7630 for (const auto& t : stats.desiredPresentTimesNano) {
7631 outStats->desiredPresentTimesNano.push_back(t);
7632 }
7633 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7634 for (const auto& t : stats.actualPresentTimesNano) {
7635 outStats->actualPresentTimesNano.push_back(t);
7636 }
7637 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7638 for (const auto& t : stats.frameReadyTimesNano) {
7639 outStats->frameReadyTimesNano.push_back(t);
7640 }
7641 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007642 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007643}
7644
Huihong Luo05539a12022-02-23 10:29:40 -08007645binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7646 const std::vector<int32_t>& hdrTypes) {
7647 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7648 // permission dynamically. Don't use the permission cache for this check.
7649 status_t status = checkAccessPermission(false);
7650 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007651 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007652 }
7653
7654 std::vector<ui::Hdr> hdrTypesVector;
7655 for (int32_t i : hdrTypes) {
7656 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7657 }
7658 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007659 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007660}
7661
7662binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7663 status_t status;
7664 const int uid = IPCThreadState::self()->getCallingUid();
7665 if (uid != AID_SYSTEM) {
7666 status = PERMISSION_DENIED;
7667 } else {
7668 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7669 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007670 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007671}
7672
7673binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7674 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007675 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007676 }
7677
7678 status_t status = checkAccessPermission();
7679 if (status == OK) {
7680 status = mFlinger->enableVSyncInjections(enable);
7681 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007682 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007683}
7684
7685binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7686 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007687 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007688 }
7689
7690 status_t status = checkAccessPermission();
7691 if (status == OK) {
7692 status = mFlinger->injectVSync(when);
7693 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007694 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007695}
7696
7697binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7698 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007699 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007700 }
7701
7702 IPCThreadState* ipc = IPCThreadState::self();
7703 const int pid = ipc->getCallingPid();
7704 const int uid = ipc->getCallingUid();
7705 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7706 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007707 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007708 }
7709 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007710 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007711}
7712
7713binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7714 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007715 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007716}
7717
7718binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7719 ui::Dataspace dataspace;
7720 ui::PixelFormat pixelFormat;
7721 ui::Dataspace wideColorGamutDataspace;
7722 ui::PixelFormat wideColorGamutPixelFormat;
7723 status_t status =
7724 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7725 &wideColorGamutPixelFormat);
7726 if (status == NO_ERROR) {
7727 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7728 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7729 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7730 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7731 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007732 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007733}
7734
7735binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7736 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7737 status_t status = checkAccessPermission();
7738 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007739 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007740 }
7741
7742 ui::PixelFormat format;
7743 ui::Dataspace dataspace;
7744 uint8_t componentMask;
7745 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7746 &componentMask);
7747 if (status == NO_ERROR) {
7748 outAttrs->format = static_cast<int32_t>(format);
7749 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7750 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7751 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007752 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007753}
7754
7755binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7756 bool enable,
7757 int8_t componentMask,
7758 int64_t maxFrames) {
7759 status_t status = checkAccessPermission();
7760 if (status == OK) {
7761 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7762 static_cast<uint8_t>(componentMask),
7763 static_cast<uint64_t>(maxFrames));
7764 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007765 return binderStatusFromStatusT(status);
7766}
7767
7768binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7769 int64_t maxFrames, int64_t timestamp,
7770 gui::DisplayedFrameStats* outStats) {
7771 if (!outStats) {
7772 return binderStatusFromStatusT(BAD_VALUE);
7773 }
7774
7775 status_t status = checkAccessPermission();
7776 if (status != OK) {
7777 return binderStatusFromStatusT(status);
7778 }
7779
7780 DisplayedFrameStats stats;
7781 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7782 static_cast<uint64_t>(timestamp), &stats);
7783 if (status == NO_ERROR) {
7784 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7785 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7786 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7787 for (const auto& s : stats.component_0_sample) {
7788 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7789 }
7790 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7791 for (const auto& s : stats.component_1_sample) {
7792 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7793 }
7794 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7795 for (const auto& s : stats.component_2_sample) {
7796 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7797 }
7798 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7799 for (const auto& s : stats.component_3_sample) {
7800 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7801 }
7802 }
7803 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007804}
7805
7806binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7807 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007808 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007809}
7810
Huihong Luo37396db2022-02-15 10:43:00 -08007811binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7812 bool* outIsWideColorDisplay) {
7813 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007814 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007815}
7816
Huihong Luo02186fb2022-02-23 14:21:54 -08007817binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7818 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7819 const sp<gui::IRegionSamplingListener>& listener) {
7820 status_t status = checkReadFrameBufferPermission();
7821 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007822 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007823 }
7824 android::Rect rect;
7825 rect.left = samplingArea.left;
7826 rect.top = samplingArea.top;
7827 rect.right = samplingArea.right;
7828 rect.bottom = samplingArea.bottom;
7829 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007830 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007831}
7832
7833binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7834 const sp<gui::IRegionSamplingListener>& listener) {
7835 status_t status = checkReadFrameBufferPermission();
7836 if (status == OK) {
7837 status = mFlinger->removeRegionSamplingListener(listener);
7838 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007839 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007840}
7841
7842binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7843 const sp<gui::IFpsListener>& listener) {
7844 status_t status = checkReadFrameBufferPermission();
7845 if (status == OK) {
7846 status = mFlinger->addFpsListener(taskId, listener);
7847 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007848 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007849}
7850
7851binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7852 status_t status = checkReadFrameBufferPermission();
7853 if (status == OK) {
7854 status = mFlinger->removeFpsListener(listener);
7855 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007856 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007857}
7858
7859binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7860 const sp<gui::ITunnelModeEnabledListener>& listener) {
7861 status_t status = checkAccessPermission();
7862 if (status == OK) {
7863 status = mFlinger->addTunnelModeEnabledListener(listener);
7864 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007865 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007866}
7867
7868binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7869 const sp<gui::ITunnelModeEnabledListener>& listener) {
7870 status_t status = checkAccessPermission();
7871 if (status == OK) {
7872 status = mFlinger->removeTunnelModeEnabledListener(listener);
7873 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007874 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007875}
7876
7877binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7878 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7879 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7880 float appRequestRefreshRateMax) {
7881 status_t status = checkAccessPermission();
7882 if (status == OK) {
7883 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7884 static_cast<ui::DisplayModeId>(defaultMode),
7885 allowGroupSwitching, primaryRefreshRateMin,
7886 primaryRefreshRateMax,
7887 appRequestRefreshRateMin,
7888 appRequestRefreshRateMax);
7889 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007890 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007891}
7892
7893binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7894 gui::DisplayModeSpecs* outSpecs) {
7895 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007896 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007897 }
7898
7899 status_t status = checkAccessPermission();
7900 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007901 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007902 }
7903
7904 ui::DisplayModeId displayModeId;
7905 bool allowGroupSwitching;
7906 float primaryRefreshRateMin;
7907 float primaryRefreshRateMax;
7908 float appRequestRefreshRateMin;
7909 float appRequestRefreshRateMax;
7910 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7911 &allowGroupSwitching, &primaryRefreshRateMin,
7912 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7913 &appRequestRefreshRateMax);
7914 if (status == NO_ERROR) {
7915 outSpecs->defaultMode = displayModeId;
7916 outSpecs->allowGroupSwitching = allowGroupSwitching;
7917 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7918 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7919 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7920 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7921 }
7922
Huihong Luo3bdef862022-03-03 11:57:19 -08007923 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007924}
7925
Huihong Luo37396db2022-02-15 10:43:00 -08007926binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7927 bool* outSupport) {
7928 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007929 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007930}
7931
7932binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7933 const gui::DisplayBrightness& brightness) {
7934 status_t status = checkControlDisplayBrightnessPermission();
7935 if (status == OK) {
7936 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7937 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007938 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007939}
7940
7941binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7942 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7943 status_t status = checkControlDisplayBrightnessPermission();
7944 if (status == OK) {
7945 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7946 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007947 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007948}
7949
7950binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7951 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7952 status_t status = checkControlDisplayBrightnessPermission();
7953 if (status == OK) {
7954 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7955 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007956 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007957}
7958
7959binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7960 status_t status = checkAccessPermission();
7961 if (status == OK) {
7962 status = mFlinger->notifyPowerBoost(boostId);
7963 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007964 return binderStatusFromStatusT(status);
7965}
7966
7967binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7968 const gui::Color& spotColor,
7969 float lightPosY, float lightPosZ,
7970 float lightRadius) {
7971 status_t status = checkAccessPermission();
7972 if (status != OK) {
7973 return binderStatusFromStatusT(status);
7974 }
7975
7976 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7977 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7978 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7979 lightPosZ, lightRadius);
7980 return binderStatusFromStatusT(status);
7981}
7982
7983binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7984 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7985 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7986 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7987 if (status != NO_ERROR) {
7988 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7989 return binderStatusFromStatusT(status);
7990 }
7991
7992 if (!support || !support.has_value()) {
7993 outSupport->reset();
7994 } else {
7995 outSupport->emplace();
7996 outSupport->value().format = static_cast<int32_t>(support->format);
7997 outSupport->value().alphaInterpretation =
7998 static_cast<int32_t>(support->alphaInterpretation);
7999 }
8000
8001 return binder::Status::ok();
8002}
8003
8004binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
8005 status_t status;
8006 const int c_uid = IPCThreadState::self()->getCallingUid();
8007 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
8008 status = mFlinger->setOverrideFrameRate(uid, frameRate);
8009 } else {
8010 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
8011 status = PERMISSION_DENIED;
8012 }
8013 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008014}
8015
Huihong Luo02186fb2022-02-23 14:21:54 -08008016binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
8017 const sp<gui::ITransactionTraceListener>& listener) {
8018 status_t status;
8019 IPCThreadState* ipc = IPCThreadState::self();
8020 const int uid = ipc->getCallingUid();
8021 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
8022 status = mFlinger->addTransactionTraceListener(listener);
8023 } else {
8024 status = PERMISSION_DENIED;
8025 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008026 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008027}
8028
8029binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
8030 *outPriority = mFlinger->getGpuContextPriority();
8031 return binder::Status::ok();
8032}
8033
8034binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
8035 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08008036 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008037}
8038
8039binder::Status SurfaceComposerAIDL::addWindowInfosListener(
8040 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8041 status_t status;
8042 const int uid = IPCThreadState::self()->getCallingUid();
8043 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8044 status = mFlinger->addWindowInfosListener(windowInfosListener);
8045 } else {
8046 status = PERMISSION_DENIED;
8047 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008048 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008049}
8050
8051binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
8052 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8053 status_t status;
8054 const int uid = IPCThreadState::self()->getCallingUid();
8055 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8056 status = mFlinger->removeWindowInfosListener(windowInfosListener);
8057 } else {
8058 status = PERMISSION_DENIED;
8059 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008060 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008061}
8062
Huihong Luo07e72362022-02-14 14:26:04 -08008063status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
8064 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
8065 IPCThreadState* ipc = IPCThreadState::self();
8066 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
8067 ipc->getCallingUid());
8068 return PERMISSION_DENIED;
8069 }
8070 return OK;
8071}
8072
Huihong Luo37396db2022-02-15 10:43:00 -08008073status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
8074 IPCThreadState* ipc = IPCThreadState::self();
8075 const int pid = ipc->getCallingPid();
8076 const int uid = ipc->getCallingUid();
8077 if ((uid != AID_GRAPHICS) &&
8078 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
8079 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
8080 return PERMISSION_DENIED;
8081 }
8082 return OK;
8083}
8084
Huihong Luo02186fb2022-02-23 14:21:54 -08008085status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
8086 IPCThreadState* ipc = IPCThreadState::self();
8087 const int pid = ipc->getCallingPid();
8088 const int uid = ipc->getCallingUid();
8089 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
8090 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
8091 return PERMISSION_DENIED;
8092 }
8093 return OK;
8094}
8095
Dominik Laskowski9dab3432019-03-27 13:21:10 -07008096} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07008097
Mathias Agopian3f844832013-08-07 21:24:32 -07008098#if defined(__gl_h_)
8099#error "don't include gl/gl.h in this file"
8100#endif
8101
8102#if defined(__gl2_h_)
8103#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008104#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008105
8106// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008107#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"