blob: a7438f2f23db55fe963870bb15373ab8d9868a67 [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
Vishnu Nair4fb00ed2022-06-03 10:25:09 -0700285static const int MAX_TRACING_MEMORY = 1024 * 1024 * 1024; // 1GB
286
Mathias Agopian99b49842011-06-27 16:05:52 -0700287// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700288int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700289bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800290bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800291int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100292uint32_t SurfaceFlinger::maxGraphicsWidth;
293uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600294bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700295bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700296Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
297ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
298Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
299ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000300LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700301
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800302std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
303 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800304 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700305 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800306 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700307 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800308 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700309 return std::string("Enhanced");
310 default:
311 return std::string("Unknown ") +
312 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800313 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800314}
315
Hongwei Wang46213ea2020-12-04 17:17:31 -0800316bool callingThreadHasRotateSurfaceFlingerAccess() {
317 IPCThreadState* ipc = IPCThreadState::self();
318 const int pid = ipc->getCallingPid();
319 const int uid = ipc->getCallingUid();
320 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
321 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
322}
323
Leon Scroggins9a20f722021-12-28 14:43:12 +0000324bool callingThreadHasInternalSystemWindowAccess() {
325 IPCThreadState* ipc = IPCThreadState::self();
326 const int pid = ipc->getCallingPid();
327 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500328 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
329 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000330}
331
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700332SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
333 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800334 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000335 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700336 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800337 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800338 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700339 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700340 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700341 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800342 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700343 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000344 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Dominik Laskowski91f635e2022-01-08 05:46:09 -0800345 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make(*this)) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700346 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700347}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800348
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700349SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800350 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800351
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900352 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900354 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700355
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900356 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700357
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900358 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800359
Brian Lindahla13f2d52020-03-05 11:54:17 +0100360 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
361 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
362
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900363 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900364 mDefaultCompositionDataspace =
365 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700366 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
367 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900368 defaultCompositionDataspace = mDefaultCompositionDataspace;
369 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
370 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
371 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
372 wideColorGamutCompositionPixelFormat =
373 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700374
Yichi Chenda901bf2019-06-28 14:58:27 +0800375 mColorSpaceAgnosticDataspace =
376 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
377
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700378 mLayerCachingEnabled = [] {
379 const bool enable =
380 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
381 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
382 }();
383
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900384 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800385
Sundong Ahn85131bd2019-02-18 15:51:53 +0900386 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800387
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388 // debugging stuff...
389 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700390
Mathias Agopianb4b17302013-03-20 18:36:41 -0700391 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700392 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700393
Alec Mouri5f487d42020-02-06 09:26:19 -0800394 property_get("ro.build.type", value, "user");
395 mIsUserBuild = strcmp(value, "user") == 0;
396
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700397 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000398
399 // DDMS debugging deprecated (b/120782499)
400 property_get("debug.sf.ddms", value, "0");
401 int debugDdms = atoi(value);
402 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700403
Ady Abrahamadb9a992019-09-19 21:21:55 +0000404 property_get("debug.sf.enable_gl_backpressure", value, "0");
405 mPropagateBackpressureClientComposition = atoi(value);
406 ALOGI_IF(mPropagateBackpressureClientComposition,
407 "Enabling backpressure propagation for Client Composition");
408
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800409 property_get("ro.surface_flinger.supports_background_blur", value, "0");
410 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700411 mSupportsBlur = supportsBlurs;
412 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800413 property_get("ro.sf.blurs_are_expensive", value, "0");
414 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800415
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700416 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700417 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
418 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800419 mGraphicBufferProducerListSizeLogThreshold =
420 std::max(static_cast<int>(0.95 *
421 static_cast<double>(mMaxGraphicBufferProducerListSize)),
422 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700423
Dan Stozaec460082018-12-17 15:35:09 -0800424 property_get("debug.sf.luma_sampling", value, "1");
425 mLumaSampling = atoi(value);
426
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800427 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800428 mDisableClientCompositionCache = atoi(value);
429
Vishnu Nair3539d812022-02-26 09:20:17 -0800430 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800431 mPredictCompositionStrategy = atoi(value);
432
Alec Mouridda07d92022-04-25 22:39:25 +0000433 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
434 mTreat170mAsSrgb = atoi(value);
435
Romain Guy11d63f42017-07-20 12:47:14 -0700436 // We should be reading 'persist.sys.sf.color_saturation' here
437 // but since /data may be encrypted, we need to wait until after vold
438 // comes online to attempt to read the property. The property is
439 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800440
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700441 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800442 // Without the override SurfaceFlinger cannot connect to HIDL
443 // services that are not listed in the manifests. Considered
444 // deriving the setting from the set service name, but it
445 // would be brittle if the name that's not 'default' is used
446 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700447 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000448 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800449 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800450
Ady Abraham29d0da32020-07-16 18:39:33 -0700451 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400452
Dominik Laskowski46471e62022-01-14 15:34:03 -0800453 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
454 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800455 }
John Reck49d9ad32022-02-23 19:03:31 -0500456
457 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
Matt Buckley50c44062022-01-17 20:48:10 +0000458
459 // Power hint session mode, representing which hint(s) to send: early, late, or both)
460 mPowerHintSessionMode =
461 {.late = base::GetBoolProperty("debug.sf.send_late_power_session_hint"s, true),
462 .early = base::GetBoolProperty("debug.sf.send_early_power_session_hint"s, true)};
ramindani4d48f902021-09-20 21:07:45 +0000463}
464
465LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
466 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
467 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000468 }
Ady Abraham9dada822022-02-03 10:26:59 -0800469
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000470 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800471 return LatchUnsignaledConfig::AutoSingleLayer;
472 }
473
474 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800475}
476
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700477SurfaceFlinger::~SurfaceFlinger() = default;
478
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700479void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800480 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700481 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800482
Dominik Laskowski756b7892021-08-04 12:53:59 -0700483 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000484 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800485
Andy McFadden13a082e2012-08-24 10:16:42 -0700486 // restore initial conditions (default device unblank, etc)
487 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800488
489 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700490 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800491}
492
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700493void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700494 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800495}
496
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700497sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700498 // onTransact already checks for some permissions, but adding an additional check here.
499 // This is to ensure that only system and graphics can request to create a secure
500 // display. Secure displays can show secure content so we add an additional restriction on it.
501 const int uid = IPCThreadState::self()->getCallingUid();
502 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
503 ALOGE("Only privileged processes can create a secure display");
504 return nullptr;
505 }
506
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507 class DisplayToken : public BBinder {
508 sp<SurfaceFlinger> flinger;
509 virtual ~DisplayToken() {
510 // no more references, this display must be terminated
511 Mutex::Autolock _l(flinger->mStateLock);
512 flinger->mCurrentState.displays.removeItem(this);
513 flinger->setTransactionFlags(eDisplayTransactionNeeded);
514 }
515 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700516 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700517 : flinger(flinger) {
518 }
519 };
520
521 sp<BBinder> token = new DisplayToken(this);
522
523 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700524 // Display ID is assigned when virtual display is allocated by HWC.
525 DisplayDeviceState state;
526 state.isSecure = secure;
527 state.displayName = displayName;
528 mCurrentState.displays.add(token, state);
529 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700530 return token;
531}
532
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700533void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700534 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700535
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700536 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700537 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800538 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700539 return;
540 }
541
Dominik Laskowski075d3172018-05-24 15:50:06 -0700542 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700543 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800544 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700545 return;
546 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700547 mInterceptor->saveDisplayDeletion(state.sequenceId);
548 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700549 setTransactionFlags(eDisplayTransactionNeeded);
550}
551
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800552void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
553 auto& generator = mVirtualDisplayIdGenerators.hal;
554 if (!generator && enable) {
555 ALOGI("Enabling HAL virtual displays");
556 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
557 } else if (generator && !enable) {
558 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
559 generator.reset();
560 }
561}
562
Dominik Laskowski263eec42021-07-21 23:13:24 -0700563VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
564 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800565 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
566 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700567 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800568 return *id;
569 }
570
571 generator->releaseId(*id);
572 } else {
573 ALOGW("%s: Exhausted HAL virtual displays", __func__);
574 }
575
576 ALOGW("%s: Falling back to GPU virtual display", __func__);
577 }
578
579 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
580 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
581 return *id;
582}
583
584void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
585 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
586 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
587 generator->releaseId(*id);
588 }
589 return;
590 }
591
592 const auto id = GpuVirtualDisplayId::tryCast(displayId);
593 LOG_ALWAYS_FATAL_IF(!id);
594 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
595}
596
Ady Abrahamed3290f2021-05-17 15:12:14 -0700597std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800598 std::vector<PhysicalDisplayId> displayIds;
599 displayIds.reserve(mPhysicalDisplayTokens.size());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700600
Dominik Laskowski3c363242022-04-07 10:44:12 -0700601 const auto defaultDisplayId = getDefaultDisplayDeviceLocked()->getPhysicalId();
Ady Abraham2a0066d2021-07-15 20:16:58 -0700602 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800603
604 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700605 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200606 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800607 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700608 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700609
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800610 return displayIds;
611}
612
Vishnu Nair8c8db542021-09-17 19:51:45 -0700613status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
614 Mutex::Autolock lock(mStateLock);
Dominik Laskowski3c363242022-04-07 10:44:12 -0700615 *id = getPrimaryDisplayIdLocked();
Vishnu Nair8c8db542021-09-17 19:51:45 -0700616 return NO_ERROR;
617}
618
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800619sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
620 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200621 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700622}
623
Ady Abraham37965d42018-11-01 13:43:32 -0700624status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
625 if (!outGetColorManagement) {
626 return BAD_VALUE;
627 }
628 *outGetColorManagement = useColorManagement;
629 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700630}
631
Lloyd Pique441d5042018-10-18 16:49:51 -0700632HWComposer& SurfaceFlinger::getHwComposer() const {
633 return mCompositionEngine->getHwComposer();
634}
635
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700636renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
637 return mCompositionEngine->getRenderEngine();
638}
639
Lloyd Pique70d91362018-10-18 16:02:55 -0700640compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
641 return *mCompositionEngine.get();
642}
643
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100644void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700645 if (mBootFinished == true) {
646 ALOGE("Extra call to bootFinished");
647 return;
648 }
649 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700650 if (mStartPropertySetThread->join() != NO_ERROR) {
651 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800652 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700653
654 if (mRenderEnginePrimeCacheFuture.valid()) {
655 mRenderEnginePrimeCacheFuture.get();
656 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800657 const nsecs_t now = systemTime();
658 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000659 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700660
Mikael Pessa90092f42019-08-26 17:22:04 -0700661 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700662 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700663 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700664
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700665 // wait patiently for the window manager death
666 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700667 mWindowManager = defaultServiceManager()->getService(name);
668 if (mWindowManager != 0) {
669 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700670 }
671
672 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700673 // formerly we would just kill the process, but we now ask it to exit so it
674 // can choose where to stop the animation.
675 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700676
677 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
678 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
679 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700680
Denis Hsue70cc6c2020-06-17 10:17:30 +0800681 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
682
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000683 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800684 if (input == nullptr) {
685 ALOGE("Failed to link to input service");
686 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700687 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800688 }
689
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800690 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000691 mPowerAdvisor->onBootFinished();
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000692 const bool powerHintEnabled = mFlagManager.use_adpf_cpu_hint();
693 mPowerAdvisor->enablePowerHint(powerHintEnabled);
694 const bool powerHintUsed = mPowerAdvisor->usePowerHintSession();
695 ALOGD("Power hint is %s",
696 powerHintUsed ? "supported" : (powerHintEnabled ? "unsupported" : "disabled"));
697 if (powerHintUsed) {
Xiang Wang76236e12022-03-22 17:25:30 +0000698 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
699 std::vector<int32_t> tidList;
700 tidList.emplace_back(gettid());
701 if (renderEngineTid.has_value()) {
702 tidList.emplace_back(*renderEngineTid);
703 }
Xiang Wang839fe5b2022-04-04 17:39:38 +0000704 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000705 ALOGW("Cannot start power hint session");
706 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000707 }
708
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800709 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800710
Ady Abraham8a82ba62020-01-17 12:43:17 -0800711 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800712 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800713 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800714 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800715}
716
Dan Stoza436ccf32018-06-21 12:10:12 -0700717uint32_t SurfaceFlinger::getNewTexture() {
718 {
719 std::lock_guard lock(mTexturePoolMutex);
720 if (!mTexturePool.empty()) {
721 uint32_t name = mTexturePool.back();
722 mTexturePool.pop_back();
723 ATRACE_INT("TexturePoolSize", mTexturePool.size());
724 return name;
725 }
726
727 // The pool was too small, so increase it for the future
728 ++mTexturePoolSize;
729 }
730
731 // The pool was empty, so we need to get a new texture name directly using a
732 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700733 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700734 uint32_t name = 0;
735 getRenderEngine().genTextures(1, &name);
736 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700737 };
738 if (std::this_thread::get_id() == mMainThreadId) {
739 return genTextures();
740 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700741 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700742 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700743}
744
Mathias Agopian3f844832013-08-07 21:24:32 -0700745void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700746 std::lock_guard lock(mTexturePoolMutex);
747 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
748 // to actually delete this or not based on mTexturePoolSize
749 mTexturePool.push_back(texture);
750 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700751}
752
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500753static std::optional<renderengine::RenderEngine::RenderEngineType>
754chooseRenderEngineTypeViaSysProp() {
755 char prop[PROPERTY_VALUE_MAX];
756 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
757
758 if (strcmp(prop, "gles") == 0) {
759 return renderengine::RenderEngine::RenderEngineType::GLES;
760 } else if (strcmp(prop, "threaded") == 0) {
761 return renderengine::RenderEngine::RenderEngineType::THREADED;
762 } else if (strcmp(prop, "skiagl") == 0) {
763 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
764 } else if (strcmp(prop, "skiaglthreaded") == 0) {
765 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
766 } else {
767 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
768 return {};
769 }
770}
771
Wei Wangf9b05ee2017-07-19 20:59:39 -0700772// Do not call property_set on main thread which will be blocked by init
773// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700774void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700775 ALOGI( "SurfaceFlinger's main thread ready to run. "
776 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700777 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800778
Steven Thomasb02664d2017-07-26 18:48:28 -0700779 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700780 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800781 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500782 auto builder = renderengine::RenderEngineCreationArgs::Builder()
783 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
784 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
785 .setUseColorManagerment(useColorManagement)
786 .setEnableProtectedContext(enable_protected_contents(false))
787 .setPrecacheToneMapperShaderOnly(false)
788 .setSupportsBackgroundBlur(mSupportsBlur)
789 .setContextPriority(
790 useContextPriority
791 ? renderengine::RenderEngine::ContextPriority::REALTIME
792 : renderengine::RenderEngine::ContextPriority::MEDIUM);
793 if (auto type = chooseRenderEngineTypeViaSysProp()) {
794 builder.setRenderEngineType(type.value());
795 }
796 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700797 mMaxRenderTargetSize =
798 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700799
800 // Set SF main policy after initializing RenderEngine which has its own policy.
801 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
802 ALOGW("Failed to set main task profile");
803 }
804
Alec Mourie4034bb2019-11-19 12:45:54 -0800805 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700806 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800807 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000808 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800809
Ady Abraham9dada822022-02-03 10:26:59 -0800810 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
811
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800812 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
813 enableHalVirtualDisplays(true);
814 }
815
Lloyd Piqueba04e622017-12-14 17:11:26 -0800816 // Process any initial hotplug and resulting display changes.
817 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700818 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700819 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200820 const auto displayId = display->getPhysicalId();
821 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700822 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800823
Mathias Agopian92a979a2012-08-02 18:32:23 -0700824 // initialize our drawing state
825 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700826
Andy McFadden13a082e2012-08-24 10:16:42 -0700827 // set initial conditions (e.g. unblank default device)
828 initializeDisplays();
829
Xiang Wang839fe5b2022-04-04 17:39:38 +0000830 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700831
Steven Thomas137d4bc2019-07-25 16:55:14 -0700832 char primeShaderCache[PROPERTY_VALUE_MAX];
833 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
834 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700835 if (setSchedFifo(false) != NO_ERROR) {
836 ALOGW("Can't set SCHED_OTHER for primeCache");
837 }
838
839 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
840
841 if (setSchedFifo(true) != NO_ERROR) {
842 ALOGW("Can't set SCHED_OTHER for primeCache");
843 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700844 }
Dan Stoza4e637772016-07-28 13:31:51 -0700845
Ady Abrahamed3290f2021-05-17 15:12:14 -0700846 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400847
Wei Wangf9b05ee2017-07-19 20:59:39 -0700848 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700849
850 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800851 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700852 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700853
854 if (mStartPropertySetThread->Start() != NO_ERROR) {
855 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800856 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800857
Dan Stoza9e56aa02015-11-02 13:00:03 -0800858 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700859}
860
Romain Guy11d63f42017-07-20 12:47:14 -0700861void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700862 Mutex::Autolock _l(mStateLock);
863
Romain Guy11d63f42017-07-20 12:47:14 -0700864 char value[PROPERTY_VALUE_MAX];
865
866 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800867 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700868 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800869 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100870
871 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700872 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800873
874 property_get("persist.sys.sf.color_mode", value, "0");
875 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700876}
877
Mathias Agopiana67e4182012-06-19 17:26:12 -0700878void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800879 // Start boot animation service by setting a property mailbox
880 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700881 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800882 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700883 if (mStartPropertySetThread->join() != NO_ERROR) {
884 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800885 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700886}
887
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800888// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800889
Brian Anderson6b376712017-04-04 10:51:39 -0700890status_t SurfaceFlinger::getSupportedFrameTimestamps(
891 std::vector<FrameEvent>* outSupported) const {
892 *outSupported = {
893 FrameEvent::REQUESTED_PRESENT,
894 FrameEvent::ACQUIRE,
895 FrameEvent::LATCH,
896 FrameEvent::FIRST_REFRESH_START,
897 FrameEvent::LAST_REFRESH_START,
898 FrameEvent::GPU_COMPOSITION_DONE,
899 FrameEvent::DEQUEUE_READY,
900 FrameEvent::RELEASE,
901 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800902
903 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
904
Ady Abrahamde549d42022-01-26 19:19:17 -0800905 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700906 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
907 }
908 return NO_ERROR;
909}
910
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800911status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
912 if (!displayToken || !state) {
913 return BAD_VALUE;
914 }
915
916 Mutex::Autolock lock(mStateLock);
917
918 const auto display = getDisplayDeviceLocked(displayToken);
919 if (!display) {
920 return NAME_NOT_FOUND;
921 }
922
923 state->layerStack = display->getLayerStack();
924 state->orientation = display->getOrientation();
925
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200926 const Rect layerStackRect = display->getLayerStackSpaceRect();
927 state->layerStackSpaceRect =
928 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800929
930 return NO_ERROR;
931}
932
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100933status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
934 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800935 if (!displayToken || !info) {
936 return BAD_VALUE;
937 }
938
939 Mutex::Autolock lock(mStateLock);
940
941 const auto display = getDisplayDeviceLocked(displayToken);
942 if (!display) {
943 return NAME_NOT_FOUND;
944 }
945
Dominik Laskowski55c85402020-01-21 16:25:47 -0800946 if (const auto connectionType = display->getConnectionType())
947 info->connectionType = *connectionType;
948 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800949 return INVALID_OPERATION;
950 }
951
952 if (mEmulatedDisplayDensity) {
953 info->density = mEmulatedDisplayDensity;
954 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100955 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800956 ? mInternalDisplayDensity
957 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800958 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700959 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800960
961 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200962 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000963 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800964
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800965 return NO_ERROR;
966}
967
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100968status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
969 ui::DynamicDisplayInfo* info) {
970 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700971 return BAD_VALUE;
972 }
973
Dominik Laskowski22488f62019-03-28 09:53:04 -0700974 Mutex::Autolock lock(mStateLock);
975
Marin Shalamanov5801c942020-12-17 17:00:13 +0100976 const auto display = getDisplayDeviceLocked(displayToken);
977 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700978 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700979 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700980
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700981 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
982 if (!displayId) {
983 return INVALID_OPERATION;
984 }
985
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800986 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700987
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100988 const auto& supportedModes = display->getSupportedModes();
989 info->supportedDisplayModes.clear();
990 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800991
992 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100993 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800994 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700995
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800996 auto [width, height] = mode->getResolution();
997 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700998
ramindani06e518e2022-03-14 18:47:53 +0000999 if (const auto physicalOrientation = display->getPhysicalOrientation();
1000 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001001 std::swap(width, height);
1002 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -07001003 }
1004
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001005 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -08001006
Huan Songf7eeb102022-03-28 11:02:38 -07001007 outMode.xDpi = xDpi;
1008 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001009
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001010 const nsecs_t period = mode->getVsyncPeriod();
1011 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001012
Ady Abraham8287e852020-08-12 14:44:58 -07001013 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001014 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001015 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1016 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1017 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001018
Andy McFadden91b2ca82014-06-13 14:04:23 -07001019 // This is how far in advance a buffer must be queued for
1020 // presentation at a given time. If you want a buffer to appear
1021 // on the screen at time N, you must submit the buffer before
1022 // (N - presentationDeadline).
1023 //
1024 // Normally it's one full refresh period (to give SF a chance to
1025 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001026 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001027 // composer or panel must be accounted for here.
1028 //
1029 // We add an additional 1ms to allow for processing time and
1030 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001031 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001032
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001033 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001034 }
1035
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001036 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001037 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001038 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001039
Marin Shalamanovb173f752021-02-16 19:38:36 +01001040 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001041 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001042 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001043 info->gameContentTypeSupported =
1044 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001045
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001046 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001047
1048 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001049 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1050 if (const auto modeId = display->translateModeId(*hwcId)) {
1051 info->preferredBootDisplayMode = modeId->value();
1052 }
1053 }
1054 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001055
Dan Stoza7f7da322014-05-02 15:26:25 -07001056 return NO_ERROR;
1057}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001059status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
1060 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001061 return BAD_VALUE;
1062 }
1063
Ady Abrahame90dd522020-12-29 12:08:45 -08001064 *stats = mScheduler->getDisplayStatInfo(systemTime());
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001065 return NO_ERROR;
1066}
1067
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001068void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001069 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001070
1071 if (!info.mode) {
1072 ALOGW("requested display mode is null");
1073 return;
1074 }
1075 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001076 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001077 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001078 return;
1079 }
1080
Ady Abraham690f4612021-07-01 23:24:03 -07001081 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001082 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001083
Alec Mouri754c98a2019-03-18 18:53:42 -07001084 // Start receiving vsync samples now, so that we can detect a period
1085 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001086 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001087 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001088 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001089 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001090
Ady Abraham690f4612021-07-01 23:24:03 -07001091 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001092 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001093 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001094}
1095
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001096status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001097 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001098
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001099 if (!displayToken) {
1100 return BAD_VALUE;
1101 }
Ady Abraham838de062019-02-04 10:24:03 -08001102
Dominik Laskowski756b7892021-08-04 12:53:59 -07001103 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001104 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001105 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001106 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001107 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001108 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001109 }
1110
1111 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001112 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001113 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001114 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001115
1116 const auto mode = display->getMode(DisplayModeId{modeId});
1117 if (!mode) {
1118 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1119 return BAD_VALUE;
1120 }
1121
1122 const auto fps = mode->getFps();
1123 // Keep the old switching type.
1124 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001125 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001126 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1127 allowGroupSwitching,
1128 {fps, fps}};
1129 constexpr bool kOverridePolicy = false;
1130
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001131 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001132 });
1133
1134 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001135}
1136
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001137void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001138 ATRACE_CALL();
1139
Dominik Laskowski22488f62019-03-28 09:53:04 -07001140 const auto display = getDefaultDisplayDeviceLocked();
1141 if (!display) {
1142 return;
1143 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001144
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001145 const auto upcomingModeInfo =
1146 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1147
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001148 if (!upcomingModeInfo.mode) {
1149 // There is no pending mode change. This can happen if the active
1150 // display changed and the mode change happened on a different display.
1151 return;
1152 }
1153
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001154 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001155 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1156 // We need to generate new sequenceId in order to recreate the display (and this
1157 // way the framebuffer).
1158 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001159 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001160 processDisplayChangesLocked();
1161
1162 // processDisplayChangesLocked will update all necessary components so we're done here.
1163 return;
1164 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001165
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001166 // We just created this display so we can call even if we are not on the main thread.
1167 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001168 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001169
Ady Abraham690f4612021-07-01 23:24:03 -07001170 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001171 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001172 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001173
Dominik Laskowski068173d2021-08-11 17:22:59 -07001174 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001175 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001176 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001177}
1178
Ady Abraham690f4612021-07-01 23:24:03 -07001179void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1180 display->clearDesiredActiveModeState();
1181 if (isDisplayActiveLocked(display)) {
1182 mScheduler->setModeChangePending(false);
1183 }
Ady Abraham53852a52019-05-28 18:07:44 -07001184}
1185
Ady Abraham690f4612021-07-01 23:24:03 -07001186void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1187 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1188 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001189 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001190 updatePhaseConfiguration(refreshRate);
1191}
1192
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001193void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001194 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001195
Marin Shalamanovdd594312021-11-09 16:37:37 +01001196 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1197
Ady Abraham690f4612021-07-01 23:24:03 -07001198 for (const auto& iter : mDisplays) {
1199 const auto& display = iter.second;
1200 if (!display || !display->isInternal()) {
1201 continue;
1202 }
1203
1204 // Store the local variable to release the lock.
1205 const auto desiredActiveMode = display->getDesiredActiveMode();
1206 if (!desiredActiveMode) {
1207 // No desired active mode pending to be applied
1208 continue;
1209 }
1210
1211 if (!isDisplayActiveLocked(display)) {
1212 // display is no longer the active display, so abort the mode change
1213 clearDesiredActiveModeState(display);
1214 continue;
1215 }
1216
1217 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1218 if (!desiredMode) {
1219 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1220 desiredActiveMode->mode->getId().value());
1221 clearDesiredActiveModeState(display);
1222 continue;
1223 }
1224
1225 const auto refreshRate = desiredMode->getFps();
1226 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1227 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1228 to_string(display->getId()).c_str());
1229
1230 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001231 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001232 desiredActiveModeChangeDone(display);
1233 continue;
1234 }
1235
1236 // Desired active mode was set, it is different than the mode currently in use, however
1237 // allowed modes might have changed by the time we process the refresh.
1238 // Make sure the desired mode is still allowed
1239 const auto displayModeAllowed =
1240 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1241 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001242 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001243 continue;
1244 }
1245
1246 // TODO(b/142753666) use constrains
1247 hal::VsyncPeriodChangeConstraints constraints;
1248 constraints.desiredTimeNanos = systemTime();
1249 constraints.seamlessRequired = false;
1250 hal::VsyncPeriodChangeTimeline outTimeline;
1251
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001252 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1253 display->initiateModeChange(*desiredActiveMode,
1254 constraints, &outTimeline));
1255
Ady Abraham690f4612021-07-01 23:24:03 -07001256 if (status != NO_ERROR) {
1257 // initiateModeChange may fail if a hotplug event is just about
1258 // to be sent. We just log the error in this case.
1259 ALOGW("initiateModeChange failed: %d", status);
1260 continue;
1261 }
1262 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1263
Marin Shalamanovdd594312021-11-09 16:37:37 +01001264 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001265 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001266 mSetActiveModePending = true;
1267 } else {
1268 // Updating the internal state should be done outside the loop,
1269 // because it can recreate a DisplayDevice and modify mDisplays
1270 // which will invalidate the iterator.
1271 displayToUpdateImmediately = display->getPhysicalId();
1272 }
1273 }
1274
1275 if (displayToUpdateImmediately) {
1276 updateInternalStateWithChangedMode();
1277
1278 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1279 const auto desiredActiveMode = display->getDesiredActiveMode();
1280 if (desiredActiveMode &&
1281 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1282 desiredActiveModeChangeDone(display);
1283 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001284 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001285}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001286
Alec Mouridea1ac52021-06-23 18:12:18 -07001287void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001288 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001289 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001290 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001291 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001292 for (const auto& [_, display] : mDisplays) {
1293 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001294 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001295 }
1296 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001297 });
1298
1299 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001300}
1301
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001302std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1303 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001304
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001305 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001306 // filter out all wide color modes. The typical reason why this happens is that the
1307 // hardware is not good enough to support GPU composition of wide color, and thus the
1308 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001309 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1310 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001311 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1312 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001313 }
Michael Wright28f24d02016-07-12 13:30:53 -07001314
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001315 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001316}
1317
Daniel Solomon42d04562019-01-20 21:03:19 -08001318status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001319 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001320 if (!displayToken) {
1321 return BAD_VALUE;
1322 }
1323
Dominik Laskowski3c363242022-04-07 10:44:12 -07001324 Mutex::Autolock lock(mStateLock);
1325
1326 const auto display = getDisplayDeviceLocked(displayToken);
1327 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001328 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001329 }
1330
Dominik Laskowski3c363242022-04-07 10:44:12 -07001331 const auto connectionType = display->getConnectionType();
1332 if (connectionType != ui::DisplayConnectionType::Internal) {
1333 return INVALID_OPERATION;
1334 }
1335
1336 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1337 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001338 return NO_ERROR;
1339}
1340
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001341status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001342 if (!displayToken) {
1343 return BAD_VALUE;
1344 }
1345
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001346 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001347 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001348 if (!display) {
1349 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1350 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001351 return NAME_NOT_FOUND;
1352 }
1353
1354 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001355 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1356 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001357 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001358 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001359
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001360 const auto modes = getDisplayColorModes(*display);
1361 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1362
1363 if (mode < ColorMode::NATIVE || !exists) {
1364 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1365 decodeColorMode(mode).c_str(), mode, displayToken.get());
1366 return BAD_VALUE;
1367 }
1368
1369 display->getCompositionDisplay()->setColorProfile(
1370 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1371
1372 return NO_ERROR;
1373 });
1374
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001375 // TODO(b/195698395): Propagate error.
1376 future.wait();
1377 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001378}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001379
Kriti Dang7defaf32021-11-15 11:55:43 +01001380status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001381 auto future = mScheduler->schedule(
1382 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1383
1384 *outSupport = future.get();
1385 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001386}
1387
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001388status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1389 ui::DisplayModeId modeId) {
1390 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001391 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001392 const auto display = getDisplayDeviceLocked(displayToken);
1393 if (!display) {
1394 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1395 return NAME_NOT_FOUND;
1396 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001397
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001398 if (display->isVirtual()) {
1399 ALOGE("%s: Invalid operation on virtual display", whence);
1400 return INVALID_OPERATION;
1401 }
1402
1403 const auto displayId = display->getPhysicalId();
1404 const auto mode = display->getMode(DisplayModeId{modeId});
1405 if (!mode) {
1406 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1407 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001408 return BAD_VALUE;
1409 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001410
1411 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001412 });
1413 return future.get();
1414}
1415
1416status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001417 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001418 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001419 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1420 return getHwComposer().clearBootDisplayMode(*displayId);
1421 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001422 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001423 return BAD_VALUE;
1424 }
1425 });
1426 return future.get();
1427}
1428
Galia Peycheva5492cb52019-10-30 14:13:16 +01001429void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001430 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001431 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001432 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1433 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1434 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001435 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001436 }
1437 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001438}
1439
Galia Peycheva5492cb52019-10-30 14:13:16 +01001440void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001441 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001442 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001443 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001444 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001445 getHwComposer().setContentType(*displayId, type);
1446 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001447 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001448 }
1449 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001450}
1451
Svetoslavd85084b2014-03-20 10:28:31 -07001452status_t SurfaceFlinger::clearAnimationFrameStats() {
1453 Mutex::Autolock _l(mStateLock);
1454 mAnimFrameTracker.clearStats();
1455 return NO_ERROR;
1456}
1457
1458status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1459 Mutex::Autolock _l(mStateLock);
1460 mAnimFrameTracker.getStats(outStats);
1461 return NO_ERROR;
1462}
1463
Kriti Dang49ad4132021-01-08 11:49:56 +01001464status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1465 const std::vector<ui::Hdr>& hdrTypes) {
1466 Mutex::Autolock lock(mStateLock);
1467
1468 auto display = getDisplayDeviceLocked(displayToken);
1469 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001470 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001471 return NAME_NOT_FOUND;
1472 }
1473
1474 display->overrideHdrTypes(hdrTypes);
1475 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1476 return NO_ERROR;
1477}
1478
Tej Singhe2751772021-04-06 22:05:29 -07001479status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1480 *success = mTimeStats->onPullAtom(atomId, pulledData);
1481 return NO_ERROR;
1482}
1483
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001484status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1485 ui::PixelFormat* outFormat,
1486 ui::Dataspace* outDataspace,
1487 uint8_t* outComponentMask) const {
1488 if (!outFormat || !outDataspace || !outComponentMask) {
1489 return BAD_VALUE;
1490 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001491
1492 Mutex::Autolock lock(mStateLock);
1493
1494 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1495 if (!displayId) {
1496 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001497 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001498
1499 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001500 outDataspace, outComponentMask);
1501}
1502
Kevin DuBois74e53772018-11-19 10:52:38 -08001503status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1504 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001505 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001506 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001507 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001508 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1509 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1510 componentMask, maxFrames);
1511 } else {
1512 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1513 return NAME_NOT_FOUND;
1514 }
1515 });
1516
1517 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001518}
1519
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001520status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1521 uint64_t maxFrames, uint64_t timestamp,
1522 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001523 Mutex::Autolock lock(mStateLock);
1524
1525 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1526 if (!displayId) {
1527 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001528 }
1529
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001530 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001531}
1532
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001533status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1534 if (!outSupported) {
1535 return BAD_VALUE;
1536 }
1537 *outSupported = getRenderEngine().supportsProtectedContent();
1538 return NO_ERROR;
1539}
1540
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001541status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1542 bool* outIsWideColorDisplay) const {
1543 if (!displayToken || !outIsWideColorDisplay) {
1544 return BAD_VALUE;
1545 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001546
1547 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001548 const auto display = getDisplayDeviceLocked(displayToken);
1549 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001550 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001551 }
Peiyong Linff84a152019-05-17 18:36:19 -07001552
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001553 *outIsWideColorDisplay =
1554 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001555 return NO_ERROR;
1556}
1557
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001558status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001559 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001560 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001561
Dominik Laskowski6505f792019-09-18 11:10:05 -07001562 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001563 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001564 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001565 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001566
Dominik Laskowski756b7892021-08-04 12:53:59 -07001567 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001568 return NO_ERROR;
1569}
1570
1571status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001572 Mutex::Autolock lock(mStateLock);
Ady Abrahame90dd522020-12-29 12:08:45 -08001573 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(when);
Ady Abraham56b42a42020-12-28 16:48:48 -08001574 const auto expectedPresent = calculateExpectedPresentTime(stats);
Ady Abraham9c53ee72020-07-22 21:16:18 -07001575 return mScheduler->injectVSync(when, /*expectedVSyncTime=*/expectedPresent,
1576 /*deadlineTimestamp=*/expectedPresent)
1577 ? NO_ERROR
1578 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001579}
1580
Huihong Luo05539a12022-02-23 10:29:40 -08001581status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001582 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001583 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001584 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001585 mDrawingState.traverseInZOrder([&](Layer* layer) {
1586 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1587 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001588 });
1589
1590 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001591 return NO_ERROR;
1592}
1593
Peiyong Linc6780972018-10-28 15:24:08 -07001594status_t SurfaceFlinger::getCompositionPreference(
1595 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1596 Dataspace* outWideColorGamutDataspace,
1597 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001598 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001599 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001600 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001601 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001602 return NO_ERROR;
1603}
1604
Dan Stozaec460082018-12-17 15:35:09 -08001605status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1606 const sp<IBinder>& stopLayerHandle,
1607 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001608 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001609 return BAD_VALUE;
1610 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001611
1612 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1613 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001614 return NO_ERROR;
1615}
1616
Dan Stozaec460082018-12-17 15:35:09 -08001617status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001618 if (!listener) {
1619 return BAD_VALUE;
1620 }
Dan Stozaec460082018-12-17 15:35:09 -08001621 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001622 return NO_ERROR;
1623}
Dan Gittik57e63c52019-01-18 16:37:54 +00001624
Alec Mouria9a68a62021-03-04 19:14:50 -08001625status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001626 if (!listener) {
1627 return BAD_VALUE;
1628 }
1629
Alec Mouria9a68a62021-03-04 19:14:50 -08001630 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001631 return NO_ERROR;
1632}
1633
1634status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1635 if (!listener) {
1636 return BAD_VALUE;
1637 }
1638 mFpsReporter->removeListener(listener);
1639 return NO_ERROR;
1640}
1641
Galia Peycheva8f04b302021-04-27 13:25:38 +02001642status_t SurfaceFlinger::addTunnelModeEnabledListener(
1643 const sp<gui::ITunnelModeEnabledListener>& listener) {
1644 if (!listener) {
1645 return BAD_VALUE;
1646 }
1647
1648 mTunnelModeEnabledReporter->addListener(listener);
1649 return NO_ERROR;
1650}
1651
1652status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1653 const sp<gui::ITunnelModeEnabledListener>& listener) {
1654 if (!listener) {
1655 return BAD_VALUE;
1656 }
1657
1658 mTunnelModeEnabledReporter->removeListener(listener);
1659 return NO_ERROR;
1660}
1661
Dan Gittik57e63c52019-01-18 16:37:54 +00001662status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1663 bool* outSupport) const {
1664 if (!displayToken || !outSupport) {
1665 return BAD_VALUE;
1666 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001667
1668 Mutex::Autolock lock(mStateLock);
1669
Dan Gittik57e63c52019-01-18 16:37:54 +00001670 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1671 if (!displayId) {
1672 return NAME_NOT_FOUND;
1673 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001674 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001675 return NO_ERROR;
1676}
1677
Alec Mouricdf16792021-12-10 13:16:06 -08001678bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1679 bool hasHdrLayers = false;
1680 mDrawingState.traverse([&,
1681 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1682 hasHdrLayers |= (layer->isVisible() &&
1683 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1684 isHdrDataspace(layer->getDataSpace()));
1685 });
1686 return hasHdrLayers;
1687}
1688
John Reck22be6962021-03-10 12:59:54 -05001689status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1690 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001691 if (!displayToken) {
1692 return BAD_VALUE;
1693 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001694
Dominik Laskowski756b7892021-08-04 12:53:59 -07001695 const char* const whence = __func__;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001696 return ftl::Future(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001697 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001698 const bool supportsDisplayBrightnessCommand =
1699 getHwComposer().getComposer()->isSupported(
1700 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1701 // If we support applying display brightness as a command, then we also support
1702 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001703 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001704 auto compositionDisplay = display->getCompositionDisplay();
1705 float currentDimmingRatio =
1706 compositionDisplay->editState().sdrWhitePointNits /
1707 compositionDisplay->editState().displayBrightnessNits;
1708 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1709 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001710 FTL_FAKE_GUARD(kMainThreadContext,
1711 display->stageBrightness(brightness.displayBrightness));
1712
Alec Mouri6da0e272022-02-07 12:45:57 -08001713 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1714 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001715 scheduleComposite(FrameHint::kNone);
1716 } else {
1717 scheduleCommit(FrameHint::kNone);
1718 }
1719 return ftl::yield<status_t>(OK);
1720 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001721 return getHwComposer()
1722 .setDisplayBrightness(display->getPhysicalId(),
1723 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001724 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001725 Hwc2::Composer::DisplayBrightnessOptions{
1726 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001727 }
Alec Mouricdf16792021-12-10 13:16:06 -08001728
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001729 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001730 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001731 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001732 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001733 }))
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001734 .then([](ftl::Future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001735 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001736}
1737
John Reck88270902021-03-18 11:27:35 -04001738status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1739 const sp<gui::IHdrLayerInfoListener>& listener) {
1740 if (!displayToken) {
1741 return BAD_VALUE;
1742 }
1743
1744 Mutex::Autolock lock(mStateLock);
1745
1746 const auto display = getDisplayDeviceLocked(displayToken);
1747 if (!display) {
1748 return NAME_NOT_FOUND;
1749 }
1750 const auto displayId = display->getId();
1751 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1752 if (!hdrInfoReporter) {
1753 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1754 }
1755 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001756
1757
1758 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001759 return OK;
1760}
1761
1762status_t SurfaceFlinger::removeHdrLayerInfoListener(
1763 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1764 if (!displayToken) {
1765 return BAD_VALUE;
1766 }
1767
1768 Mutex::Autolock lock(mStateLock);
1769
1770 const auto display = getDisplayDeviceLocked(displayToken);
1771 if (!display) {
1772 return NAME_NOT_FOUND;
1773 }
1774 const auto displayId = display->getId();
1775 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1776 if (hdrInfoReporter) {
1777 hdrInfoReporter->removeListener(listener);
1778 }
1779 return OK;
1780}
1781
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001782status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001783 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001784 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001785
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001786 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001787 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001788 }
1789
1790 return NO_ERROR;
1791}
1792
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001793status_t SurfaceFlinger::getDisplayDecorationSupport(
1794 const sp<IBinder>& displayToken,
1795 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001796 if (!displayToken || !outSupport) {
1797 return BAD_VALUE;
1798 }
1799
1800 Mutex::Autolock lock(mStateLock);
1801
1802 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1803 if (!displayId) {
1804 return NAME_NOT_FOUND;
1805 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001806 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001807 return NO_ERROR;
1808}
1809
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001810// ----------------------------------------------------------------------------
1811
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001812sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001813 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001814 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001815 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1816 ? mSfConnectionHandle
1817 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001818
Ady Abraham62f216c2020-10-13 19:07:23 -07001819 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001820}
1821
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001822void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001823 if (hint == FrameHint::kActive) {
1824 mScheduler->resetIdleTimer();
1825 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001826 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001827 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001828}
1829
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001830void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1831 mMustComposite = true;
1832 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001833}
1834
1835void SurfaceFlinger::scheduleRepaint() {
1836 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001837 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001838}
1839
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001840void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001841 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001842}
1843
Ady Abraham2492a022020-07-24 11:09:55 -07001844nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001845 if (const auto display = getDefaultDisplayDeviceLocked()) {
1846 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001847 }
1848
Marin Shalamanov045b7002021-01-07 16:56:24 +01001849 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001850}
1851
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001852void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1853 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001854 const std::string tracePeriod = [vsyncPeriod]() {
1855 if (ATRACE_ENABLED() && vsyncPeriod) {
1856 std::stringstream ss;
1857 ss << "(" << *vsyncPeriod << ")";
1858 return ss.str();
1859 }
1860 return std::string();
1861 }();
1862 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001863
Steven Thomas3cfac282017-02-06 12:29:30 -08001864 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001865 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1866 if (displayId) {
1867 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1868 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001869 display->onVsync(timestamp);
1870 }
1871
Dominik Laskowski075d3172018-05-24 15:50:06 -07001872 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001873 return;
1874 }
1875
Ady Abrahame1166472021-07-15 10:56:06 -07001876 const bool isActiveDisplay =
1877 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1878 if (!isActiveDisplay) {
1879 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001880 return;
1881 }
1882
Alec Mourif8e689c2019-05-20 18:32:22 -07001883 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001884 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001885 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001886 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001887 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001888}
1889
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001890void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001891 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1892 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001893}
1894
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001895void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1896 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001897 const bool connected = connection == hal::Connection::CONNECTED;
1898 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001899
Steven Thomasb02664d2017-07-26 18:48:28 -07001900 // Only lock if we're not on the main thread. This function is normally
1901 // called on a hwbinder thread, but for the primary display it's called on
1902 // the main thread with the state lock already held, so don't attempt to
1903 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001904 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001905
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001906 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001907
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001908 if (std::this_thread::get_id() == mMainThreadId) {
1909 // Process all pending hot plug events immediately if we are on the main thread.
1910 processDisplayHotplugEventsLocked();
1911 }
1912
Lloyd Piqueba04e622017-12-14 17:11:26 -08001913 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001914}
1915
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001916void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1917 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001918 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001919 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001920
1921 if (timeline.refreshRequired) {
1922 scheduleComposite(FrameHint::kNone);
1923 }
Ady Abraham7159f572019-10-11 11:10:18 -07001924}
1925
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001926void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001927 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001928 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1929}
1930
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001931void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001932 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001933 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001934}
1935
Yichi Chen3401b562022-01-17 15:42:35 +08001936void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001937 ATRACE_CALL();
1938 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001939}
1940
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001941void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001942 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001943
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001944 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001945 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001946 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001947
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001948 if (const auto display = getDefaultDisplayDeviceLocked();
1949 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001950 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001951 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001952 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001953}
1954
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001955SurfaceFlinger::FenceWithFenceTime SurfaceFlinger::previousFrameFence() {
Ady Abrahamccf4b472021-05-11 19:53:01 -07001956 const auto now = systemTime();
1957 const auto vsyncPeriod = mScheduler->getDisplayStatInfo(now).vsyncPeriod;
1958 const bool expectedPresentTimeIsTheNextVsync = mExpectedPresentTime - now <= vsyncPeriod;
1959 return expectedPresentTimeIsTheNextVsync ? mPreviousPresentFences[0]
1960 : mPreviousPresentFences[1];
Alec Mouri6d414b52020-03-17 11:18:05 -07001961}
1962
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001963bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001964 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001965 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001966
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001967 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001968 return false;
1969 }
1970
Dan Stoza59083052020-04-28 10:13:20 -07001971 const status_t status = fence->wait(graceTimeMs);
1972 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1973 // which calls wait(0) again internally
1974 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001975}
1976
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001977nsecs_t SurfaceFlinger::previousFramePresentTime() {
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001978 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001979
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001980 if (fence == FenceTime::NO_FENCE) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001981 return Fence::SIGNAL_TIME_INVALID;
1982 }
1983
1984 return fence->getSignalTime();
1985}
1986
Ady Abraham56b42a42020-12-28 16:48:48 -08001987nsecs_t SurfaceFlinger::calculateExpectedPresentTime(DisplayStatInfo stats) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001988 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham8cb21882020-08-26 18:22:05 -07001989 return mVsyncModulator->getVsyncConfig().sfOffset > 0 ? stats.vsyncTime
1990 : stats.vsyncTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001991}
1992
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001993bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1994 FTL_FAKE_GUARD(kMainThreadContext) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001995 // calculate the expected present time once and use the cached
1996 // value throughout this frame to make sure all layers are
1997 // seeing this same value.
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001998 if (expectedVsyncTime >= frameTime) {
1999 mExpectedPresentTime = expectedVsyncTime;
Snild Dolkow819636c2021-01-22 14:42:08 +01002000 } else {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002001 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(frameTime);
Snild Dolkow819636c2021-01-22 14:42:08 +01002002 mExpectedPresentTime = calculateExpectedPresentTime(stats);
2003 }
2004
2005 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002006 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07002007
Ady Abraham893c99d2021-04-30 16:00:23 -07002008 const auto vsyncIn = [&] {
2009 if (!ATRACE_ENABLED()) return 0.f;
2010 return (mExpectedPresentTime - systemTime()) / 1e6f;
2011 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002012 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
2013 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002014
Dan Stoza28d46a52020-04-28 09:54:54 -07002015 // When Backpressure propagation is enabled we want to give a small grace period
2016 // for the present fence to fire instead of just giving up on this frame to handle cases
2017 // where present fence is just about to get signaled.
2018 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002019 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002020
2021 // Pending frames may trigger backpressure propagation.
2022 const TracedOrdinal<bool> framePending = {"PrevFramePending",
2023 previousFramePending(graceTimeForPresentFenceMs)};
2024
2025 // Frame missed counts for metrics tracking.
2026 // A frame is missed if the prior frame is still pending. If no longer pending,
2027 // then we still count the frame as missed if the predicted present time
2028 // was further in the past than when the fence actually fired.
2029
2030 // Add some slop to correct for drift. This should generally be
2031 // smaller than a typical frame duration, but should not be so small
2032 // that it reports reasonable drift as a missed frame.
Ady Abrahame90dd522020-12-29 12:08:45 -08002033 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(systemTime());
Dan Stoza28d46a52020-04-28 09:54:54 -07002034 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
2035 const nsecs_t previousPresentTime = previousFramePresentTime();
2036 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2037 framePending ||
2038 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002039 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002040 previousPresentTime - frameMissedSlop))};
2041 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2042 mHadDeviceComposition && frameMissed};
2043 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2044 mHadClientComposition && frameMissed};
2045
2046 if (frameMissed) {
2047 mFrameMissedCount++;
2048 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002049 }
2050
2051 if (hwcFrameMissed) {
2052 mHwcFrameMissedCount++;
2053 }
2054
2055 if (gpuFrameMissed) {
2056 mGpuFrameMissedCount++;
2057 }
2058
Vishnu Nair286f4f92022-06-08 16:37:39 -07002059 if (mTracingEnabledChanged) {
2060 mLayerTracingEnabled = mLayerTracing.isEnabled();
2061 mTracingEnabledChanged = false;
2062 }
2063
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002064 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002065 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002066 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002067 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002068 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002069 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002070 }
2071
2072 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002073 // the mode, hence we update SF.
2074 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002075 {
2076 Mutex::Autolock lock(mStateLock);
2077 updateInternalStateWithChangedMode();
2078 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002079 }
2080
John Reck2ec53912020-07-07 16:53:55 -07002081 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002082 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002083 scheduleCommit(FrameHint::kNone);
2084 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002085 }
2086 }
2087
Matt Buckley50c44062022-01-17 20:48:10 +00002088 // Save this once per commit + composite to ensure consistency
2089 mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession();
2090 if (mPowerHintSessionEnabled) {
2091 nsecs_t vsyncPeriod;
2092 {
2093 Mutex::Autolock lock(mStateLock);
2094 vsyncPeriod = getVsyncPeriodFromHWC();
2095 }
2096 mPowerAdvisor->setCommitStart(frameTime);
2097 mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime);
2098 const nsecs_t idealSfWorkDuration =
2099 mVsyncModulator->getVsyncConfig().sfWorkDuration.count();
2100 // Frame delay is how long we should have minus how long we actually have
2101 mPowerAdvisor->setFrameDelay(idealSfWorkDuration - (mExpectedPresentTime - frameTime));
2102 mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration);
2103 mPowerAdvisor->setTargetWorkDuration(vsyncPeriod);
2104
2105 // Send early hint here to make sure there's not another frame pending
2106 if (mPowerHintSessionMode.early) {
2107 // Send a rough prediction for this frame based on last frame's timing info
2108 mPowerAdvisor->sendPredictedWorkDuration();
2109 }
2110 }
2111
Ady Abraham29d0da32020-07-16 18:39:33 -07002112 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002113 Mutex::Autolock lock(mStateLock);
2114 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002115 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002116 }
2117 }
2118
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002119 // Composite if transactions were committed, or if requested by HWC.
2120 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002121 {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002122 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(stats.vsyncPeriod));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002123
chaviw6b9ffea2021-11-08 09:25:48 -06002124 bool needsTraversal = false;
2125 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07002126 needsTraversal |= commitCreatedLayers(vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002127 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002128 }
2129
2130 const bool shouldCommit =
2131 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2132 if (shouldCommit) {
2133 commitTransactions();
2134 }
2135
2136 if (transactionFlushNeeded()) {
2137 setTransactionFlags(eTransactionFlushNeeded);
2138 }
2139
2140 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002141 mustComposite |= latchBuffers();
2142
chaviw6b9ffea2021-11-08 09:25:48 -06002143 // This has to be called after latchBuffers because we want to include the layers that have
2144 // been latched in the commit callback
2145 if (!needsTraversal) {
2146 // Invoke empty transaction callbacks early.
2147 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2148 } else {
2149 // Invoke OnCommit callbacks.
2150 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2151 }
2152
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002153 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002154 }
2155
2156 // Layers need to get updated (in the previous line) before we can use them for
2157 // choosing the refresh rate.
2158 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2159 // and may eventually call to ~Layer() if it holds the last reference
2160 {
2161 Mutex::Autolock _l(mStateLock);
2162 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002163 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002164 }
2165
Dan Stoza28d46a52020-04-28 09:54:54 -07002166 updateCursorAsync();
2167 updateInputFlinger();
2168
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002169 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2170 // This will block and tracing should only be enabled for debugging.
Pablo Gamitob8775792022-06-10 15:02:42 +00002171 mLayerTracing.notify(mVisibleRegionsDirty, frameTime, vsyncId);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002172 }
Pablo Gamito6be82442022-06-13 11:04:34 +00002173 mLastCommittedVsyncId = vsyncId;
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002174
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002175 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002176
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002177 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002178}
2179
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002180void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2181 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002182 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002183
Lloyd Piqueab039b52019-02-13 14:22:42 -08002184 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002185 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002186 refreshArgs.outputs.reserve(displays.size());
Matt Buckley50c44062022-01-17 20:48:10 +00002187 std::vector<DisplayId> displayIds;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002188 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002189 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Matt Buckley50c44062022-01-17 20:48:10 +00002190 displayIds.push_back(display->getId());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002191 }
Matt Buckley50c44062022-01-17 20:48:10 +00002192 mPowerAdvisor->setDisplays(displayIds);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002193 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002194 if (auto layerFE = layer->getCompositionEngineLayerFE())
2195 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002196 });
Tianhao Yao67dd7122022-02-22 17:48:33 +00002197
2198 if (DOES_CONTAIN_BORDER) {
2199 refreshArgs.borderInfoList.clear();
2200 mDrawingState.traverse([&refreshArgs](Layer* layer) {
2201 if (layer->isBorderEnabled()) {
2202 compositionengine::BorderRenderInfo info;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00002203 info.width = layer->getBorderWidth();
2204 info.color = layer->getBorderColor();
Tianhao Yao67dd7122022-02-22 17:48:33 +00002205 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2206 info.layerIds.push_back(ilayer->getSequence());
2207 });
2208 refreshArgs.borderInfoList.emplace_back(std::move(info));
2209 }
2210 });
2211 }
2212
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002213 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002214 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002215 if (auto layerFE = layer->getCompositionEngineLayerFE())
2216 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002217 }
2218
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002219 refreshArgs.outputColorSetting = useColorManagement
2220 ? mDisplayColorSetting
2221 : compositionengine::OutputColorSetting::kUnmanaged;
2222 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2223 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002224
2225 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002226 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002227 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002228 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002229
2230 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2231 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2232 mDrawingState.colorMatrixChanged = false;
2233 }
2234
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002235 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002236
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002237 if (mDebugFlashDelay != 0) {
2238 refreshArgs.devOptForceClientComposition = true;
2239 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002240 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002241
Ady Abraham43065bd2021-12-10 17:22:15 -08002242 const auto expectedPresentTime = mExpectedPresentTime.load();
2243 const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
Ady Abrahamcaba2982021-06-16 16:45:04 -07002244 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2245 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002246 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002247 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002248 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002249
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002250 // Store the present time just before calling to the composition engine so we could notify
2251 // the scheduler.
2252 const auto presentTime = systemTime();
2253
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002254 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002255
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002256 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002257
Matt Buckley50c44062022-01-17 20:48:10 +00002258 // Send a power hint hint after presentation is finished
2259 if (mPowerHintSessionEnabled) {
2260 if (mPowerHintSessionMode.late) {
2261 mPowerAdvisor->sendActualWorkDuration();
2262 }
2263 }
2264
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002265 if (mScheduler->onPostComposition(presentTime)) {
2266 scheduleComposite(FrameHint::kNone);
2267 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002268
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002269 postFrame();
2270 postComposition();
2271
Midas Chien50f52e22020-09-26 17:57:42 +08002272 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002273
Vishnu Nair9cf89262022-02-26 09:17:49 -08002274 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2275 TimeStats::ClientCompositionRecord clientCompositionRecord;
2276 for (const auto& [_, display] : displays) {
2277 const auto& state = display->getCompositionDisplay()->getState();
2278 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2279 mHadDeviceComposition |= state.usesDeviceComposition;
2280 mReusedClientComposition |= state.reusedClientComposition;
2281 clientCompositionRecord.predicted |=
2282 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2283 clientCompositionRecord.predictionSucceeded |=
2284 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002285 }
2286
Vishnu Nair9cf89262022-02-26 09:17:49 -08002287 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2288 clientCompositionRecord.reused = mReusedClientComposition;
2289 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2290 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2291
Yichi Chen28dee2c2020-07-06 21:24:14 +08002292 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002293 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2294 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002295
David Sodman7e4ae112018-02-09 15:02:28 -08002296 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002297 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002298 // This will block and should only be used for debugging.
Pablo Gamitob8775792022-06-10 15:02:42 +00002299 mLayerTracing.notify(mVisibleRegionsDirty, frameTime, vsyncId);
Vishnu Nairdf529052019-06-07 14:53:14 -07002300 }
Robert Carr167bdde2021-07-28 11:26:51 -07002301
2302 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002303 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002304
2305 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002306 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002307 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002308
Matt Buckley50c44062022-01-17 20:48:10 +00002309 if (mPowerHintSessionEnabled) {
2310 mPowerAdvisor->setCompositeEnd(systemTime());
Matt Buckleyef51fba2021-10-12 19:30:12 +00002311 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002312}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002313
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002314void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002315 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002316
Vishnu Nair4351ad52019-02-11 14:13:02 -08002317 if (mVisibleRegionsDirty) {
2318 computeLayerBounds();
2319 }
2320
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002321 for (auto& layer : mLayersPendingRefresh) {
2322 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002323 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002324 invalidateLayerStack(layer, visibleReg);
2325 }
2326 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002327}
2328
Ana Krulece588e312018-09-18 12:32:24 -07002329void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2330 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002331 // Update queue of past composite+present times and determine the
2332 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002333 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002334 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002335 while (!getBE().mCompositePresentTimes.empty()) {
2336 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002337 // Cached values should have been updated before calling this method,
2338 // which helps avoid duplicate syscalls.
2339 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2340 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2341 break;
2342 }
2343 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002344 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002345 }
2346
2347 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002348 while (getBE().mCompositePresentTimes.size() > 16) {
2349 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002350 }
2351
Ana Krulece588e312018-09-18 12:32:24 -07002352 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002353}
2354
Ana Krulece588e312018-09-18 12:32:24 -07002355void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2356 nsecs_t compositeToPresentLatency) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002357 // Avoid division by 0 by defaulting to 60Hz
2358 const auto vsyncPeriod = stats.vsyncPeriod ?: (60_Hz).getPeriodNsecs();
2359
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002360 // Integer division and modulo round toward 0 not -inf, so we need to
2361 // treat negative and positive offsets differently.
Ady Abraham8287e852020-08-12 14:44:58 -07002362 nsecs_t idealLatency = (mVsyncConfiguration->getCurrentConfigs().late.sfOffset > 0)
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002363 ? (vsyncPeriod -
2364 (mVsyncConfiguration->getCurrentConfigs().late.sfOffset % vsyncPeriod))
2365 : ((-mVsyncConfiguration->getCurrentConfigs().late.sfOffset) % vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002366
Ady Abraham8287e852020-08-12 14:44:58 -07002367 // Just in case mVsyncConfiguration->getCurrentConfigs().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002368 if (idealLatency <= 0) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002369 idealLatency = vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002370 }
2371
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002372 // Snap the latency to a value that removes scheduling jitter from the
2373 // composition and present times, which often have >1ms of jitter.
2374 // Reducing jitter is important if an app attempts to extrapolate
2375 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002376 // Snapping also allows an app to precisely calculate
Ady Abraham8287e852020-08-12 14:44:58 -07002377 // mVsyncConfiguration->getCurrentConfigs().late.sf with (presentLatency % interval).
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002378 const nsecs_t bias = vsyncPeriod / 2;
2379 const int64_t extraVsyncs = ((compositeToPresentLatency - idealLatency + bias) / vsyncPeriod);
Ady Abraham8d7e7842022-02-03 01:42:45 +00002380 const nsecs_t snappedCompositeToPresentLatency =
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002381 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002382
David Sodman99974d22017-11-28 12:04:33 -08002383 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002384 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002385 getBE().mCompositorTiming.interval = vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002386 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002387}
2388
John Reck49d9ad32022-02-23 19:03:31 -05002389bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002390 // Treat all layers as non-HDR if:
2391 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2392 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2393 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2394 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2395 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002396 return false;
2397 }
2398 if (mIgnoreHdrCameraLayers) {
2399 auto buffer = layer->getBuffer();
2400 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2401 return false;
2402 }
2403 }
2404 return true;
2405}
2406
ramindani06e518e2022-03-14 18:47:53 +00002407ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2408 bool isPrimary) const {
2409 const auto id = PhysicalDisplayId::tryCast(displayId);
2410 if (!id) {
2411 return ui::ROTATION_0;
2412 }
2413 if (getHwComposer().getComposer()->isSupported(
2414 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2415 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2416 case Hwc2::AidlTransform::ROT_90:
2417 return ui::ROTATION_90;
2418 case Hwc2::AidlTransform::ROT_180:
2419 return ui::ROTATION_180;
2420 case Hwc2::AidlTransform::ROT_270:
2421 return ui::ROTATION_270;
2422 default:
2423 return ui::ROTATION_0;
2424 }
2425 }
2426
2427 if (isPrimary) {
2428 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2429 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2430 case Values::ORIENTATION_90:
2431 return ui::ROTATION_90;
2432 case Values::ORIENTATION_180:
2433 return ui::ROTATION_180;
2434 case Values::ORIENTATION_270:
2435 return ui::ROTATION_270;
2436 default:
2437 break;
2438 }
2439 }
2440 return ui::ROTATION_0;
2441}
2442
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002443void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002444 ATRACE_CALL();
2445 ALOGV("postComposition");
2446
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002447 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002448
2449 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002450 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002451 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002452 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002453 ->getRenderSurface()
2454 ->getClientTargetAcquireFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002455 } else {
2456 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2457 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002458
Ady Abrahambe0f9482019-04-24 15:41:53 -07002459 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002460 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002461 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002462 mPreviousPresentFences[0].fenceTime =
2463 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2464
Vishnu Nair9a69a042021-06-18 13:19:49 -07002465 nsecs_t now = systemTime();
2466
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002467 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2468 // information from previous' frame classification is already available when sending jank info
2469 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002470 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002471 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002472
Vishnu Nair9a69a042021-06-18 13:19:49 -07002473 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002474
Lloyd Piqueab039b52019-02-13 14:22:42 -08002475 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2476 // be sampled a little later than when we started doing work for this frame,
2477 // but that should be okay since updateCompositorTiming has snapping logic.
2478 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002479 mPreviousPresentFences[0].fenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002480 CompositorTiming compositorTiming;
2481 {
David Sodman99974d22017-11-28 12:04:33 -08002482 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2483 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002484 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002485
Robert Carrc747ad02021-06-11 14:01:24 -07002486 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002487 layer->onPostComposition(display, glCompositionDoneFenceTime,
2488 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002489 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002490 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002491
John Reck88270902021-03-18 11:27:35 -04002492 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2493 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002494 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002495 {
2496 Mutex::Autolock lock(mStateLock);
2497 if (mFpsReporter) {
2498 mFpsReporter->dispatchLayerFps();
2499 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002500
2501 if (mTunnelModeEnabledReporter) {
2502 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2503 }
John Reck88270902021-03-18 11:27:35 -04002504 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002505 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2506 if (reporter && reporter->hasListeners()) {
2507 if (const auto display = getDisplayDeviceLocked(displayId)) {
2508 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002509 }
2510 }
2511 }
Robert Carr167bdde2021-07-28 11:26:51 -07002512 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2513 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002514 }
2515
Robert Carr167bdde2021-07-28 11:26:51 -07002516 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2517 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2518 HdrLayerInfoReporter::HdrLayerInfo info;
2519 int32_t maxArea = 0;
2520 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2521 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002522 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002523 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002524 const auto* outputLayer =
2525 compositionDisplay->getOutputLayerForLayer(layerFe);
2526 if (outputLayer) {
2527 info.numberOfHdrLayers++;
2528 const auto displayFrame = outputLayer->getState().displayFrame;
2529 const int32_t area = displayFrame.width() * displayFrame.height();
2530 if (area > maxArea) {
2531 maxArea = area;
2532 info.maxW = displayFrame.width();
2533 info.maxH = displayFrame.height();
2534 }
John Reckdb1a16b2021-07-09 13:05:52 -04002535 }
John Reck88270902021-03-18 11:27:35 -04002536 }
2537 }
Robert Carr167bdde2021-07-28 11:26:51 -07002538 });
2539 listener->dispatchHdrLayerInfo(info);
2540 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002541 }
2542
Robert Carr167bdde2021-07-28 11:26:51 -07002543 mSomeDataspaceChanged = false;
2544 mVisibleRegionsWereDirtyThisFrame = false;
2545
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002546 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002547 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002548 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002549
Ady Abrahamed3290f2021-05-17 15:12:14 -07002550 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002551 mPreviousPresentFences[0].fenceTime->isValid()) {
2552 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002553 }
2554
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002555 const bool isDisplayConnected =
2556 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002557
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002558 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002559 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002560 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002561 }
2562 }
2563
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002564 if (mAnimCompositionPending) {
2565 mAnimCompositionPending = false;
2566
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002567 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2568 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002569 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002570 // The HWC doesn't support present fences, so use the refresh
2571 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002572 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002573 mAnimFrameTracker.setActualPresentTime(presentTime);
2574 }
2575 mAnimFrameTracker.advanceFrame();
2576 }
Dan Stozab90cf072015-03-05 11:05:59 -08002577
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002578 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002579
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002580 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002581
Alec Mouri717bcb62020-02-10 17:07:19 -08002582 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2583 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2584 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2585
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002586 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002587 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002588 return;
2589 }
2590
2591 nsecs_t currentTime = systemTime();
2592 if (mHasPoweredOff) {
2593 mHasPoweredOff = false;
2594 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002595 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002596 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002597 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2598 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002599 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002600 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002601 }
David Sodman4a36e932017-11-07 14:29:47 -08002602 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002603 }
David Sodman4a36e932017-11-07 14:29:47 -08002604 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002605
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002606 // Cleanup any outstanding resources due to rendering a prior frame.
2607 getRenderEngine().cleanupPostRender();
2608
Dan Stoza436ccf32018-06-21 12:10:12 -07002609 {
2610 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002611 if (mTexturePool.size() < mTexturePoolSize) {
2612 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002613 const size_t offset = mTexturePool.size();
2614 mTexturePool.resize(mTexturePoolSize);
2615 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2616 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002617 } else if (mTexturePool.size() > mTexturePoolSize) {
2618 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2619 const size_t offset = mTexturePoolSize;
2620 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2621 mTexturePool.resize(mTexturePoolSize);
2622 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002623 }
2624 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002625
Dan Stoza45de5ba2019-04-25 14:12:09 -07002626 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2627 // side-effect of getTotalSize(), so we check that again here
2628 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002629 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002630 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2631 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002632}
2633
chaviw79468ab2021-10-27 11:11:24 -05002634FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002635 const ui::Size maxSize = [this] {
2636 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002637
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002638 // The LayerTraceGenerator tool runs without displays.
2639 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002640
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002641 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2642 [](ui::Size size, const auto& pair) -> ui::Size {
2643 const auto& display = pair.second;
2644 return {std::max(size.getWidth(), display->getWidth()),
2645 std::max(size.getHeight(), display->getHeight())};
2646 });
2647 }();
chaviwb09c6552021-08-12 17:20:43 -05002648
2649 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2650 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002651 const float xMax = maxSize.getWidth() * 10.f;
2652 const float yMax = maxSize.getHeight() * 10.f;
2653
2654 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002655}
2656
2657void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002658 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002659 for (const auto& layer : mDrawingState.layersSortedByZ) {
2660 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002661 }
2662}
2663
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002664void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002665 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002666 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002667 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002668 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2669 logFrameStats();
2670 }
2671 }
2672}
2673
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002674void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002675 ATRACE_CALL();
2676
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002677 // Keep a copy of the drawing state (that is going to be overwritten
2678 // by commitTransactionsLocked) outside of mStateLock so that the side
2679 // effects of the State assignment don't happen with mStateLock held,
2680 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002681 State drawingState(mDrawingState);
2682
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002683 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002684 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685
Mathias Agopianca4d3602011-05-19 15:38:14 -07002686 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002687 // so we can call commitTransactionsLocked unconditionally.
2688 // We clear the flags with mStateLock held to guarantee that
2689 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002690 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002691 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002692
Mathias Agopianca4d3602011-05-19 15:38:14 -07002693 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002694}
2695
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002696std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2697 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002698 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2699 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002700
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002701 int attempt = 0;
2702 constexpr int kMaxAttempts = 3;
2703 do {
2704 hwcModes = getHwComposer().getModes(displayId);
2705 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2706 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2707
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002708 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2709 return mode.hwcId == *activeModeHwcId;
2710 };
2711
2712 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2713 break;
2714 }
2715 } while (++attempt < kMaxAttempts);
2716
2717 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002718 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002719 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002720 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002721
2722 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002723 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2724 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002725 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002726
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002727 ui::DisplayModeId nextModeId = 1 +
2728 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2729 [](ui::DisplayModeId max, const auto& pair) {
2730 return std::max(max, pair.first.value());
2731 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002732
2733 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002734 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002735 const DisplayModeId id{nextModeId++};
2736 newModes.try_emplace(id,
2737 DisplayMode::Builder(hwcMode.hwcId)
2738 .setId(id)
2739 .setPhysicalDisplayId(displayId)
2740 .setResolution({hwcMode.width, hwcMode.height})
2741 .setVsyncPeriod(hwcMode.vsyncPeriod)
2742 .setDpiX(hwcMode.dpiX)
2743 .setDpiY(hwcMode.dpiY)
2744 .setGroup(hwcMode.configGroup)
2745 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002746 }
2747
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002748 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002749 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002750 [](const auto& lhs, const auto& rhs) {
2751 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002752 });
2753
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002754 // Keep IDs if modes have not changed.
2755 const auto& modes = sameModes ? oldModes : newModes;
2756 const DisplayModePtr activeMode =
2757 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2758 return pair.second->getHwcId() == activeModeHwcId;
2759 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002760
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002761 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002762}
2763
Lloyd Piqueba04e622017-12-14 17:11:26 -08002764void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2765 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002766 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002767 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002768
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002770 continue;
2771 }
2772
Marin Shalamanova524a092020-07-27 21:39:55 +02002773 const auto displayId = info->id;
Dominik Laskowskieb627312022-04-07 09:13:16 -07002774 const auto token = mPhysicalDisplayTokens.get(displayId);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002775
Peiyong Line9d809e2020-04-14 13:10:48 -07002776 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002777 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002778
Dominik Laskowskieb627312022-04-07 09:13:16 -07002779 if (!token) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002780 ALOGV("Creating display %s", to_string(displayId).c_str());
2781
Dominik Laskowski075d3172018-05-24 15:50:06 -07002782 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002783 state.physical = {.id = displayId,
2784 .type = getHwComposer().getDisplayConnectionType(displayId),
2785 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002786 .deviceProductInfo = std::move(info->deviceProductInfo),
2787 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002788 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002789 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002790 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002791
2792 sp<IBinder> token = new BBinder();
2793 mCurrentState.displays.add(token, state);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002794 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002795 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002796 } else {
2797 ALOGV("Recreating display %s", to_string(displayId).c_str());
2798
Dominik Laskowskieb627312022-04-07 09:13:16 -07002799 auto& state = mCurrentState.displays.editValueFor(token->get());
2800 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
Marin Shalamanova903d032020-12-29 20:35:13 +01002801 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002802 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002803 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2804 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2805 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002806 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002807 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002808 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002809
Dominik Laskowskieb627312022-04-07 09:13:16 -07002810 if (const ssize_t index = mCurrentState.displays.indexOfKey(token->get()); index >= 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002811 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2812 mInterceptor->saveDisplayDeletion(state.sequenceId);
2813 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002814 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002815
2816 mPhysicalDisplayTokens.erase(displayId);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002817 }
2818
2819 processDisplayChangesLocked();
2820 }
2821
2822 mPendingHotplugEvents.clear();
2823}
2824
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002825void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002826 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2827 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002828 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2829 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002830}
2831
Lloyd Pique99d3da52018-01-22 17:48:03 -08002832sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002833 const wp<IBinder>& displayToken,
2834 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002835 const DisplayDeviceState& state,
2836 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002837 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002838 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002839 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002840 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002841 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002842 creationArgs.hasWideColorGamut = false;
2843 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002844
Dominik Laskowski55c85402020-01-21 16:25:47 -08002845 if (const auto& physical = state.physical) {
2846 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002847 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002848 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002849 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2850 getKernelIdleTimerProperties(compositionDisplay->getId());
2851
Ady Abraham3efa3942021-06-24 19:01:25 -07002852 scheduler::RefreshRateConfigs::Config config =
2853 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2854 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002855 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002856 .idleTimerTimeout = idleTimerTimeoutMs,
2857 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002858 creationArgs.refreshRateConfigs =
2859 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2860 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002861 }
2862
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002863 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002864 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002865
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002866 if (useColorManagement) {
2867 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2868 for (ColorMode colorMode : modes) {
2869 if (isWideColorMode(colorMode)) {
2870 creationArgs.hasWideColorGamut = true;
2871 }
2872
2873 std::vector<RenderIntent> renderIntents =
2874 getHwComposer().getRenderIntents(*id, colorMode);
2875 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002876 }
2877 }
tangrobin6753a022018-08-10 10:58:54 +08002878 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002879
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002880 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2881 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2882 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002883 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002884
Lloyd Pique90c115d2018-09-18 21:39:42 -07002885 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002886 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002887 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002888
Lloyd Pique99d3da52018-01-22 17:48:03 -08002889 // Make sure that composition can never be stalled by a virtual display
2890 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002891 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002892 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002893 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2894 }
2895
Dominik Laskowski718f9602019-11-09 20:01:35 -08002896 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002897 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2898 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002899
Lloyd Pique99d3da52018-01-22 17:48:03 -08002900 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002901 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002902
Lloyd Pique9370a482019-10-03 17:58:30 -07002903 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002904
Ady Abraham8565ad22021-06-22 17:45:44 -07002905 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002906
2907 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002908 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002909 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002910 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002911 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002912 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002913 display->getCompositionDisplay()->setColorProfile(
2914 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2915 RenderIntent::COLORIMETRIC,
2916 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002917 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002918 FTL_FAKE_GUARD(kMainThreadContext,
2919 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002920 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002921 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002922
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002923 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002924 display->setProjection(state.orientation, state.layerStackSpaceRect,
2925 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002926 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002927 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002928
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002929 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002930}
2931
Marin Shalamanovae685592020-02-12 17:12:22 +01002932void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2933 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002934 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002935 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2936 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002937 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002938 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2939 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002940 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002941 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002942 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002943 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002944 int format;
2945 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002946 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002947 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002948 } else {
2949 // Virtual displays without a surface are dormant:
2950 // they have external state (layer stack, projection,
2951 // etc.) but no internal state (i.e. a DisplayDevice).
2952 return;
2953 }
2954
2955 compositionengine::DisplayCreationArgsBuilder builder;
2956 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002957 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002958 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002959 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002960 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002961
Marin Shalamanov045b7002021-01-07 16:56:24 +01002962 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002963 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002964 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002965 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002966 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002967 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002968
2969 sp<compositionengine::DisplaySurface> displaySurface;
2970 sp<IGraphicBufferProducer> producer;
2971 sp<IGraphicBufferProducer> bqProducer;
2972 sp<IGraphicBufferConsumer> bqConsumer;
2973 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2974
Marin Shalamanovae685592020-02-12 17:12:22 +01002975 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002976 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2977 LOG_FATAL_IF(!displayId);
2978 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2979 bqProducer, bqConsumer, state.displayName);
2980 displaySurface = surface;
2981 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002982 } else {
2983 ALOGE_IF(state.surface != nullptr,
2984 "adding a supported display, but rendering "
2985 "surface is provided (%p), ignoring it",
2986 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002987 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2988 LOG_FATAL_IF(!displayId);
2989 displaySurface =
2990 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002991 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002992 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002993 producer = bqProducer;
2994 }
2995
Marin Shalamanov700e6392020-02-12 20:22:26 +01002996 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002997 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2998 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002999 if (display->isPrimary()) {
3000 initScheduler(display);
3001 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003002 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003003 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01003004 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07003005
3006 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01003007}
3008
3009void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08003010 auto display = getDisplayDeviceLocked(displayToken);
3011 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01003012 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003013
3014 if (display->isVirtual()) {
3015 releaseVirtualDisplay(display->getVirtualId());
3016 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003017 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01003018 }
3019 }
3020
3021 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08003022
3023 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07003024 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08003025 // Destroy the display without holding the mStateLock.
3026 // This is a temporary solution until we can manage transaction queues without
3027 // holding the mStateLock.
3028 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
3029 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
3030 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
3031 // ends up running on the main thread causing a deadlock since setTransactionstate
3032 // will try to acquire the mStateLock. Instead we extend the lifetime of
3033 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
3034 // The display will be disconnected and removed from the mDisplays list so it will
3035 // not be accessible.
3036 }));
3037 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003038}
3039
3040void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
3041 const DisplayDeviceState& currentState,
3042 const DisplayDeviceState& drawingState) {
3043 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3044 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003045
3046 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01003047 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02003048 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003049
Marin Shalamanovae685592020-02-12 17:12:22 +01003050 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3051 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003052 if (display->isVirtual()) {
3053 releaseVirtualDisplay(display->getVirtualId());
3054 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003055 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003056
Marin Shalamanovae685592020-02-12 17:12:22 +01003057 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003058
Marin Shalamanov700e6392020-02-12 20:22:26 +01003059 if (const auto& physical = currentState.physical) {
3060 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3061 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003062
Marin Shalamanovae685592020-02-12 17:12:22 +01003063 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003064
Marin Shalamanov700e6392020-02-12 20:22:26 +01003065 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003066 const auto display = getDisplayDeviceLocked(displayToken);
3067 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003068
3069 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003070 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003071 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003072 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003073 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003074 return;
3075 }
3076
3077 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3078 if (currentState.layerStack != drawingState.layerStack) {
3079 display->setLayerStack(currentState.layerStack);
3080 }
Evan Rosky2239b372021-05-20 13:43:47 -07003081 if (currentState.flags != drawingState.flags) {
3082 display->setFlags(currentState.flags);
3083 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003084 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003085 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3086 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3087 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3088 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003089 if (isDisplayActiveLocked(display)) {
3090 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003091 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003092 }
3093 if (currentState.width != drawingState.width ||
3094 currentState.height != drawingState.height) {
3095 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003096
Ady Abrahamed3290f2021-05-17 15:12:14 -07003097 if (isDisplayActiveLocked(display)) {
3098 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003099 }
3100 }
3101 }
3102}
Ady Abraham3efa3942021-06-24 19:01:25 -07003103void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003104 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003105 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003106 updatePhaseConfiguration(refreshRate);
3107 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003108}
Marin Shalamanovae685592020-02-12 17:12:22 +01003109
Lloyd Pique347200f2017-12-14 17:00:15 -08003110void SurfaceFlinger::processDisplayChangesLocked() {
3111 // here we take advantage of Vector's copy-on-write semantics to
3112 // improve performance by skipping the transaction entirely when
3113 // know that the lists are identical
3114 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3115 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3116 if (!curr.isIdenticalTo(draw)) {
3117 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003118
3119 // find the displays that were removed
3120 // (ie: in drawing state but not in current state)
3121 // also handle displays that changed
3122 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003123 for (size_t i = 0; i < draw.size(); i++) {
3124 const wp<IBinder>& displayToken = draw.keyAt(i);
3125 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003126 if (j < 0) {
3127 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003128 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003129 } else {
3130 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003131 const DisplayDeviceState& currentState = curr[j];
3132 const DisplayDeviceState& drawingState = draw[i];
3133 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003134 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003135 }
3136
3137 // find displays that were added
3138 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003139 for (size_t i = 0; i < curr.size(); i++) {
3140 const wp<IBinder>& displayToken = curr.keyAt(i);
3141 if (draw.indexOfKey(displayToken) < 0) {
3142 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003143 }
3144 }
3145 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003146
3147 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003148}
3149
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003150void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3151 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003152 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3153 if (displayTransactionNeeded) {
3154 processDisplayChangesLocked();
3155 processDisplayHotplugEventsLocked();
3156 }
Robert Carrb552ff52021-06-11 13:35:54 -07003157 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158
Robert Carre450fb52021-06-11 13:21:09 -07003159 if (mSomeChildrenChanged) {
3160 mVisibleRegionsDirty = true;
3161 mSomeChildrenChanged = false;
3162 }
3163
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003164 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003165 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003166 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003167 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003168 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003169 // the hint is set before we acquire a buffer from the surface texture.
3170 //
3171 // NOTE: layer transactions have taken place already, so we use their
3172 // drawing state. However, SurfaceFlinger's own transaction has not
3173 // happened yet, so we must use the current state layer list
3174 // (soon to become the drawing state list).
3175 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003176 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003177 ui::LayerStack layerStack;
3178
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003179 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003180 // NOTE: we rely on the fact that layers are sorted by
3181 // layerStack first (so we don't have to traverse the list
3182 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003183 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3184 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003185 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003186
3187 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003188 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003189 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3190 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003191 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003192
3193 // Pick the primary display if another display mirrors the layer.
3194 if (hintDisplay) {
3195 hintDisplay = nullptr;
3196 break;
3197 }
3198
3199 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003200 }
3201 }
Chet Haase91d25932013-04-11 15:24:55 -07003202
Vishnu Naire3066de2022-06-08 12:16:25 -07003203 if (!hintDisplay && mDisplays.size() > 0) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003204 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3205 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003206
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003207 // could be null when this layer is using a layerStack
3208 // that is not visible on any display. Also can occur at
3209 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003210 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003211 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003212
Vishnu Naire3066de2022-06-08 12:16:25 -07003213 if (hintDisplay) {
3214 layer->updateTransformHint(hintDisplay->getTransformHint());
3215 } else {
3216 ALOGW("Ignoring transform hint update for %s", layer->getDebugName());
3217 }
Robert Carr2047fae2016-11-28 14:09:09 -08003218 });
Mathias Agopian84300952012-11-21 16:02:13 -08003219 }
3220
Robert Carr1f0a16a2016-10-24 16:27:39 -07003221 if (mLayersAdded) {
3222 mLayersAdded = false;
3223 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003224 mVisibleRegionsDirty = true;
3225 }
3226
3227 // some layers might have been removed, so
3228 // we need to update the regions they're exposing.
3229 if (mLayersRemoved) {
3230 mLayersRemoved = false;
3231 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003232 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003233 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003234 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003235 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003236 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003237 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003238 }
Robert Carr2047fae2016-11-28 14:09:09 -08003239 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240 }
3241
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003242 doCommitTransactions();
3243 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3244 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003245}
3246
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003247void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003248 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003249 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003250 return;
3251 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003252
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003253 std::vector<WindowInfo> windowInfos;
3254 std::vector<DisplayInfo> displayInfos;
3255 bool updateWindowInfo = false;
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003256 if (mVisibleRegionsDirty || mInputInfoChanged) {
3257 mInputInfoChanged = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003258 updateWindowInfo = true;
3259 buildWindowInfos(windowInfos, displayInfos);
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003260 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003261 if (!updateWindowInfo && mInputWindowCommands.empty()) {
3262 return;
3263 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003264 BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
3265 windowInfos = std::move(windowInfos),
3266 displayInfos = std::move(displayInfos),
3267 inputWindowCommands =
3268 std::move(mInputWindowCommands),
3269 inputFlinger = mInputFlinger, this]() {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003270 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3271 if (updateWindowInfo) {
3272 mWindowInfosListenerInvoker->windowInfosChanged(windowInfos, displayInfos,
3273 inputWindowCommands.syncInputWindows);
3274 } else if (inputWindowCommands.syncInputWindows) {
3275 // If the caller requested to sync input windows, but there are no
3276 // changes to input windows, notify immediately.
3277 windowInfosReported();
3278 }
3279 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3280 inputFlinger->setFocusedWindow(focusRequest);
3281 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003282 }});
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003283
Arthur Hung6cbb9752019-09-05 16:38:18 +08003284 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003285}
3286
Alec Mouricdf16792021-12-10 13:16:06 -08003287void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3288 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3289 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3290 if (!supportsDisplayBrightnessCommand) {
3291 return;
3292 }
3293
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003294 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003295 if (const auto brightness = display->getStagedBrightness(); brightness) {
3296 if (!needsComposite) {
3297 const status_t error =
3298 getHwComposer()
3299 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003300 display->getCompositionDisplay()
3301 ->getState()
3302 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003303 Hwc2::Composer::DisplayBrightnessOptions{
3304 .applyImmediately = true})
3305 .get();
3306
3307 ALOGE_IF(error != NO_ERROR,
3308 "Error setting display brightness for display %s: %d (%s)",
3309 display->getDebugName().c_str(), error, strerror(error));
3310 }
3311 display->persistBrightness(needsComposite);
3312 }
3313 }
3314}
3315
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003316void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3317 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003318 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3319
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003320 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003321 const auto layerStack = display->getLayerStack();
3322 const auto info = display->getInputInfo();
3323
3324 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003325 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003326 continue;
3327 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003328
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003329 // If the layer stack is mirrored on multiple displays, the first display that is configured
3330 // to receive input takes precedence.
3331 auto& otherInfo = it->second;
3332 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003333 ALOGW_IF(display->receivesInput(),
3334 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003335 layerStack.id);
3336 } else {
3337 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003338 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003339 }
Robert Carr720e5062018-07-30 17:45:14 -07003340
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003341 static size_t sNumWindowInfos = 0;
3342 outWindowInfos.reserve(sNumWindowInfos);
3343 sNumWindowInfos = 0;
3344
Robert Carr720e5062018-07-30 17:45:14 -07003345 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003346 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003347
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003348 // Do not create WindowInfos for windows on displays that cannot receive input.
3349 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3350 const auto& info = opt->get();
3351 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003352 }
Robert Carr720e5062018-07-30 17:45:14 -07003353 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003354
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003355 sNumWindowInfos = outWindowInfos.size();
3356
3357 outDisplayInfos.reserve(displayInputInfos.size());
3358 for (const auto& [_, info] : displayInputInfos) {
3359 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003360 }
Robert Carr720e5062018-07-30 17:45:14 -07003361}
3362
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003363void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003364 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003365 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003366 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003367 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003368 }
3369 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003370
3371 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003372}
3373
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003374void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003375 // If this is called from the main thread mStateLock must be locked before
3376 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003377 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003378
3379 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003380
3381 const auto display = getDefaultDisplayDeviceLocked();
3382 if (!display || mBootStage != BootStage::FINISHED) {
3383 return;
3384 }
3385 ATRACE_CALL();
3386
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003387 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3388 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003389 return;
3390 }
3391
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003392 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003393}
3394
Ady Abraham62a0be22020-12-08 16:54:10 -08003395void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3396 PhysicalDisplayId displayId = [&]() {
3397 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3398 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3399 }();
3400
3401 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3402}
3403
Ady Abraham3efa3942021-06-24 19:01:25 -07003404void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003405 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003406 // If the scheduler is already initialized, this means that we received
3407 // a hotplug(connected) on the primary display. In that case we should
3408 // update the scheduler with the most recent display information.
3409 ALOGW("Scheduler already initialized, updating instead");
3410 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003411 return;
3412 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003413 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003414 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3415 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003416
Marin Shalamanova903d032020-12-29 20:35:13 +01003417 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003418 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003419
Dominik Laskowski068173d2021-08-11 17:22:59 -07003420 using Feature = scheduler::Feature;
3421 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003422
Dominik Laskowski068173d2021-08-11 17:22:59 -07003423 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3424 features |= Feature::kContentDetection;
3425 }
3426 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3427 features |= Feature::kTracePredictedVsync;
3428 }
3429 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003430 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003431 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003432 }
3433
Dominik Laskowski068173d2021-08-11 17:22:59 -07003434 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3435 static_cast<ISchedulerCallback&>(*this),
3436 features);
3437 {
3438 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003439 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003440 features |= Feature::kKernelIdleTimer;
3441 }
3442
3443 mScheduler->createVsyncSchedule(features);
3444 mScheduler->setRefreshRateConfigs(std::move(configs));
3445 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003446 setVsyncEnabled(false);
3447 mScheduler->startTimers();
3448
Ady Abraham9c53ee72020-07-22 21:16:18 -07003449 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003450 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003451 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003452 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003453 /*workDuration=*/configs.late.appWorkDuration,
3454 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003455 impl::EventThread::InterceptVSyncsCallback());
3456 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003457 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3458 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3459 /*readyDuration=*/configs.late.sfWorkDuration,
3460 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003461 mInterceptor->saveVSyncEvent(timestamp);
3462 });
3463
Dominik Laskowski756b7892021-08-04 12:53:59 -07003464 mScheduler->initVsync(mScheduler->getVsyncDispatch(), *mFrameTimeline->getTokenManager(),
3465 configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003466
3467 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003468 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003469 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003470 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003471 // initialization, so that the EventThreads always contain a reference to a
3472 // prior configuration.
3473 //
3474 // This is a bit hacky, but this avoids a back-pointer into the main SF
3475 // classes from EventThread, and there should be no run-time binder cost
3476 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003477 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003478}
3479
Marin Shalamanov5801c942020-12-17 17:00:13 +01003480void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3481 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003482 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003483 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003484}
3485
Ady Abraham55fa7272020-09-30 19:19:27 -07003486void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3487 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003488 mScheduler->setDuration(mAppConnectionHandle,
3489 /*workDuration=*/config.appWorkDuration,
3490 /*readyDuration=*/config.sfWorkDuration);
3491 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003492 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3493 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003494 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003495}
3496
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003497void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003498 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003499
Lloyd Pique58e24a32019-08-01 15:50:14 -07003500 if (!mLayersPendingRemoval.isEmpty()) {
3501 // Notify removed layers now that they can't be drawn from
3502 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003503 // Ensure any buffers set to display on any children are released.
3504 if (l->isRemovedFromCurrentState()) {
3505 l->latchAndReleaseBuffer();
3506 }
3507
chaviw6852bff2022-04-19 17:35:11 -05003508 // If a layer has a parent, we allow it to out-live it's handle
3509 // with the idea that the parent holds a reference and will eventually
3510 // be cleaned up. However no one cleans up the top-level so we do so
3511 // here.
3512 if (l->isAtRoot()) {
3513 l->setIsAtRoot(false);
3514 mCurrentState.layersSortedByZ.remove(l);
3515 }
3516
Lloyd Pique58e24a32019-08-01 15:50:14 -07003517 // If the layer has been removed and has no parent, then it will not be reachable
3518 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3519 // ensure we can copy its current to drawing state.
3520 if (!l->getParent()) {
3521 mOffscreenLayers.emplace(l.get());
3522 }
3523 }
3524 mLayersPendingRemoval.clear();
3525 }
3526
3527 // If this transaction is part of a window animation then the next frame
3528 // we composite should be considered an animation as well.
3529 mAnimCompositionPending = mAnimTransactionPending;
3530
3531 mDrawingState = mCurrentState;
3532 // clear the "changed" flags in current state
3533 mCurrentState.colorMatrixChanged = false;
3534
Robert Carra70e91c2021-06-11 13:59:52 -07003535 if (mVisibleRegionsDirty) {
3536 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3537 rootLayer->commitChildList();
3538 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003539 }
Robert Carra70e91c2021-06-11 13:59:52 -07003540
Lloyd Pique58e24a32019-08-01 15:50:14 -07003541 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003542 if (mNumClones > 0) {
3543 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3544 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003545}
3546
chaviw74d90ad2019-04-26 14:45:26 -07003547void SurfaceFlinger::commitOffscreenLayers() {
3548 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003549 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003550 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3551 layer->doTransaction(0);
3552 layer->commitChildList();
3553 }
chaviw74d90ad2019-04-26 14:45:26 -07003554 });
3555 }
3556}
3557
Chia-I Wuab0c3192017-08-01 11:29:00 -07003558void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003559 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003560 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003561 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003562 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003563 }
3564 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003565}
3566
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003567bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003568 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003569
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003570 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003571
Mathias Agopian4fec8732012-06-29 14:12:52 -07003572 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003573 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003574 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003575
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003576 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3577
Eric Penner51c59cd2014-07-28 19:51:58 -07003578 // Store the set of layers that need updates. This set must not change as
3579 // buffers are being latched, as this could result in a deadlock.
3580 // Example: Two producers share the same command stream and:
3581 // 1.) Layer 0 is latched
3582 // 2.) Layer 0 gets a new frame
3583 // 2.) Layer 1 gets a new frame
3584 // 3.) Layer 1 is latched.
3585 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3586 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003587 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003588 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3589 const uint32_t flags = layer->doTransaction(0);
3590 if (flags & Layer::eVisibleRegion) {
3591 mVisibleRegionsDirty = true;
3592 }
3593 }
Robert Carrb552ff52021-06-11 13:35:54 -07003594
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003595 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003596 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003597 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003598 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003599 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003600 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003601 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003602 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003603 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003604 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003605 }
Robert Carr2047fae2016-11-28 14:09:09 -08003606 });
Robert Carrb552ff52021-06-11 13:35:54 -07003607 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003608
chaviw49a108c2019-08-12 11:23:06 -07003609 // The client can continue submitting buffers for offscreen layers, but they will not
3610 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3611 // layers to ensure dequeueBuffer doesn't block indefinitely.
3612 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003613 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003614 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3615 }
3616
Lloyd Piquef2c79392018-12-20 16:23:33 -08003617 if (!mLayersWithQueuedFrames.empty()) {
3618 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3619 // writes to Layer current state. See also b/119481871
3620 Mutex::Autolock lock(mStateLock);
3621
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003622 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003623 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003624 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003625 newDataLatched = true;
3626 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003627 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003628 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003629 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003630
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003631 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003632
3633 // If we will need to wake up at some time in the future to deal with a
3634 // queued frame that shouldn't be displayed during this vsync period, wake
3635 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003636 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003637 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003638 }
3639
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003640 // enter boot animation on first buffer latch
3641 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3642 ALOGI("Enter boot animation");
3643 mBootStage = BootStage::BOOTANIMATION;
3644 }
3645
Robert Carr6a0382d2021-07-01 15:57:17 -07003646 if (mNumClones > 0) {
3647 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3648 }
chaviw74b03172019-08-19 11:09:03 -07003649
Dan Stoza6b9454d2014-11-07 16:00:59 -08003650 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003651 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003652}
3653
Robert Carrc0df3122019-04-11 13:18:21 -07003654status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003655 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003656 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003657 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003658 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003659 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003660 static_cast<void>(mScheduler->schedule([=] {
3661 ALOGE("Dumping random sampling of on-screen layers: ");
3662 mDrawingState.traverse([&](Layer *layer) {
3663 // Aim to dump about 200 layers to avoid totally trashing
3664 // logcat. On the other hand, if there really are 4096 layers
3665 // something has gone totally wrong its probably the most
3666 // useful information in logcat.
3667 if (rand() % 20 == 13) {
3668 ALOGE("Layer: %s", layer->getName().c_str());
3669 }
3670 });
3671 for (Layer* offscreenLayer : mOffscreenLayers) {
3672 if (rand() % 20 == 13) {
3673 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3674 }
3675 }
3676 }));
arthurhungdba591c2021-02-08 17:28:49 +08003677 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003678 }
3679
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003680 {
3681 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3682 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3683 }
arthurhungdba591c2021-02-08 17:28:49 +08003684
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003685 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003686 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003687 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003688 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003689 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003690 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003691 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003692 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003693
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003694 setTransactionFlags(eTransactionNeeded);
3695 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003696}
3697
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003698uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003699 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003700}
3701
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003702uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3703 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003704}
3705
Dominik Laskowski94000c42022-03-17 12:55:14 -07003706void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003707 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003708 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003709
3710 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003711 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003713}
3714
Ady Abraham9dada822022-02-03 10:26:59 -08003715bool SurfaceFlinger::stopTransactionProcessing(
3716 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3717 applyTokensWithUnsignaledTransactions) const {
3718 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3719 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3720 // then we should have only one applyToken for processing.
3721 // so we can stop further transactions on this applyToken.
3722 return !applyTokensWithUnsignaledTransactions.empty();
3723 }
3724
3725 return false;
3726}
3727
ramindani9eff2492022-03-23 00:28:26 +00003728int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3729 std::vector<TransactionState>& transactions,
3730 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3731 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3732 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3733 applyTokensWithUnsignaledTransactions,
3734 /*tryApplyUnsignaled*/ true);
3735}
3736
Robert Carr79dc06a2022-02-22 15:28:59 -08003737int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003738 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003739 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003740 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3741 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003742 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003743 auto it = mPendingTransactionQueues.begin();
3744 while (it != mPendingTransactionQueues.end()) {
3745 auto& [applyToken, transactionQueue] = *it;
3746 while (!transactionQueue.empty()) {
3747 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3748 ATRACE_NAME("stopTransactionProcessing");
3749 break;
3750 }
3751
3752 auto& transaction = transactionQueue.front();
3753 const auto ready =
Robert Carr4c1b6462021-12-21 10:30:50 -08003754 transactionIsReadyToBeApplied(transaction,
3755 transaction.frameTimelineInfo,
3756 transaction.isAutoTimestamp,
3757 transaction.desiredPresentTime,
3758 transaction.originUid, transaction.states,
3759 bufferLayersReadyToPresent, transactions.size(),
3760 tryApplyUnsignaled);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003761 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3762 if (ready == TransactionReadiness::NotReady) {
3763 setTransactionFlags(eTransactionFlushNeeded);
3764 break;
3765 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003766 if (ready == TransactionReadiness::NotReadyBarrier) {
3767 transactionsPendingBarrier++;
3768 setTransactionFlags(eTransactionFlushNeeded);
3769 break;
3770 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003771 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003772 const bool frameNumberChanged = state.bufferData->flags.test(
3773 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003774 if (frameNumberChanged) {
3775 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3776 } else {
3777 // Barrier function only used for BBQ which always includes a frame number
3778 bufferLayersReadyToPresent[state.surface] =
3779 std::numeric_limits<uint64_t>::max();
3780 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003781 });
3782 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3783 if (appliedUnsignaled) {
3784 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3785 }
3786
3787 transactions.emplace_back(std::move(transaction));
3788 transactionQueue.pop();
3789 }
3790
3791 if (transactionQueue.empty()) {
3792 it = mPendingTransactionQueues.erase(it);
3793 mTransactionQueueCV.broadcast();
3794 } else {
3795 it = std::next(it, 1);
3796 }
3797 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003798 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003799}
3800
Vishnu Nair7891e962021-11-11 12:07:21 -08003801bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003802 // to prevent onHandleDestroyed from being called while the lock is held,
3803 // we must keep a copy of the transactions (specifically the composer
3804 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003805 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003806 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003807 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003808 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003809 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003810 Mutex::Autolock _l(mStateLock);
3811 {
3812 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003813
Robert Carr79dc06a2022-02-22 15:28:59 -08003814 int lastTransactionsPendingBarrier = 0;
3815 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003816 // First collect transactions from the pending transaction queues.
3817 // We are not allowing unsignaled buffers here as we want to
3818 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003819 transactionsPendingBarrier =
3820 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3821 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003822
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003823 // Second, collect transactions from the transaction queue.
3824 // Here as well we are not allowing unsignaled buffers for the same
3825 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003826 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003827 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003828 const bool pendingTransactions =
3829 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003830 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003831 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003832 if (pendingTransactions) {
3833 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003834 return TransactionReadiness::NotReady;
3835 }
3836
Robert Carr4c1b6462021-12-21 10:30:50 -08003837 return transactionIsReadyToBeApplied(transaction, transaction.frameTimelineInfo,
Ady Abraham9dada822022-02-03 10:26:59 -08003838 transaction.isAutoTimestamp,
3839 transaction.desiredPresentTime,
3840 transaction.originUid, transaction.states,
3841 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003842 transactions.size(),
3843 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003844 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003845 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003846 if (ready != TransactionReadiness::Ready) {
3847 if (ready == TransactionReadiness::NotReadyBarrier) {
3848 transactionsPendingBarrier++;
3849 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003850 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003851 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003852 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003853 const bool frameNumberChanged = state.bufferData->flags.test(
3854 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003855 if (frameNumberChanged) {
3856 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3857 } else {
3858 // Barrier function only used for BBQ which always includes a frame number.
3859 // This value only used for barrier logic.
3860 bufferLayersReadyToPresent[state.surface] =
3861 std::numeric_limits<uint64_t>::max();
3862 }
Xiang Wang76236e12022-03-22 17:25:30 +00003863 });
Ady Abraham9dada822022-02-03 10:26:59 -08003864 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003865 }
ramindani4d48f902021-09-20 21:07:45 +00003866 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003867 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003868 }
Arthur Hung58144272021-01-16 03:43:53 +00003869
Robert Carr79dc06a2022-02-22 15:28:59 -08003870 // Transactions with a buffer pending on a barrier may be on a different applyToken
3871 // than the transaction which satisfies our barrier. In fact this is the exact use case
3872 // that the primitive is designed for. This means we may first process
3873 // the barrier dependent transaction, determine it ineligible to complete
3874 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3875 // The barrier dependent transaction was eligible to be presented in this frame
3876 // but we would have prevented it without case. To fix this we continually
3877 // loop through flushPendingTransactionQueues until we perform an iteration
3878 // where the number of transactionsPendingBarrier doesn't change. This way
3879 // we can continue to resolve dependency chains of barriers as far as possible.
3880 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3881 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3882 transactionsPendingBarrier =
3883 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3884 applyTokensWithUnsignaledTransactions,
3885 /*tryApplyUnsignaled*/ false);
3886 }
3887
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003888 // We collected all transactions that could apply without latching unsignaled buffers.
3889 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3890 // transactions that were not applied and try to apply them unsignaled.
3891 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003892 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3893 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003894 }
3895
Vishnu Nair7891e962021-11-11 12:07:21 -08003896 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003897 }
ramindani4d48f902021-09-20 21:07:45 +00003898 }
3899}
3900
Vishnu Nair7891e962021-11-11 12:07:21 -08003901bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3902 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003903 bool needsTraversal = false;
3904 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003905 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003906 needsTraversal |=
3907 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3908 transaction.displays, transaction.flags,
3909 transaction.inputWindowCommands,
3910 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3911 transaction.buffer, transaction.postTime,
3912 transaction.permissions, transaction.hasListenerCallbacks,
3913 transaction.listenerCallbacks, transaction.originPid,
3914 transaction.originUid, transaction.id);
3915 if (transaction.transactionCommittedSignal) {
3916 mTransactionCommittedSignals.emplace_back(
3917 std::move(transaction.transactionCommittedSignal));
3918 }
3919 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003920
Dominik Laskowski46471e62022-01-14 15:34:03 -08003921 if (mTransactionTracing) {
3922 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003923 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003924 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003925}
3926
3927bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003928 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003929 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003930}
3931
Ady Abraham8db10102021-03-15 17:19:23 -07003932bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3933 // The amount of time SF can delay a frame if it is considered early based
3934 // on the VsyncModulator::VsyncConfig::appWorkDuration
3935 constexpr static std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3936
3937 const auto currentVsyncPeriod = mScheduler->getDisplayStatInfo(systemTime()).vsyncPeriod;
3938 const auto earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
3939
3940 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3941 if (!prediction.has_value()) {
3942 return false;
3943 }
3944
3945 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3946 kEarlyLatchMaxThreshold.count()) {
3947 return false;
3948 }
3949
3950 return prediction->presentTime >= expectedPresentTime &&
3951 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3952}
Ady Abraham9dada822022-02-03 10:26:59 -08003953bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003954 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003955 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3956 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3957 return false;
3958 }
Ady Abraham8db10102021-03-15 17:19:23 -07003959
Ady Abraham9dada822022-02-03 10:26:59 -08003960 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3961 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3962 return true;
3963 }
3964
3965 // We only want to latch unsignaled when a single layer is updated in this
3966 // transaction (i.e. not a blast sync transaction).
3967 if (numStates != 1) {
3968 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3969 return false;
3970 }
3971
Ady Abraham2739e832022-02-14 17:42:00 -08003972 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3973 if (totalTXapplied > 0) {
3974 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3975 __func__, totalTXapplied);
3976 return false;
3977 }
3978
3979 // We don't want to latch unsignaled if are in early / client composition
3980 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3981 // or window animations being slow.
3982 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3983 if (!isDefaultVsyncConfig) {
3984 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3985 __func__);
3986 return false;
3987 }
Ady Abraham9dada822022-02-03 10:26:59 -08003988 }
3989
3990 if (!layer->simpleBufferUpdate(state)) {
3991 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3992 return false;
3993 }
3994
3995 ALOGV("%s: true", __func__);
3996 return true;
3997}
3998
Robert Carr4c1b6462021-12-21 10:30:50 -08003999auto SurfaceFlinger::transactionIsReadyToBeApplied(TransactionState& transaction,
Ady Abraham43752eb2021-03-04 16:24:25 -08004000 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08004001 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08004002 const std::unordered_map<
4003 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004004 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00004005 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07004006 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08004007 // Do not present if the desiredPresentTime has not passed unless it is more than one second
4008 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08004009 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08004010 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004011 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08004012 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08004013 }
4014
Ady Abraham5690bda2021-03-12 15:01:18 -08004015 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
4016 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08004017 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08004018 }
4019
Ady Abraham8db10102021-03-15 17:19:23 -07004020 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
4021 // present time of this transaction.
4022 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
4023 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08004024 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07004025 }
4026
Ady Abraham9dada822022-02-03 10:26:59 -08004027 bool fenceUnsignaled = false;
Robert Carr4c1b6462021-12-21 10:30:50 -08004028 auto queueProcessTime = systemTime();
Marissa Wall713b63f2018-10-17 15:42:43 -07004029 for (const ComposerState& state : states) {
4030 const layer_state_t& s = state.state;
Robert Carr4c1b6462021-12-21 10:30:50 -08004031
Ady Abrahamf20c1922020-12-21 18:39:01 -08004032 sp<Layer> layer = nullptr;
4033 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07004034 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004035 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08004036 ALOGW("Transaction with buffer, but no Layer?");
4037 continue;
4038 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08004039 if (!layer) {
4040 continue;
4041 }
Ady Abraham43752eb2021-03-04 16:24:25 -08004042
Robert Carr79dc06a2022-02-22 15:28:59 -08004043 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
4044 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
4045 const bool willApplyBarrierFrame =
4046 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
4047 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
4048 if (!willApplyBarrierFrame) {
4049 ATRACE_NAME("NotReadyBarrier");
4050 return TransactionReadiness::NotReadyBarrier;
4051 }
4052 }
4053
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004054 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08004055 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08004056 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
4057 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08004058
4059 const bool acquireFenceChanged = s.bufferData &&
4060 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
4061 s.bufferData->acquireFence;
4062 fenceUnsignaled = fenceUnsignaled ||
4063 (acquireFenceChanged &&
4064 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
4065
4066 if (fenceUnsignaled && !allowLatchUnsignaled) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004067 if (!transaction.sentFenceTimeoutWarning &&
4068 queueProcessTime - transaction.queueTime > std::chrono::nanoseconds(4s).count()) {
4069 transaction.sentFenceTimeoutWarning = true;
4070 auto listener = s.bufferData->releaseBufferListener;
4071 if (listener) {
4072 listener->onTransactionQueueStalled();
4073 }
4074 }
4075
Ady Abraham9dada822022-02-03 10:26:59 -08004076 ATRACE_NAME("fence unsignaled");
4077 return TransactionReadiness::NotReady;
4078 }
4079
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004080 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08004081 // If backpressure is enabled and we already have a buffer to commit, keep the
4082 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004083 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4084 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004085 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004086 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004087 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004088 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004089 }
4090 }
Ady Abraham9dada822022-02-03 10:26:59 -08004091 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004092}
4093
arthurhungf1b7c7b2021-03-03 17:42:23 +08004094void SurfaceFlinger::queueTransaction(TransactionState& state) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004095 state.queueTime = systemTime();
4096
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004097 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004098
arthurhungf1b7c7b2021-03-03 17:42:23 +08004099 // Generate a CountDownLatch pending state if this is a synchronous transaction.
4100 if ((state.flags & eSynchronous) || state.inputWindowCommands.syncInputWindows) {
4101 state.transactionCommittedSignal = std::make_shared<CountDownLatch>(
Arthur Hung2274a312021-04-28 15:13:06 +00004102 (state.inputWindowCommands.syncInputWindows
4103 ? (CountDownLatch::eSyncInputWindows | CountDownLatch::eSyncTransaction)
4104 : CountDownLatch::eSyncTransaction));
arthurhungf1b7c7b2021-03-03 17:42:23 +08004105 }
4106
ramindani4d48f902021-09-20 21:07:45 +00004107 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004108 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4109
Ady Abrahame46243a2021-02-23 19:33:49 -08004110 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004111 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4112 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004113 return TransactionSchedule::Late;
4114 }(state.flags);
4115
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004116 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4117
4118 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004119}
4120
arthurhungf1b7c7b2021-03-03 17:42:23 +08004121void SurfaceFlinger::waitForSynchronousTransaction(
4122 const CountDownLatch& transactionCommittedSignal) {
4123 // applyTransactionState is called on the main SF thread. While a given process may wish
4124 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4125 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004126 if (!transactionCommittedSignal.wait_until(
4127 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004128 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004129 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004130}
Ady Abrahame46243a2021-02-23 19:33:49 -08004131
Arthur Hung2274a312021-04-28 15:13:06 +00004132void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004133 for (auto it = mTransactionCommittedSignals.begin();
4134 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004135 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004136 it = mTransactionCommittedSignals.erase(it);
4137 } else {
4138 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004139 }
4140 }
4141}
4142
chaviw308ddba2020-08-11 16:23:51 -07004143status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004144 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004145 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4146 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004147 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004148 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004149 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004150
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004151 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004152 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4153 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004154 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4155 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004156 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004157 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004158 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004159 }
4160
Leon Scroggins9a20f722021-12-28 14:43:12 +00004161 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004162 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004163 }
4164
Robert Carrde6d7b42022-01-07 18:23:06 -08004165 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004166 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4167 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4168 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004169 }
4170
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004171 const int64_t postTime = systemTime();
4172
4173 IPCThreadState* ipc = IPCThreadState::self();
4174 const int originPid = ipc->getCallingPid();
4175 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004176 TransactionState state{frameTimelineInfo, states,
4177 displays, flags,
4178 applyToken, inputWindowCommands,
4179 desiredPresentTime, isAutoTimestamp,
4180 uncacheBuffer, postTime,
4181 permissions, hasListenerCallbacks,
4182 listenerCallbacks, originPid,
4183 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004184
4185 // Check for incoming buffer updates and increment the pending buffer count.
4186 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4187 mBufferCountTracker.increment(state.surface->localBinder());
4188 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004189
Dominik Laskowski46471e62022-01-14 15:34:03 -08004190 if (mTransactionTracing) {
4191 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004192 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004193 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004194
arthurhungf1b7c7b2021-03-03 17:42:23 +08004195 // Check the pending state to make sure the transaction is synchronous.
4196 if (state.transactionCommittedSignal) {
4197 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004198 }
4199
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004200 return NO_ERROR;
4201}
Marissa Wall713b63f2018-10-17 15:42:43 -07004202
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004203bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004204 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004205 const Vector<DisplayState>& displays, uint32_t flags,
4206 const InputWindowCommands& inputWindowCommands,
4207 const int64_t desiredPresentTime, bool isAutoTimestamp,
4208 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004209 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004210 bool hasListenerCallbacks,
4211 const std::vector<ListenerCallbacks>& listenerCallbacks,
4212 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004213 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004214 for (const DisplayState& display : displays) {
4215 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004216 }
4217
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004218 // start and end registration for listeners w/ no surface so they can get their callback. Note
4219 // that listeners with SurfaceControls will start registration during setClientStateLocked
4220 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004221 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004222 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004223 }
4224
Marissa Walle2ffb422018-10-12 11:33:52 -07004225 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004226 for (int i = 0; i < states.size(); i++) {
4227 ComposerState& state = states.editItemAt(i);
4228 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004229 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004230 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004231 if (const auto layer = fromHandle(state.state.surface).promote()) {
4232 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004233 mScheduler->recordLayerHistory(layer.get(),
4234 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004235 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004236 }
4237 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004238 }
4239
Marissa Walle2ffb422018-10-12 11:33:52 -07004240 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004241
Robert Carrde6d7b42022-01-07 18:23:06 -08004242 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004243 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4244 } else if (!inputWindowCommands.empty()) {
4245 ALOGE("Only privileged callers are allowed to send input commands.");
4246 }
chaviw273171b2018-12-26 11:46:30 -08004247
Marissa Wall947d34e2019-03-29 14:03:53 -07004248 if (uncacheBuffer.isValid()) {
4249 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004250 }
4251
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004252 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4253 // anyway. This can be used as a flush mechanism for previous async transactions.
4254 // Empty animation transaction can be used to simulate back-pressure, so also force a
4255 // transaction for empty animation transactions.
4256 if (transactionFlags == 0 &&
4257 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004258 transactionFlags = eTransactionNeeded;
4259 }
4260
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004261 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004262 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004263 if (mInterceptor->isEnabled()) {
4264 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004265 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004266 }
4267
Arthur Hung58144272021-01-16 03:43:53 +00004268 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4269 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4270 if (transactionFlags & eTraversalNeeded) {
4271 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004272 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004273 }
Arthur Hung58144272021-01-16 03:43:53 +00004274 if (transactionFlags) {
4275 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004276 }
4277
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004278 if (flags & eAnimation) {
4279 mAnimTransactionPending = true;
4280 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004281 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004282
4283 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004284}
4285
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004286uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4287 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4288 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004289
Mathias Agopiane57f2922012-08-09 16:29:12 -07004290 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004291 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4292
4293 const uint32_t what = s.what;
4294 if (what & DisplayState::eSurfaceChanged) {
4295 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4296 state.surface = s.surface;
4297 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004298 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004299 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004300 if (what & DisplayState::eLayerStackChanged) {
4301 if (state.layerStack != s.layerStack) {
4302 state.layerStack = s.layerStack;
4303 flags |= eDisplayTransactionNeeded;
4304 }
4305 }
Evan Rosky2239b372021-05-20 13:43:47 -07004306 if (what & DisplayState::eFlagsChanged) {
4307 if (state.flags != s.flags) {
4308 state.flags = s.flags;
4309 flags |= eDisplayTransactionNeeded;
4310 }
4311 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004312 if (what & DisplayState::eDisplayProjectionChanged) {
4313 if (state.orientation != s.orientation) {
4314 state.orientation = s.orientation;
4315 flags |= eDisplayTransactionNeeded;
4316 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004317 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4318 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004319 flags |= eDisplayTransactionNeeded;
4320 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004321 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4322 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004323 flags |= eDisplayTransactionNeeded;
4324 }
4325 }
4326 if (what & DisplayState::eDisplaySizeChanged) {
4327 if (state.width != s.width) {
4328 state.width = s.width;
4329 flags |= eDisplayTransactionNeeded;
4330 }
4331 if (state.height != s.height) {
4332 state.height = s.height;
4333 flags |= eDisplayTransactionNeeded;
4334 }
4335 }
4336
Mathias Agopiane57f2922012-08-09 16:29:12 -07004337 return flags;
4338}
4339
Steven Thomasd4071902020-03-24 16:02:53 -07004340bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004341 IPCThreadState* ipc = IPCThreadState::self();
4342 const int pid = ipc->getCallingPid();
4343 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004344 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004345 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4346 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004347 return false;
4348 }
4349 return true;
4350}
4351
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004352uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004353 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004354 int64_t desiredPresentTime, bool isAutoTimestamp,
4355 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004356 layer_state_t& s = composerState.state;
4357 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004358
4359 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004360 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004361 // Starts a registration but separates the callback ids according to callback type. This
4362 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004363 // note that startRegistration will not re-register if the listener has
4364 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004365
4366 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4367 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004368 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004369 }
4370
4371 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4372 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004373 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004374 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004375 }
4376
arthurhungdba591c2021-02-08 17:28:49 +08004377 const uint64_t what = s.what;
4378 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004379 sp<Layer> layer = nullptr;
4380 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004381 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004382 } else {
4383 // The client may provide us a null handle. Treat it as if the layer was removed.
4384 ALOGW("Attempt to set client state with a null layer handle");
4385 }
chaviw8b3871a2017-11-01 17:41:01 -07004386 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004387 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004388 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004389 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004390 }
chaviw8b3871a2017-11-01 17:41:01 -07004391 return 0;
4392 }
4393
Valerie Hau871d6352020-01-29 08:44:02 -08004394 // Only set by BLAST adapter layers
4395 if (what & layer_state_t::eProducerDisconnect) {
4396 layer->onDisconnect();
4397 }
4398
chaviw8b3871a2017-11-01 17:41:01 -07004399 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004400 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004401 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004402 }
chaviw8b3871a2017-11-01 17:41:01 -07004403 }
4404 if (what & layer_state_t::eLayerChanged) {
4405 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004406 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004407 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004408 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004409 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004410 mCurrentState.layersSortedByZ.removeAt(idx);
4411 mCurrentState.layersSortedByZ.add(layer);
4412 // we need traversal (state changed)
4413 // AND transaction (list changed)
4414 flags |= eTransactionNeeded|eTraversalNeeded;
4415 }
chaviw8b3871a2017-11-01 17:41:01 -07004416 } else {
4417 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004418 flags |= eTransactionNeeded|eTraversalNeeded;
4419 }
4420 }
chaviw8b3871a2017-11-01 17:41:01 -07004421 }
4422 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004423 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004424 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004425 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4426 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004427 if (p == nullptr) {
4428 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004429 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004430 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004431 mCurrentState.layersSortedByZ.removeAt(idx);
4432 mCurrentState.layersSortedByZ.add(layer);
4433 // we need traversal (state changed)
4434 // AND transaction (list changed)
4435 flags |= eTransactionNeeded|eTraversalNeeded;
4436 }
4437 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004438 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004439 flags |= eTransactionNeeded|eTraversalNeeded;
4440 }
chaviw8b3871a2017-11-01 17:41:01 -07004441 }
4442 }
4443 if (what & layer_state_t::eSizeChanged) {
4444 if (layer->setSize(s.w, s.h)) {
4445 flags |= eTraversalNeeded;
4446 }
4447 }
4448 if (what & layer_state_t::eAlphaChanged) {
4449 if (layer->setAlpha(s.alpha))
4450 flags |= eTraversalNeeded;
4451 }
4452 if (what & layer_state_t::eColorChanged) {
4453 if (layer->setColor(s.color))
4454 flags |= eTraversalNeeded;
4455 }
Peiyong Lind3788632018-09-18 16:01:31 -07004456 if (what & layer_state_t::eColorTransformChanged) {
4457 if (layer->setColorTransform(s.colorTransform)) {
4458 flags |= eTraversalNeeded;
4459 }
4460 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004461 if (what & layer_state_t::eBackgroundColorChanged) {
4462 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4463 flags |= eTraversalNeeded;
4464 }
4465 }
chaviw8b3871a2017-11-01 17:41:01 -07004466 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004467 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004468 }
4469 if (what & layer_state_t::eTransparentRegionChanged) {
4470 if (layer->setTransparentRegionHint(s.transparentRegion))
4471 flags |= eTraversalNeeded;
4472 }
4473 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004474 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004475 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004476 if (what & layer_state_t::eCornerRadiusChanged) {
4477 if (layer->setCornerRadius(s.cornerRadius))
4478 flags |= eTraversalNeeded;
4479 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004480 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004481 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4482 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004483 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004484 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4485 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004486 if (what & layer_state_t::eRenderBorderChanged) {
Tianhao Yao10cea3c2022-03-30 01:37:22 +00004487 if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00004488 flags |= eTraversalNeeded;
4489 }
4490 }
chaviw8b3871a2017-11-01 17:41:01 -07004491 if (what & layer_state_t::eLayerStackChanged) {
4492 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4493 // We only allow setting layer stacks for top level layers,
4494 // everything else inherits layer stack from its parent.
4495 if (layer->hasParent()) {
4496 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004497 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004498 } else if (idx < 0) {
4499 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004500 "that also does not appear in the top level layer list. Something"
4501 " has gone wrong.",
4502 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004503 } else if (layer->setLayerStack(s.layerStack)) {
4504 mCurrentState.layersSortedByZ.removeAt(idx);
4505 mCurrentState.layersSortedByZ.add(layer);
4506 // we need traversal (state changed)
4507 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004508 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004509 }
4510 }
Marissa Wall61c58622018-07-18 10:12:20 -07004511 if (what & layer_state_t::eTransformChanged) {
4512 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4513 }
4514 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4515 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4516 flags |= eTraversalNeeded;
4517 }
4518 if (what & layer_state_t::eCropChanged) {
4519 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4520 }
Marissa Wall61c58622018-07-18 10:12:20 -07004521 if (what & layer_state_t::eDataspaceChanged) {
4522 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4523 }
4524 if (what & layer_state_t::eHdrMetadataChanged) {
4525 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4526 }
4527 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4528 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4529 }
4530 if (what & layer_state_t::eApiChanged) {
4531 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4532 }
4533 if (what & layer_state_t::eSidebandStreamChanged) {
4534 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4535 }
Robert Carr720e5062018-07-30 17:45:14 -07004536 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004537 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4538 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004539 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004540 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004541 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004542 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004543
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004544 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4545 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004546 // The transaction will be received on the Task layer and needs to be applied to all
4547 // child layers. Child layers that are added at a later point will obtain the game mode
4548 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004549 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004550 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004551
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004552 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4553 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004554 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4555 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4556 flags |= eTraversalNeeded;
4557 }
4558 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004559 if (what & layer_state_t::eShadowRadiusChanged) {
4560 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4561 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004562 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004563 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004564 flags |= eTraversalNeeded;
4565 }
4566 }
Steven Thomas3172e202020-01-06 19:25:30 -08004567 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004568 const auto compatibility =
4569 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4570 const auto strategy =
4571 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004572
Robert Carrde6d7b42022-01-07 18:23:06 -08004573 if (layer->setFrameRate(
4574 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4575 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004576 }
Steven Thomas3172e202020-01-06 19:25:30 -08004577 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004578 if (what & layer_state_t::eFixedTransformHintChanged) {
4579 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4580 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4581 }
4582 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004583 if (what & layer_state_t::eAutoRefreshChanged) {
4584 layer->setAutoRefresh(s.autoRefresh);
4585 }
Sally Qi421ffb02022-03-21 19:41:33 -07004586 if (what & layer_state_t::eDimmingEnabledChanged) {
4587 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4588 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004589 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004590 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4591 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004592 }
4593 }
John Reckcdb4ed72021-02-04 13:39:33 -05004594 if (what & layer_state_t::eStretchChanged) {
4595 if (layer->setStretchEffect(s.stretchEffect)) {
4596 flags |= eTraversalNeeded;
4597 }
4598 }
chaviwf3f40fe2021-04-27 15:54:02 -05004599 if (what & layer_state_t::eBufferCropChanged) {
4600 if (layer->setBufferCrop(s.bufferCrop)) {
4601 flags |= eTraversalNeeded;
4602 }
4603 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004604 if (what & layer_state_t::eDestinationFrameChanged) {
4605 if (layer->setDestinationFrame(s.destinationFrame)) {
4606 flags |= eTraversalNeeded;
4607 }
4608 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004609 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004610 if (layer->setDropInputMode(s.dropInputMode)) {
4611 flags |= eTraversalNeeded;
4612 mInputInfoChanged = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004613 }
4614 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004615 // This has to happen after we reparent children because when we reparent to null we remove
4616 // child layers from current state and remove its relative z. If the children are reparented in
4617 // the same transaction, then we have to make sure we reparent the children first so we do not
4618 // lose its relative z order.
4619 if (what & layer_state_t::eReparent) {
4620 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004621 auto parentHandle = (s.parentSurfaceControlForChild)
4622 ? s.parentSurfaceControlForChild->getHandle()
4623 : nullptr;
4624 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004625 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004626 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004627 mCurrentState.layersSortedByZ.remove(layer);
4628 }
4629 flags |= eTransactionNeeded | eTraversalNeeded;
4630 }
4631 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004632 std::vector<sp<CallbackHandle>> callbackHandles;
4633 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4634 for (auto& [listener, callbackIds] : filteredListeners) {
4635 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4636 }
4637 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004638
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004639 if (what & layer_state_t::eBufferChanged) {
4640 std::shared_ptr<renderengine::ExternalTexture> buffer =
4641 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4642 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4643 dequeueBufferTimestamp, frameTimelineInfo)) {
4644 flags |= eTraversalNeeded;
4645 }
Ady Abraham8db10102021-03-15 17:19:23 -07004646 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4647 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004648 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004649
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004650 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004651 // Do not put anything that updates layer state or modifies flags after
4652 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004653 return flags;
4654}
4655
chaviw273171b2018-12-26 11:46:30 -08004656uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004657 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004658 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004659}
4660
Vishnu Nair84125ac2021-12-02 08:47:48 -08004661status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4662 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4663 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004664 if (!mirrorFromHandle) {
4665 return NAME_NOT_FOUND;
4666 }
4667
4668 sp<Layer> mirrorLayer;
4669 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004670 {
4671 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004672 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004673 if (!mirrorFrom) {
4674 return NAME_NOT_FOUND;
4675 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004676 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004677 if (result != NO_ERROR) {
4678 return result;
4679 }
4680
Robert Carr6a0382d2021-07-01 15:57:17 -07004681 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004682 }
4683
Ady Abraham9f0a4002020-10-05 15:47:26 -07004684 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004685 if (mTransactionTracing) {
4686 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4687 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004688 }
4689 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004690 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004691}
4692
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004693status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004694 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4695 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004696 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4697 "Expected only one of parentLayer or parentHandle to be non-null. "
4698 "Programmer error?");
4699
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004700 status_t result = NO_ERROR;
4701
4702 sp<Layer> layer;
4703
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004704 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004705 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004706 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004707 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004708 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4709 if (pendingBufferCounter) {
4710 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004711 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004712 pendingBufferCounter);
4713 }
4714 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004715 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004716 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004717 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004718 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004719 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004720 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004721 default:
4722 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004723 break;
4724 }
4725
Dan Stoza7d89d062015-04-30 13:29:25 -07004726 if (result != NO_ERROR) {
4727 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004728 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004729
Vishnu Nair858a3b42022-01-12 20:42:28 -08004730 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004731 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4732 if (parentHandle != nullptr && parent == nullptr) {
4733 ALOGE("Invalid parent handle %p.", parentHandle.get());
4734 addToRoot = false;
4735 }
4736 if (parentLayer != nullptr) {
4737 addToRoot = false;
4738 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004739
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004740 int parentId = -1;
4741 // We can safely promote the layer in binder thread because we have a strong reference
4742 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4743 sp<Layer> parentSp = parent.promote();
4744 if (parentSp != nullptr) {
4745 parentId = parentSp->getSequence();
4746 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004747 if (mTransactionTracing) {
4748 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4749 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004750 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004751
Vishnu Nair047fb332021-12-09 09:54:36 -08004752 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4753 if (result != NO_ERROR) {
4754 return result;
4755 }
4756
Ady Abraham9f0a4002020-10-05 15:47:26 -07004757 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004758 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004759}
4760
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004761status_t SurfaceFlinger::createBufferQueueLayer(LayerCreationArgs& args, PixelFormat& format,
Evan Roskya1f1e152019-01-24 16:17:46 -08004762 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004763 sp<IGraphicBufferProducer>* gbp,
4764 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004765 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004766 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004767 case PIXEL_FORMAT_TRANSPARENT:
4768 case PIXEL_FORMAT_TRANSLUCENT:
4769 format = PIXEL_FORMAT_RGBA_8888;
4770 break;
4771 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004772 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004773 break;
4774 }
4775
chaviwb4c6e582019-08-16 14:35:07 -07004776 sp<BufferQueueLayer> layer;
chaviwb4c6e582019-08-16 14:35:07 -07004777 args.textureName = getNewTexture();
4778 {
4779 // Grab the SF state lock during this since it's the only safe way to access
4780 // RenderEngine when creating a BufferLayerConsumer
4781 // TODO: Check if this lock is still needed here
4782 Mutex::Autolock lock(mStateLock);
4783 layer = getFactory().createBufferQueueLayer(args);
4784 }
4785
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004786 status_t err = layer->setDefaultBufferProperties(0, 0, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004787 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004788 *handle = layer->getHandle();
4789 *gbp = layer->getProducer();
4790 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004791 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004792
Marissa Wallfd668622018-05-10 10:21:13 -07004793 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004794 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004795}
4796
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004797status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004798 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004799 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004800 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004801 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004802 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004803}
4804
Vishnu Nair84125ac2021-12-02 08:47:48 -08004805status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004806 sp<Layer>* outLayer) {
4807 *outLayer = getFactory().createEffectLayer(args);
4808 *handle = (*outLayer)->getHandle();
4809 return NO_ERROR;
4810}
4811
Vishnu Nair84125ac2021-12-02 08:47:48 -08004812status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004813 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004814 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004815 *handle = (*outLayer)->getHandle();
4816 return NO_ERROR;
4817}
4818
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004819void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004820 mLayersPendingRemoval.add(layer);
4821 mLayersRemoved = true;
4822 setTransactionFlags(eTransactionNeeded);
4823}
4824
Vishnu Nairf9096652021-07-20 18:49:42 -07004825void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004826 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004827 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004828 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004829 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004830 if (mTransactionTracing) {
4831 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004832 }
Rob Carr4bba3702018-10-08 21:53:30 +00004833}
4834
Mathias Agopianb60314a2012-04-10 22:09:54 -07004835// ---------------------------------------------------------------------------
4836
Andy McFadden13a082e2012-08-24 10:16:42 -07004837void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004838 const auto display = getDefaultDisplayDeviceLocked();
4839 if (!display) return;
4840
4841 const sp<IBinder> token = display->getDisplayToken().promote();
4842 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004843
Jesse Hall01e29052013-02-19 16:13:35 -08004844 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004845 Vector<ComposerState> state;
4846 Vector<DisplayState> displays;
4847 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004848 d.what = DisplayState::eDisplayProjectionChanged |
4849 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004850 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004851 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004852 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004853 d.orientedDisplaySpaceRect.makeInvalid();
4854 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004855 d.width = 0;
4856 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004857 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004858
Vishnu Nair9a69a042021-06-18 13:19:49 -07004859 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004860
4861 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004862 // It should be on the main thread, apply it directly.
4863 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004864 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004865 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004866
Peiyong Lin65248e02020-04-18 21:15:07 -07004867 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004868 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004869 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004870 mActiveDisplayTransformHint = display->getTransformHint();
Brian Andersond0010582017-03-07 13:20:31 -08004871 // Use phase of 0 since phase is not known.
4872 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004873 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004874 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004875}
4876
4877void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004878 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004879 static_cast<void>(
4880 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004881}
4882
Peiyong Lin65248e02020-04-18 21:15:07 -07004883void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004884 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004885 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004886 return;
4887 }
4888
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004889 const auto displayId = display->getPhysicalId();
4890 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004891
Peiyong Lin65248e02020-04-18 21:15:07 -07004892 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004893 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004894 return;
4895 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004896
Ady Abraham4f960d12021-10-13 16:59:49 -07004897 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4898 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4899 activeDisplay->isPoweredOn()) {
4900 ALOGW("Trying to change power mode on non active display while the active display is ON");
4901 }
4902
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004903 display->setPowerMode(mode);
4904
Lloyd Pique4dccc412018-01-22 17:21:36 -08004905 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004906 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004907 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004908 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004909 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004910 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004911 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004912 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004913 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004914 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4915 // We can merge the syscall later.
4916 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4917 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4918 }
Martin Liu4a322352020-03-24 21:30:38 +08004919 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4920 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4921 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004922 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004923 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004924 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004925 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004926 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004927 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004928
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004929 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004930 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004931 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004932 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004933 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004934 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4935 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004936 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004937 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4938 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4939 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004940 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004941 mScheduler->disableHardwareVsync(true);
4942 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004943 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004944
Ady Abraham27c70212019-06-11 10:52:26 -07004945 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004946 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004947
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004948 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004949 mVisibleRegionsDirty = true;
4950 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004951 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004952 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004953 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004954 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004955 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004956 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004957 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004958 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004959 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004960 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004961 mScheduler->disableHardwareVsync(true);
4962 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004963 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004964 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004965 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004966 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004967 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004968 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004969
Ady Abrahamadc914c2021-10-13 17:04:27 -07004970 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004971 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004972 mRefreshRateStats->setPowerMode(mode);
Rachel Lee6a9731d2022-06-06 17:08:14 -07004973 mScheduler->setDisplayPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004974 }
4975
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004976 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004977}
4978
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004979void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004980 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004981 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004982 if (!display) {
4983 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4984 displayToken.get());
4985 } else if (display->isVirtual()) {
4986 ALOGW("Attempt to set power mode %d for virtual display", mode);
4987 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004988 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004989 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004990 });
4991
4992 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004993}
4994
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004995status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004996 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004997
Mathias Agopianbd115332013-04-18 16:41:04 -07004998 IPCThreadState* ipc = IPCThreadState::self();
4999 const int pid = ipc->getCallingPid();
5000 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07005001
Mathias Agopianbd115332013-04-18 16:41:04 -07005002 if ((uid != AID_SHELL) &&
5003 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005004 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
5005 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005006 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08005007 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005008 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005009 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005010 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07005011 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005012 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005013 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
5014 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
5015 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08005016 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005017 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
5018 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005019 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005020 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005021 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005022 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005023
Dominik Laskowskic2867142019-01-21 11:33:38 -08005024 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005025
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005026 bool dumpLayers = true;
5027 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005028 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005029 if (!lock.locked()) {
5030 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
5031 strerror(-lock.status), lock.status);
5032 }
5033
5034 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
5035 (it->second)(args, asProto, result);
5036 dumpLayers = false;
5037 } else if (!asProto) {
5038 dumpAllLocked(args, result);
5039 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08005040 }
5041
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005042 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005043 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05005044 LayersTraceProto* layersTrace = traceFileProto.add_entry();
5045 LayersProto layersProto = dumpProtoFromMainThread();
5046 layersTrace->mutable_layers()->Swap(&layersProto);
5047 dumpDisplayProto(*layersTrace);
5048
Dominik Laskowski46470112019-08-02 13:13:11 -07005049 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05005050 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07005051 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07005052 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05005053 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07005054 result.append(LayerProtoParser::layerTreeToString(layerTree));
5055 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07005056 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07005057 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07005058 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005059 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005060 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005061 return NO_ERROR;
5062}
5063
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005064status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08005065 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005066 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005067 if (mTransactionTracing) {
5068 mTransactionTracing->writeToFile();
5069 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005070 }
5071
5072 return doDump(fd, DumpArgs(), asProto);
5073}
5074
Dominik Laskowskic2867142019-01-21 11:33:38 -08005075void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005076 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005077 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005078}
5079
Dominik Laskowskic2867142019-01-21 11:33:38 -08005080void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07005081 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005082
Dominik Laskowskic2867142019-01-21 11:33:38 -08005083 if (args.size() > 1) {
5084 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08005085 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005086 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005087 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005088 }
Robert Carr2047fae2016-11-28 14:09:09 -08005089 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005090 } else {
5091 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005092 }
5093}
5094
Dominik Laskowskic2867142019-01-21 11:33:38 -08005095void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005096 const bool clearAll = args.size() < 2;
5097 const auto name = clearAll ? String8() : String8(args[1]);
5098
Edgar Arriaga844fa672020-01-16 14:21:42 -08005099 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005100 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005101 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005102 }
Robert Carr2047fae2016-11-28 14:09:09 -08005103 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005104
Svetoslavd85084b2014-03-20 10:28:31 -07005105 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005106}
5107
Dominik Laskowskic2867142019-01-21 11:33:38 -08005108void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5109 mTimeStats->parseArgs(asProto, args, result);
5110}
5111
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005112void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5113 mFrameTimeline->parseArgs(args, result);
5114}
5115
Jamie Gennis6547ff42013-07-16 20:12:42 -07005116void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005117 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005118 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005119 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005120
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005121 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005122}
5123
Yiwei Zhang5434a782018-12-05 18:06:32 -08005124void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005125 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005126
Yiwei Zhang5434a782018-12-05 18:06:32 -08005127 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5128 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005129 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5130 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005131 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5132 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5133 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005134 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005135}
5136
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005137void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005138 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005139
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005140 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005141 result.append("\n");
5142
Ady Abraham8287e852020-08-12 14:44:58 -07005143 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005144 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005145 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005146 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005147
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005148 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5149 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005150
Ana Krulecc2870422019-01-29 19:00:58 -08005151 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005152 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005153 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5154 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005155}
5156
Dan Stoza269dc4d2021-01-15 15:07:43 -08005157void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5158 for (const auto& [token, display] : mDisplays) {
5159 const auto compositionDisplay = display->getCompositionDisplay();
5160 compositionDisplay->dumpPlannerInfo(args, result);
5161 }
5162}
5163
Yiwei Zhang5434a782018-12-05 18:06:32 -08005164void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5165 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005166 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5167 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005168 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005169 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005170 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005171 }
David Sodman4a36e932017-11-07 14:29:47 -08005172 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005173 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005174 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005175 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5176 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005177}
5178
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005179void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5180 for (const auto& [token, display] : mDisplays) {
5181 display->getCompositionDisplay()->dump(result);
5182 result += '\n';
5183 }
5184}
5185
5186void SurfaceFlinger::dumpDisplays(std::string& result) const {
5187 for (const auto& [token, display] : mDisplays) {
5188 display->dump(result);
5189 result += '\n';
5190 }
5191}
5192
Yiwei Zhang5434a782018-12-05 18:06:32 -08005193void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005194 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005195 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005196 if (!displayId) {
5197 continue;
5198 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005199 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005200 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005201 continue;
5202 }
5203
Yiwei Zhang5434a782018-12-05 18:06:32 -08005204 StringAppendF(&result,
5205 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5206 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005207 uint8_t port;
5208 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005209 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005210 result.append("no identification data\n");
5211 continue;
5212 }
5213
5214 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005215 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005216 continue;
5217 }
5218
5219 const auto edid = parseEdid(data);
5220 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005221 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005222 continue;
5223 }
5224
Yiwei Zhang5434a782018-12-05 18:06:32 -08005225 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005226 result.append(edid->displayName.data(), edid->displayName.length());
5227 result.append("\"\n");
5228 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005229}
5230
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005231void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5232 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005233 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005234 uint8_t port;
5235 DisplayIdentificationData data;
5236
5237 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5238 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5239 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5240 }
5241}
5242
Yiwei Zhang5434a782018-12-05 18:06:32 -08005243void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005244 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005245 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5246 StringAppendF(&result, "DisplayColorSetting: %s\n",
5247 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005248
5249 // TODO: print out if wide-color mode is active or not
5250
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005251 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005252 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005253 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005254 continue;
5255 }
5256
Yiwei Zhang5434a782018-12-05 18:06:32 -08005257 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005258 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005259 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005260 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005261 }
5262
Lloyd Pique32cbe282018-10-19 13:09:22 -07005263 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005264 StringAppendF(&result, " Current color mode: %s (%d)\n",
5265 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005266 }
5267 result.append("\n");
5268}
5269
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005270LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005271 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005272 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005273 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005274 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005275
chaviw1d044282017-09-27 12:19:28 -07005276 return layersProto;
5277}
5278
chaviw0a398992021-08-13 10:13:01 -05005279void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005280 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005281 DisplayProto* displayProto = layersTraceProto.add_displays();
5282 displayProto->set_id(display->getId().value);
5283 displayProto->set_name(display->getDisplayName());
5284 displayProto->set_layer_stack(display->getLayerStack().id);
5285 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5286 [&]() { return displayProto->mutable_size(); });
5287 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5288 return displayProto->mutable_layer_stack_space_rect();
5289 });
5290 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5291 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005292 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005293 }
5294}
5295
Alec Mouri6b9e9912020-01-21 10:50:24 -08005296void SurfaceFlinger::dumpHwc(std::string& result) const {
5297 getHwComposer().dump(result);
5298}
5299
Vishnu Nair0f085c62019-08-30 08:49:12 -07005300void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5301 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5302 // it.
5303 LayerProto* rootProto = layersProto.add_layers();
5304 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5305 rootProto->set_id(offscreenRootLayerId);
5306 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005307 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005308
5309 for (Layer* offscreenLayer : mOffscreenLayers) {
5310 // Add layer as child of the fake root
5311 rootProto->add_children(offscreenLayer->sequence);
5312
5313 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005314 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005315 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005316 }
5317}
5318
Vishnu Nair8406fd72019-07-30 11:29:31 -07005319LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005320 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005321}
5322
Vishnu Nair0f085c62019-08-30 08:49:12 -07005323void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005324 auto future = mScheduler->schedule([this] {
5325 std::string result;
5326 for (Layer* offscreenLayer : mOffscreenLayers) {
5327 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5328 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5329 }
5330 return result;
5331 });
5332
Vishnu Nair0f085c62019-08-30 08:49:12 -07005333 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005334 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005335}
5336
Dominik Laskowskic2867142019-01-21 11:33:38 -08005337void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5338 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005339 Colorizer colorizer(colorize);
5340
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005341 // figure out if we're stuck somewhere
5342 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005343 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005344 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5345
5346 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005347 * Dump library configuration.
5348 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005349
5350 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005351 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005352 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005353 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005354 result.append("\n");
5355
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005356 result.append("\nDisplay identification data:\n");
5357 dumpDisplayIdentificationData(result);
5358
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005359 result.append("\nWide-Color information:\n");
5360 dumpWideColorInfo(result);
5361
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005362 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005363 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005364 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005365 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005366 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005367
Andy McFadden41d67d72014-04-25 16:58:34 -07005368 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005369 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005370 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005371 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005372 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005373
Dan Stozab90cf072015-03-05 11:05:59 -08005374 dumpStaticScreenStats(result);
5375 result.append("\n");
5376
Alec Mouri40189b02019-03-05 15:07:54 -08005377 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5378 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5379 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005380
Andy McFadden4803b742012-09-24 19:07:20 -07005381 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005382 * Dump the visible layer list
5383 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005384 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005385 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005386 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005387
Chia-I Wu2f884132018-09-13 15:17:58 -07005388 {
Lloyd Pique207def92019-02-28 16:09:52 -08005389 StringAppendF(&result, "Composition layers\n");
5390 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005391 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005392 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005393
5394 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5395 layer->getDebugName() ? layer->getDebugName()
5396 : "<unknown>");
5397 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005398 });
5399 }
5400
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005401 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005402 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005403 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005404 dumpDisplays(result);
5405 dumpCompositionDisplays(result);
5406 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005407
5408 mCompositionEngine->dump(result);
5409
5410 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005411 * Dump SurfaceFlinger global state
5412 */
5413
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005414 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005415 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005416 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005417
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005418 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005419
Robert Carrbeba6f02021-02-10 21:06:27 -08005420 result.append("ClientCache state:\n");
5421 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005422 DebugEGLImageTracker::getInstance()->dump(result);
5423
Dominik Laskowski075d3172018-05-24 15:50:06 -07005424 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005425 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5426 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005427 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5428 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005429 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005430 StringAppendF(&result,
5431 " transaction-flags : %08x\n"
5432 " gpu_to_cpu_unsupported : %d\n",
5433 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005434
Marin Shalamanov045b7002021-01-07 16:56:24 +01005435 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005436 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005437 if (const auto activeMode = display->getActiveMode()) {
5438 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005439
5440 const auto dpi = activeMode->getDpi();
5441 xDpi = base::StringPrintf("%.2f", dpi.x);
5442 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005443 } else {
5444 fps = "unknown";
5445 xDpi = "unknown";
5446 yDpi = "unknown";
5447 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005448 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005449 " refresh-rate : %s\n"
5450 " x-dpi : %s\n"
5451 " y-dpi : %s\n",
5452 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005453 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005454
Yiwei Zhang5434a782018-12-05 18:06:32 -08005455 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005456
Dan Stozae22aec72016-08-01 13:20:59 -07005457 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005458 * Tracing state
5459 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005460 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005461
5462 result.append("\nTransaction tracing: ");
5463 if (mTransactionTracing) {
5464 result.append("enabled\n");
5465 mTransactionTracing->dump(result);
5466 } else {
5467 result.append("disabled\n");
5468 }
5469 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005470
5471 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005472 * HWC layer minidump
5473 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005474 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005475 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005476 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005477 continue;
5478 }
5479
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005480 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5481 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005482 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005483
5484 const DisplayDevice& ref = *display;
5485 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005486 result.append("\n");
5487 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005488
Ady Abraham2790e9f2021-04-28 13:14:20 -07005489 {
5490 DumpArgs plannerArgs;
5491 plannerArgs.add(); // first argument is ignored
5492 plannerArgs.add(String16("--layers"));
5493 dumpPlannerInfo(plannerArgs, result);
5494 }
5495
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005496 /*
5497 * Dump HWComposer state
5498 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005499 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005500 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005501 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005502 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005503 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005504 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005505
5506 /*
5507 * Dump gralloc state
5508 */
5509 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5510 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005511
rnleea2ecd832021-07-29 13:58:30 -07005512 /*
5513 * Dump flag/property manager state
5514 */
Robert Carr9b623c32022-03-21 15:55:22 -07005515 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005516
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005517 result.append(mTimeStats->miniDump());
5518 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005519}
5520
chaviw17ac24b2021-01-28 18:50:05 -08005521mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5522 if (saturation == 1) {
5523 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005524 }
5525
chaviw17ac24b2021-01-28 18:50:05 -08005526 float3 luminance{0.213f, 0.715f, 0.072f};
5527 luminance *= 1.0f - saturation;
5528 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5529 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5530 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5531 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5532 return saturationMatrix;
5533}
5534
5535void SurfaceFlinger::updateColorMatrixLocked() {
5536 mat4 colorMatrix =
5537 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5538
Chia-I Wu28f320b2018-05-03 11:02:56 -07005539 if (mCurrentState.colorMatrix != colorMatrix) {
5540 mCurrentState.colorMatrix = colorMatrix;
5541 mCurrentState.colorMatrixChanged = true;
5542 setTransactionFlags(eTransactionNeeded);
5543 }
5544}
5545
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005546status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005547#pragma clang diagnostic push
5548#pragma clang diagnostic error "-Wswitch-enum"
5549 switch (static_cast<ISurfaceComposerTag>(code)) {
5550 // These methods should at minimum make sure that the client requested
5551 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005552 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005553 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005554 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005555 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005556 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5557 // permission dynamically. Don't use the permission cache for this check.
5558 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005559 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005560 IPCThreadState* ipc = IPCThreadState::self();
5561 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5562 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005563 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005564 }
Robert Carr1db73f62016-12-21 12:58:51 -08005565 return OK;
5566 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005567 // The following calls are currently used by clients that do not
5568 // request necessary permissions. However, they do not expose any secret
5569 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005570 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005571 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005572 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005573 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005574 // Calling setTransactionState is safe, because you need to have been
5575 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005576 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005577 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005578 return OK;
5579 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005580 case BOOT_FINISHED:
5581 // Used by apps to hook Choreographer to SurfaceFlinger.
5582 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005583 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005584 case CREATE_DISPLAY:
5585 case DESTROY_DISPLAY:
5586 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5587 case GET_PHYSICAL_DISPLAY_IDS:
5588 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005589 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005590 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005591 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005592 case GET_DISPLAY_STATE:
5593 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005594 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005595 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005596 case GET_DISPLAY_NATIVE_PRIMARIES:
5597 case SET_ACTIVE_COLOR_MODE:
5598 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005599 case CLEAR_BOOT_DISPLAY_MODE:
5600 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5601 case SET_AUTO_LOW_LATENCY_MODE:
5602 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005603 case CAPTURE_LAYERS:
5604 case CAPTURE_DISPLAY:
5605 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005606 case CLEAR_ANIMATION_FRAME_STATS:
5607 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005608 case OVERRIDE_HDR_TYPES:
5609 case ON_PULL_ATOM:
5610 case ENABLE_VSYNC_INJECTIONS:
5611 case INJECT_VSYNC:
5612 case GET_LAYER_DEBUG_INFO:
5613 case GET_COLOR_MANAGEMENT:
5614 case GET_COMPOSITION_PREFERENCE:
5615 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5616 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005617 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005618 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005619 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005620 case ADD_REGION_SAMPLING_LISTENER:
5621 case REMOVE_REGION_SAMPLING_LISTENER:
5622 case ADD_FPS_LISTENER:
5623 case REMOVE_FPS_LISTENER:
5624 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5625 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5626 case ADD_WINDOW_INFOS_LISTENER:
5627 case REMOVE_WINDOW_INFOS_LISTENER:
5628 case SET_DESIRED_DISPLAY_MODE_SPECS:
5629 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005630 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5631 case SET_DISPLAY_BRIGHTNESS:
5632 case ADD_HDR_LAYER_INFO_LISTENER:
5633 case REMOVE_HDR_LAYER_INFO_LISTENER:
5634 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005635 case SET_GLOBAL_SHADOW_SETTINGS:
5636 case GET_DISPLAY_DECORATION_SUPPORT:
5637 case SET_FRAME_RATE:
5638 case SET_OVERRIDE_FRAME_RATE:
5639 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005640 case ADD_TRANSACTION_TRACE_LISTENER:
5641 case GET_GPU_CONTEXT_PRIORITY:
5642 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005643 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005644 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005645 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005646
5647 // These codes are used for the IBinder protocol to either interrogate the recipient
5648 // side of the transaction for its canonical interface descriptor or to dump its state.
5649 // We let them pass by default.
5650 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5651 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5652 code == IBinder::SYSPROPS_TRANSACTION) {
5653 return OK;
5654 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005655 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005656 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005657 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005658 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5659 return OK;
5660 }
5661 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5662 return PERMISSION_DENIED;
5663#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005664}
5665
Ana Krulec13be8ad2018-08-21 02:43:56 +00005666status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5667 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005668 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5669 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005670 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005671
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005672 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5673 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005674 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005675 IPCThreadState* ipc = IPCThreadState::self();
5676 const int uid = ipc->getCallingUid();
5677 if (CC_UNLIKELY(uid != AID_SYSTEM
5678 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005679 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005680 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005681 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005682 return PERMISSION_DENIED;
5683 }
5684 int n;
5685 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005686 case 1000: // Unused.
5687 case 1001:
5688 return NAME_NOT_FOUND;
5689 case 1002: // Toggle flashing on surface damage.
5690 if (const int delay = data.readInt32(); delay > 0) {
5691 mDebugFlashDelay = delay;
5692 } else {
5693 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5694 }
5695 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005696 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005697 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005698 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005699 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005700 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005701 case 1005: { // Force commit ahead of next VSYNC.
5702 Mutex::Autolock lock(mStateLock);
5703 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5704 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005705 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005706 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005707 case 1007: // Unused.
5708 return NAME_NOT_FOUND;
5709 case 1008: // Toggle forced GPU composition.
5710 mDebugDisableHWC = data.readInt32() != 0;
5711 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005712 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005713 case 1009: // Toggle use of transform hint.
5714 mDebugDisableTransformHint = data.readInt32() != 0;
5715 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005716 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005717 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005718 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005719 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005720 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005721 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005722 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005723 return NO_ERROR;
5724 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005725 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005726 if (!display) {
5727 return NAME_NOT_FOUND;
5728 }
5729
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005730 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005731 return NO_ERROR;
5732 }
5733 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005734 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005735 // daltonize
5736 n = data.readInt32();
5737 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005738 case 1:
5739 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5740 break;
5741 case 2:
5742 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5743 break;
5744 case 3:
5745 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5746 break;
5747 default:
5748 mDaltonizer.setType(ColorBlindnessType::None);
5749 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005750 }
5751 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005752 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005753 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005754 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005755 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005756
5757 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005758 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005759 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005760 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005761 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005762 // apply a color matrix
5763 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005764 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005765 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005766 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005767 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005768 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005769 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005770 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005771 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005772 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005773 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005774
5775 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5776 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005777 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005778 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5779 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5780 }
5781
Chia-I Wu28f320b2018-05-03 11:02:56 -07005782 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005783 return NO_ERROR;
5784 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005785 case 1016: { // Unused.
5786 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005787 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005788 case 1017: {
5789 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005790 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005791 return NO_ERROR;
5792 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005793 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005794 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005795 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005796 return NO_ERROR;
5797 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005798 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005799 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005800 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005801 return NO_ERROR;
5802 }
Irvel468051e2016-06-13 16:44:44 -07005803 case 1020: { // Layer updates interceptor
5804 n = data.readInt32();
5805 if (n) {
5806 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005807 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005808 }
5809 else{
5810 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005811 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005812 }
5813 return NO_ERROR;
5814 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005815 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005816 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005817 static_cast<void>(
5818 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005819 return NO_ERROR;
5820 }
Romain Guy0147a172017-06-01 13:53:56 -07005821 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005822 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005823 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005824
Chia-I Wu28f320b2018-05-03 11:02:56 -07005825 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005826 return NO_ERROR;
5827 }
Romain Guy54f154a2017-10-24 21:40:32 +01005828 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005829 int32_t colorMode;
5830
Chia-I Wu0d711262018-05-21 15:19:35 -07005831 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005832 if (data.readInt32(&colorMode) == NO_ERROR) {
5833 mForceColorMode = static_cast<ColorMode>(colorMode);
5834 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005835 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005836 return NO_ERROR;
5837 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005838 // Deprecate, use 1030 to check whether the device is color managed.
5839 case 1024: {
5840 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005841 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005842 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005843 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005844 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005845 if (n == 1) {
5846 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005847 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005848 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005849 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005850 int64_t startingTime =
5851 (fixedStartingTime) ? fixedStartingTime : systemTime();
5852 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005853 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Pablo Gamitob8775792022-06-10 15:02:42 +00005854 mLayerTracing.notify(true /* visibleRegionDirty */,
Pablo Gamito6be82442022-06-13 11:04:34 +00005855 startingTime, mLastCommittedVsyncId);
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005856 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005857 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005858 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005859 } else if (n == 2) {
5860 std::string filename = std::string(data.readCString());
5861 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5862 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005863 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005864 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005865 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005866 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005867 mTracingEnabledChanged = tracingEnabledChanged;
5868 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005869 return NO_ERROR;
5870 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005871 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005872 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005873 return NO_ERROR;
5874 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005875 // Is a DisplayColorSetting supported?
5876 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005877 const auto display = getDefaultDisplayDevice();
5878 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005879 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005880 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005881
5882 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5883 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005884 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005885 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005886 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005887 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005888 reply->writeBool(true);
5889 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005890 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005891 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005892 break;
5893 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005894 reply->writeBool(
5895 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005896 break;
5897 }
5898 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005899 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005900 case 1028: { // Unused.
5901 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005902 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005903 // Set buffer size for SF tracing (value in KB)
5904 case 1029: {
5905 n = data.readInt32();
5906 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5907 ALOGW("Invalid buffer size: %d KB", n);
5908 reply->writeInt32(BAD_VALUE);
5909 return BAD_VALUE;
5910 }
5911
5912 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005913 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005914 reply->writeInt32(NO_ERROR);
5915 return NO_ERROR;
5916 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005917 // Is device color managed?
5918 case 1030: {
5919 reply->writeBool(useColorManagement);
5920 return NO_ERROR;
5921 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005922 // Override default composition data space
5923 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5924 // && adb shell stop zygote && adb shell start zygote
5925 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5926 // adb shell stop zygote && adb shell start zygote
5927 case 1031: {
5928 Mutex::Autolock _l(mStateLock);
5929 n = data.readInt32();
5930 if (n) {
5931 n = data.readInt32();
5932 if (n) {
5933 Dataspace dataspace = static_cast<Dataspace>(n);
5934 if (!validateCompositionDataspace(dataspace)) {
5935 return BAD_VALUE;
5936 }
5937 mDefaultCompositionDataspace = dataspace;
5938 }
5939 n = data.readInt32();
5940 if (n) {
5941 Dataspace dataspace = static_cast<Dataspace>(n);
5942 if (!validateCompositionDataspace(dataspace)) {
5943 return BAD_VALUE;
5944 }
5945 mWideColorGamutCompositionDataspace = dataspace;
5946 }
5947 } else {
5948 // restore composition data space.
5949 mDefaultCompositionDataspace = defaultCompositionDataspace;
5950 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5951 }
5952 return NO_ERROR;
5953 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005954 // Set trace flags
5955 case 1033: {
5956 n = data.readUint32();
5957 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005958 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005959 reply->writeInt32(NO_ERROR);
5960 return NO_ERROR;
5961 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005962 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005963 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005964 switch (n = data.readInt32()) {
5965 case 0:
5966 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005967 FTL_FAKE_GUARD(mStateLock,
5968 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005969 break;
5970 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005971 reply->writeBool(
5972 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005973 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005974 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005975 });
5976
5977 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005978 return NO_ERROR;
5979 }
Ady Abraham34392f72019-04-10 11:29:27 -07005980 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005981 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005982
Dominik Laskowskif1833852021-03-23 15:06:50 -07005983 const auto display = [&]() -> sp<IBinder> {
5984 uint64_t value;
5985 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005986 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005987 }
5988
Dominik Laskowskif1833852021-03-23 15:06:50 -07005989 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5990 return getPhysicalDisplayToken(*id);
5991 }
5992
5993 ALOGE("Invalid physical display ID");
5994 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005995 }();
5996
Shiyong Li2bcece92021-08-30 20:38:50 +00005997 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005998 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005999 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
6000 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07006001 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006002 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
6003 // manager frame rate policy a new policy which allows switching between all refresh
6004 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07006005 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006006 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07006007 return mScheduler
6008 ->schedule([this] {
6009 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006010 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006011
Dominik Laskowski756b7892021-08-04 12:53:59 -07006012 // This is a little racy, but not in a way that hurts anything. As
6013 // we grab the defaultMode from the display manager policy, we could
6014 // be setting a new display manager policy, leaving us using a stale
6015 // defaultMode. The defaultMode doesn't matter for the override
6016 // policy though, since we set allowGroupSwitching to true, so it's
6017 // not a problem.
6018 scheduler::RefreshRateConfigs::Policy overridePolicy;
6019 overridePolicy.defaultMode = display->refreshRateConfigs()
6020 .getDisplayManagerPolicy()
6021 .defaultMode;
6022 overridePolicy.allowGroupSwitching = true;
6023 constexpr bool kOverridePolicy = true;
6024 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
6025 kOverridePolicy);
6026 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006027 .get();
6028 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07006029 return mScheduler
6030 ->schedule([this] {
6031 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006032 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07006033 constexpr bool kOverridePolicy = true;
6034 return setDesiredDisplayModeSpecsInternal(display, {},
6035 kOverridePolicy);
6036 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006037 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07006038 }
Ady Abraham07e54702020-04-16 15:05:37 -07006039 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02006040 // Inject a hotplug connected event for the primary display. This will deallocate and
6041 // reallocate the display state including framebuffers.
6042 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006043 const hal::HWDisplayId hwcId =
6044 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
6045
6046 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02006047 return NO_ERROR;
6048 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07006049 // Modify the max number of display frames stored within FrameTimeline
6050 case 1038: {
6051 n = data.readInt32();
6052 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
6053 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
6054 return BAD_VALUE;
6055 }
6056 if (n == 0) {
6057 // restore to default
6058 mFrameTimeline->reset();
6059 return NO_ERROR;
6060 }
6061 mFrameTimeline->setMaxDisplayFrames(n);
6062 return NO_ERROR;
6063 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07006064 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07006065 PhysicalDisplayId displayId = [&]() {
6066 Mutex::Autolock lock(mStateLock);
6067 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6068 }();
6069
6070 auto inUid = static_cast<uid_t>(data.readInt32());
6071 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08006072 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
6073 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07006074 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08006075 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006076 // Toggle caching feature
6077 // First argument is an int32 - nonzero enables caching and zero disables caching
6078 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6079 // caching to a particular physical display
6080 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006081 auto future = mScheduler->schedule([&] {
6082 n = data.readInt32();
6083 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6084 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6085 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6086 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6087 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6088 return NAME_NOT_FOUND;
6089 }
6090 }
6091 {
6092 Mutex::Autolock lock(mStateLock);
6093 mLayerCachingEnabled = n != 0;
6094 for (const auto& [_, display] : mDisplays) {
6095 if (!inputId || *inputId == display->getPhysicalId()) {
6096 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006097 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006098 }
6099 }
6100 return OK;
6101 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006102
Dominik Laskowski756b7892021-08-04 12:53:59 -07006103 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006104 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006105 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006106 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006107 return NO_ERROR;
6108 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006109 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006110 if (mTransactionTracing) {
6111 if (data.readInt32()) {
6112 // Transaction tracing is always running but allow the user to temporarily
6113 // increase the buffer when actively debugging.
6114 mTransactionTracing->setBufferSize(
6115 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6116 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006117 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006118 mTransactionTracing->setBufferSize(
6119 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006120 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006121 }
6122 reply->writeInt32(NO_ERROR);
6123 return NO_ERROR;
6124 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006125 case 1042: { // Write layers trace or transaction trace to file
6126 if (mTransactionTracing) {
6127 mTransactionTracing->writeToFile();
6128 }
6129 if (mLayerTracingEnabled) {
6130 mLayerTracing.writeToFile();
6131 }
6132 reply->writeInt32(NO_ERROR);
6133 return NO_ERROR;
6134 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006135 }
6136 }
6137 return err;
6138}
6139
Ady Abrahama09852a2020-02-20 14:23:42 -08006140void SurfaceFlinger::kernelTimerChanged(bool expired) {
6141 static bool updateOverlay =
6142 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006143 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006144
6145 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006146 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006147 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006148 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006149 if (!display) {
6150 ALOGW("%s: default display is null", __func__);
6151 return;
6152 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006153 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006154
6155 const auto desiredActiveMode = display->getDesiredActiveMode();
6156 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6157 ? std::make_optional(desiredActiveMode->mode->getId())
6158 : std::nullopt;
6159
6160 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6161
Ady Abraham1b11bc62021-06-03 19:51:19 -07006162 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006163 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006164 }
6165 }));
6166}
6167
ramindani32cf0602022-03-02 02:30:29 +00006168std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6169SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6170 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6171 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6172 const auto timeout = getIdleTimerTimeout(displayId);
6173 if (isKernelIdleTimerHwcSupported) {
6174 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6175 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6176 // In order to decide if we can use the HWC api for idle timer
6177 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6178 // without relying on hasDisplayCapability.
6179 // hasDisplayCapability relies on DisplayCapabilities
6180 // which are updated after we set the PowerMode::ON.
6181 // DISPLAY_IDLE_TIMER is a display driver property
6182 // and is available before the PowerMode::ON
6183 return {KernelIdleTimerController::HwcApi, timeout};
6184 }
6185 return {std::nullopt, timeout};
6186 }
6187 if (getKernelIdleTimerSyspropConfig(displayId)) {
6188 return {KernelIdleTimerController::Sysprop, timeout};
6189 }
6190
6191 return {std::nullopt, timeout};
6192}
6193
6194void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6195 KernelIdleTimerController controller,
6196 PhysicalDisplayId displayId) {
6197 switch (controller) {
6198 case KernelIdleTimerController::HwcApi: {
6199 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6200 break;
6201 }
6202 case KernelIdleTimerController::Sysprop: {
6203 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6204 break;
6205 }
6206 }
6207}
6208
Ana Krulecb9afd792020-06-11 13:16:15 -07006209void SurfaceFlinger::toggleKernelIdleTimer() {
6210 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6211
Ady Abraham3efa3942021-06-24 19:01:25 -07006212 const auto display = getDefaultDisplayDeviceLocked();
6213 if (!display) {
6214 ALOGW("%s: default display is null", __func__);
6215 return;
6216 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006217
Ady Abrahame9316b72021-09-24 17:04:36 -07006218 // If the support for kernel idle timer is disabled for the active display,
6219 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006220 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6221 display->refreshRateConfigs().kernelIdleTimerController();
6222 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006223 return;
6224 }
6225
Ady Abraham3efa3942021-06-24 19:01:25 -07006226 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006227
Ana Krulecb9afd792020-06-11 13:16:15 -07006228 switch (action) {
6229 case KernelIdleTimerAction::TurnOff:
6230 if (mKernelIdleTimerEnabled) {
6231 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006232 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6233 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6234 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006235 mKernelIdleTimerEnabled = false;
6236 }
6237 break;
6238 case KernelIdleTimerAction::TurnOn:
6239 if (!mKernelIdleTimerEnabled) {
6240 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006241 const std::chrono::milliseconds timeout =
6242 display->refreshRateConfigs().getIdleTimerTimeout();
6243 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6244 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006245 mKernelIdleTimerEnabled = true;
6246 }
6247 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006248 }
6249}
6250
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006251// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6252class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006253public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006254 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6255 ~WindowDisconnector() {
6256 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006257 }
6258
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006259private:
6260 ANativeWindow* mWindow;
6261 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006262};
6263
chaviw93df2ea2019-04-30 16:45:12 -07006264static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6265 switch (colorMode) {
6266 case ColorMode::DISPLAY_P3:
6267 case ColorMode::BT2100_PQ:
6268 case ColorMode::BT2100_HLG:
6269 case ColorMode::DISPLAY_BT2020:
6270 return Dataspace::DISPLAY_P3;
6271 default:
6272 return Dataspace::V0_SRGB;
6273 }
6274}
6275
chaviwf5bb97b2021-04-28 15:35:37 -05006276static bool hasCaptureBlackoutContentPermission() {
6277 IPCThreadState* ipc = IPCThreadState::self();
6278 const int pid = ipc->getCallingPid();
6279 const int uid = ipc->getCallingUid();
6280 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6281 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6282}
6283
chaviw4b9d5e12020-08-04 18:30:35 -07006284static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6285 IPCThreadState* ipc = IPCThreadState::self();
6286 const int pid = ipc->getCallingPid();
6287 const int uid = ipc->getCallingUid();
6288 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6289 return OK;
6290 }
6291
6292 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6293 // itself, we allow it to continue.
6294 if (captureArgs.uid == uid) {
6295 return OK;
6296 }
6297
6298 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6299 return PERMISSION_DENIED;
6300}
6301
Peiyong Lin05cc0112020-10-14 16:16:37 -07006302status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6303 static constexpr int kFifoPriority = 2;
6304 static constexpr int kOtherPriority = 0;
6305
6306 struct sched_param param = {0};
6307 int sched_policy;
6308 if (enabled) {
6309 sched_policy = SCHED_FIFO;
6310 param.sched_priority = kFifoPriority;
6311 } else {
6312 sched_policy = SCHED_OTHER;
6313 param.sched_priority = kOtherPriority;
6314 }
6315
6316 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6317 return -errno;
6318 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006319
6320 return NO_ERROR;
6321}
6322
6323status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6324 static const unsigned int kUclampMin =
6325 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6326
6327 if (!kUclampMin) {
6328 // uclamp.min set to 0 (default), skip setting
6329 return NO_ERROR;
6330 }
6331
6332 // Currently, there is no wrapper in bionic: b/183240349.
6333 struct sched_attr {
6334 uint32_t size;
6335 uint32_t sched_policy;
6336 uint64_t sched_flags;
6337 int32_t sched_nice;
6338 uint32_t sched_priority;
6339 uint64_t sched_runtime;
6340 uint64_t sched_deadline;
6341 uint64_t sched_period;
6342 uint32_t sched_util_min;
6343 uint32_t sched_util_max;
6344 };
6345
6346 sched_attr attr = {};
6347 attr.size = sizeof(attr);
6348
6349 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6350 attr.sched_util_min = enabled ? kUclampMin : 0;
6351 attr.sched_util_max = 1024;
6352
6353 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6354 return -errno;
6355 }
6356
Peiyong Lin05cc0112020-10-14 16:16:37 -07006357 return NO_ERROR;
6358}
6359
chaviwd2432892020-07-24 17:42:39 -07006360status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006361 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006362 ATRACE_CALL();
6363
chaviw4b9d5e12020-08-04 18:30:35 -07006364 status_t validate = validateScreenshotPermissions(args);
6365 if (validate != OK) {
6366 return validate;
6367 }
6368
chaviwd2432892020-07-24 17:42:39 -07006369 if (!args.displayToken) return BAD_VALUE;
6370
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006371 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006372 ui::LayerStack layerStack;
6373 ui::Size reqSize(args.width, args.height);
6374 ui::Dataspace dataspace;
6375 {
6376 Mutex::Autolock lock(mStateLock);
6377 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6378 if (!display) return NAME_NOT_FOUND;
6379 displayWeak = display;
6380 layerStack = display->getLayerStack();
6381
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006382 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006383 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006384 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006385 }
6386
arthurhung79e81aa2020-08-28 00:09:19 +08006387 // The dataspace is depended on the color mode of display, that could use non-native mode
6388 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6389 // and failed if display is not in native mode. This provide a way to force using native
6390 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006391 dataspace = args.dataspace;
6392 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006393 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6394 dataspace = pickDataspaceFromColorMode(colorMode);
6395 }
chaviwd2432892020-07-24 17:42:39 -07006396 }
6397
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006398 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006399 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006400 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006401 });
6402
chaviw4b9d5e12020-08-04 18:30:35 -07006403 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6404 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006405 };
chaviw03900772020-08-18 12:34:51 -07006406
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006407 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6408 args.pixelFormat, args.allowProtected, args.grayscale,
6409 captureListener);
6410 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006411}
6412
Dominik Laskowskif1833852021-03-23 15:06:50 -07006413status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006414 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006415 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006416 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006417 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006418 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006419 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006420 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006421
Dominik Laskowskif1833852021-03-23 15:06:50 -07006422 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006423 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006424 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006425 }
6426
chaviw93df2ea2019-04-30 16:45:12 -07006427 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006428 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006429 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006430
chaviw426b5c02020-07-27 11:20:15 -07006431 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006432 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6433 }
6434
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006435 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006436 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006437 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006438 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006439 });
chaviw93df2ea2019-04-30 16:45:12 -07006440
Marin Shalamanov1c434292020-06-12 01:47:29 +02006441 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006442 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006443 };
6444
Sally Qi59a9f502021-10-12 18:53:23 +00006445 if (captureListener == nullptr) {
6446 ALOGE("capture screen must provide a capture listener callback");
6447 return BAD_VALUE;
6448 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006449
6450 constexpr bool kAllowProtected = false;
6451 constexpr bool kGrayscale = false;
6452
6453 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6454 ui::PixelFormat::RGBA_8888, kAllowProtected, kGrayscale,
6455 captureListener);
6456 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006457}
6458
chaviw3efadb12020-07-27 10:07:15 -07006459status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006460 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006461 ATRACE_CALL();
6462
chaviw4b9d5e12020-08-04 18:30:35 -07006463 status_t validate = validateScreenshotPermissions(args);
6464 if (validate != OK) {
6465 return validate;
6466 }
6467
Marin Shalamanov1c434292020-06-12 01:47:29 +02006468 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006469 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006470 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006471 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006472 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006473
6474 // Call this before holding mStateLock to avoid any deadlocking.
6475 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6476
Robert Carrc0df3122019-04-11 13:18:21 -07006477 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006478 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006479
Vishnu Nairf9096652021-07-20 18:49:42 -07006480 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006481 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006482 ALOGE("captureLayers called with an invalid or removed parent");
6483 return NAME_NOT_FOUND;
6484 }
6485
chaviwf5bb97b2021-04-28 15:35:37 -05006486 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006487 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006488 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6489 return PERMISSION_DENIED;
6490 }
6491
Robert Carr6a160312021-05-17 12:08:20 -07006492 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006493 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006494 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006495 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006496 }
6497
chaviw3efadb12020-07-27 10:07:15 -07006498 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006499 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006500 crop.bottom = parentSourceBounds.getHeight();
6501 }
6502
chaviw17ac24b2021-01-28 18:50:05 -08006503 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006504 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6505 // crop was not specified, or an invalid frame scale was provided.
6506 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006507 }
chaviw17ac24b2021-01-28 18:50:05 -08006508 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006509
chaviw3efadb12020-07-27 10:07:15 -07006510 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006511 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006512 if (excludeLayer != nullptr) {
6513 excludeLayers.emplace(excludeLayer);
6514 } else {
6515 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6516 return NAME_NOT_FOUND;
6517 }
6518 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006519
arthurhung79e81aa2020-08-28 00:09:19 +08006520 // The dataspace is depended on the color mode of display, that could use non-native mode
6521 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6522 // and failed if display is not in native mode. This provide a way to force using native
6523 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006524 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006525 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006526
Chia-I Wu20261cb2018-08-23 12:55:44 -07006527 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006528 if (reqSize.width <= 0 || reqSize.height <= 0) {
6529 ALOGW("Failed to captureLayes: crop or scale too small");
6530 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006531 }
6532
chaviw79468ab2021-10-27 11:11:24 -05006533 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006534 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006535 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006536 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006537 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006538 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006539 });
6540
chaviw03900772020-08-18 12:34:51 -07006541 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006542 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6543 if (!layer->isVisible()) {
6544 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006545 } else if (args.childrenOnly && layer == parent.get()) {
6546 return;
6547 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006548 return;
chaviwa76b2712017-09-20 12:02:26 -07006549 }
Robert Carr866455f2019-04-02 16:28:26 -07006550
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006551 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006552 while (p != nullptr) {
6553 if (excludeLayers.count(p) != 0) {
6554 return;
6555 }
6556 p = p->getParent();
6557 }
6558
chaviwa76b2712017-09-20 12:02:26 -07006559 visitor(layer);
6560 });
6561 };
Robert Carr108b2c72019-04-02 16:32:58 -07006562
Sally Qi59a9f502021-10-12 18:53:23 +00006563 if (captureListener == nullptr) {
6564 ALOGE("capture screen must provide a capture listener callback");
6565 return BAD_VALUE;
6566 }
6567
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006568 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6569 args.pixelFormat, args.allowProtected, args.grayscale,
6570 captureListener);
6571 return fenceStatus(future.get());
chaviwa76b2712017-09-20 12:02:26 -07006572}
6573
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006574ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Sally Qi59a9f502021-10-12 18:53:23 +00006575 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6576 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6577 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006578 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006579
Garfield Tan9c9c1912021-07-19 12:02:16 -07006580 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6581 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6582 ") that exceeds render target size limit.",
6583 bufferSize.getWidth(), bufferSize.getHeight());
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006584 return ftl::yield<FenceResult>(base::unexpected(BAD_VALUE)).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006585 }
6586
Peiyong Lin05cc0112020-10-14 16:16:37 -07006587 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6588 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6589 // A protected layer has no implication on whether it's secure, which is explicitly set by
6590 // application to avoid being screenshot or drawn via unsecure display.
6591 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6592 bool hasProtectedLayer = false;
6593 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006594 auto future = mScheduler->schedule([=]() {
6595 bool protectedLayerFound = false;
6596 traverseLayers([&](Layer* layer) {
6597 protectedLayerFound =
6598 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6599 });
6600 return protectedLayerFound;
6601 });
6602 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006603 }
6604
Richard Liucbcb8952020-04-08 10:51:55 +00006605 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6606 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006607 (hasProtectedLayer && allowProtected && supportsProtected
6608 ? GRALLOC_USAGE_PROTECTED
6609 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006610 sp<GraphicBuffer> buffer =
6611 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6612 static_cast<android_pixel_format>(reqPixelFormat),
6613 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006614
6615 const status_t bufferStatus = buffer->initCheck();
6616 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6617 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006618 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6619 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6620 renderengine::impl::ExternalTexture::Usage::
6621 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006622 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006623 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006624}
6625
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006626ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006627 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6628 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6629 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006630 ATRACE_CALL();
6631
chaviwf5bb97b2021-04-28 15:35:37 -05006632 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006633
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006634 auto future = mScheduler->schedule([=, renderAreaFuture = std::move(renderAreaFuture)]() mutable
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006635 -> ftl::SharedFuture<FenceResult> {
chaviw03900772020-08-18 12:34:51 -07006636 ScreenCaptureResults captureResults;
6637 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6638 if (!renderArea) {
6639 ALOGW("Skipping screen capture because of invalid render area.");
6640 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006641 captureListener->onScreenCaptureCompleted(captureResults);
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006642 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
chaviw03900772020-08-18 12:34:51 -07006643 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006644
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006645 ftl::SharedFuture<FenceResult> renderFuture;
chaviw03900772020-08-18 12:34:51 -07006646 renderArea->render([&] {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006647 renderFuture =
6648 renderScreenImpl(*renderArea, traverseLayers, buffer, canCaptureBlackoutContent,
6649 regionSampling, grayscale, captureResults);
chaviw03900772020-08-18 12:34:51 -07006650 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006651
6652 if (captureListener) {
6653 // TODO: The future returned by std::async blocks the main thread. Return a chain of
6654 // futures to the Binder thread instead.
Sally Qi59a9f502021-10-12 18:53:23 +00006655 std::async([=]() mutable {
6656 ATRACE_NAME("captureListener is nonnull!");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006657 auto fenceResult = renderFuture.get();
6658 // TODO(b/232535621): Change ScreenCaptureResults to store a FenceResult.
6659 captureResults.result = fenceStatus(fenceResult);
6660 captureResults.fence = std::move(fenceResult).value_or(Fence::NO_FENCE);
Sally Qi59a9f502021-10-12 18:53:23 +00006661 captureListener->onScreenCaptureCompleted(captureResults);
6662 });
6663 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006664 return renderFuture;
Sally Qi59a9f502021-10-12 18:53:23 +00006665 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006666
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006667 if (captureListener) {
6668 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
Sally Qi59a9f502021-10-12 18:53:23 +00006669 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006670
6671 // Flatten nested futures.
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006672 auto chain = ftl::Future(std::move(future)).then([](ftl::SharedFuture<FenceResult> future) {
6673 return future;
6674 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006675
6676 return chain.share();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006677}
6678
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006679ftl::SharedFuture<FenceResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006680 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006681 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6682 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6683 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006684 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006685
chaviw426b5c02020-07-27 11:20:15 -07006686 traverseLayers([&](Layer* layer) {
6687 captureResults.capturedSecureLayers =
6688 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6689 });
6690
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006691 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006692
chaviw426b5c02020-07-27 11:20:15 -07006693 // We allow the system server to take screenshots of secure layers for
6694 // use in situations like the Screen-rotation animation and place
6695 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006696 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006697 ALOGW("FB is protected: PERMISSION_DENIED");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006698 return ftl::yield<FenceResult>(base::unexpected(PERMISSION_DENIED)).share();
chaviw426b5c02020-07-27 11:20:15 -07006699 }
6700
Alec Mouria90a5702021-04-16 16:36:21 +00006701 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006702 auto dataspace = renderArea.getReqDataSpace();
6703 auto parent = renderArea.getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00006704 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07006705 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
6706 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
6707
Robert Carr12a3b9b2022-03-10 09:55:29 -08006708 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6709 Mutex::Autolock lock(mStateLock);
6710 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6711 return display.getLayerStack() == layerStack;
6712 });
6713 if (!display) {
6714 // If the layer is not on a display, use the dataspace for the default display.
6715 display = getDefaultDisplayDeviceLocked();
6716 }
6717
6718 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6719 dataspace = pickDataspaceFromColorMode(colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00006720 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07006721 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
6722 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08006723 }
6724 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006725
chaviwa76b2712017-09-20 12:02:26 -07006726 const auto reqWidth = renderArea.getReqWidth();
6727 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006728 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006729 const auto transform = renderArea.getTransform();
6730 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006731 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006732
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006733 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006734 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006735
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006736 // assume that bounds are never offset, and that they are the same as the
6737 // buffer bounds.
6738 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006739 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006740 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006741
Robert Carr12a3b9b2022-03-10 09:55:29 -08006742 clientCompositionDisplay.outputDataspace = dataspace;
Sally Qie258f092022-05-19 15:24:12 -07006743 clientCompositionDisplay.currentLuminanceNits = displayBrightnessNits;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006744 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006745 clientCompositionDisplay.renderIntent =
6746 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006747
chaviw17ac24b2021-01-28 18:50:05 -08006748 const float colorSaturation = grayscale ? 0 : 1;
6749 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6750
chaviw50da5042018-04-09 13:49:37 -07006751 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006752
Vishnu Nair9b079a22020-01-21 14:36:08 -08006753 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006754 fillLayer.source.buffer.buffer = nullptr;
6755 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006756 fillLayer.geometry.boundaries =
6757 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006758 fillLayer.alpha = half(alpha);
6759 clientCompositionLayers.push_back(fillLayer);
6760
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006761 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006762 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006763 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006764 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006765 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006766
Lloyd Piquef16688f2019-02-19 17:47:57 -08006767 Region clip(renderArea.getBounds());
6768 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6769 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006770 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006771 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006772 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006773 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006774 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006775 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006776 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006777 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006778 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6779 BlurSetting::Disabled
6780 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6781 BlurSetting::Enabled,
Sally Qidb653012022-05-04 13:12:22 -07006782 isHdrLayer(layer) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006783
Lloyd Piquef16688f2019-02-19 17:47:57 -08006784 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006785 std::vector<compositionengine::LayerFE::LayerSettings> results =
6786 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006787 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006788 for (auto& settings : results) {
6789 settings.geometry.positionTransform =
6790 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006791 // There's no need to process blurs when we're executing region sampling,
6792 // we're just trying to understand what we're drawing, and doing so without
6793 // blurs is already a pretty good approximation.
6794 if (regionSampling) {
6795 settings.backgroundBlurRadius = 0;
6796 }
Sally Qidb653012022-05-04 13:12:22 -07006797 captureResults.capturedHdrLayers |= isHdrLayer(layer);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006798 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006799
Yichi Chen40773d92020-04-01 10:10:18 +08006800 clientCompositionLayers.insert(clientCompositionLayers.end(),
6801 std::make_move_iterator(results.begin()),
6802 std::make_move_iterator(results.end()));
6803 renderedLayers.push_back(layer);
6804 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006805
chaviwa76b2712017-09-20 12:02:26 -07006806 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006807
Sally Qi59a9f502021-10-12 18:53:23 +00006808 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6809 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006810 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006811 std::back_inserter(clientRenderEngineLayers),
6812 [](compositionengine::LayerFE::LayerSettings& settings)
6813 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006814
Alec Mouri6338c9d2019-02-07 16:57:51 -08006815 // Use an empty fence for the buffer fence, since we just created the buffer so
6816 // there is no need for synchronization with the GPU.
6817 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006818 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006819
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006820 constexpr bool kUseFramebufferCache = false;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006821 auto chain =
6822 ftl::Future(getRenderEngine().drawLayers(clientCompositionDisplay,
6823 clientRenderEngineLayers, buffer,
6824 kUseFramebufferCache, std::move(bufferFence)))
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006825 .then(&toFenceResult);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006826
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006827 const auto future = chain.share();
Sally Qi59a9f502021-10-12 18:53:23 +00006828 for (auto* layer : renderedLayers) {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006829 layer->onLayerDisplayed(future);
Yichi Chen40773d92020-04-01 10:10:18 +08006830 }
Ady Abraham99599942021-01-27 20:27:23 -08006831
Peiyong Lin05cc0112020-10-14 16:16:37 -07006832 // Always switch back to unprotected context.
6833 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006834
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006835 return future;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006836}
6837
chaviwbf023a62021-06-07 16:00:06 -05006838void SurfaceFlinger::windowInfosReported() {
chaviw95ef3c42019-02-14 10:55:09 -08006839 Mutex::Autolock _l(mStateLock);
Arthur Hung2274a312021-04-28 15:13:06 +00006840 signalSynchronousTransactions(CountDownLatch::eSyncInputWindows);
chaviw95ef3c42019-02-14 10:55:09 -08006841}
chaviw5f21a5e2019-02-14 10:00:34 -08006842
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006843// ---------------------------------------------------------------------------
6844
Edgar Arriaga844fa672020-01-16 14:21:42 -08006845void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6846 layersSortedByZ.traverse(visitor);
6847}
6848
Dan Stoza412903f2017-04-27 13:42:17 -07006849void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6850 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006851}
6852
Dan Stoza412903f2017-04-27 13:42:17 -07006853void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6854 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006855}
6856
chaviw4b9d5e12020-08-04 18:30:35 -07006857void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006858 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006859 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006860 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006861 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006862 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006863 continue;
6864 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006865 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006866 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006867 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006868 return;
6869 }
chaviwa76b2712017-09-20 12:02:26 -07006870 if (!layer->isVisible()) {
6871 return;
6872 }
chaviw4b9d5e12020-08-04 18:30:35 -07006873 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6874 return;
6875 }
chaviwa76b2712017-09-20 12:02:26 -07006876 visitor(layer);
6877 });
6878 }
6879}
6880
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006881status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006882 const sp<DisplayDevice>& display,
6883 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006884 Mutex::Autolock lock(mStateLock);
6885
Ady Abrahamfb853662021-04-09 11:46:40 -07006886 if (mDebugDisplayModeSetByBackdoor) {
6887 // ignore this request as mode is overridden by backdoor
6888 return NO_ERROR;
6889 }
6890
Ady Abrahama92a5682022-06-07 23:35:38 +00006891 const status_t setPolicyResult = display->setRefreshRatePolicy(policy, overridePolicy);
Ady Abraham3efa3942021-06-24 19:01:25 -07006892 if (setPolicyResult < 0) {
6893 return BAD_VALUE;
6894 }
6895 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6896 return NO_ERROR;
6897 }
6898
Ady Abraham3efa3942021-06-24 19:01:25 -07006899 scheduler::RefreshRateConfigs::Policy currentPolicy =
6900 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006901
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006902 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006903
Ana Krulecb9afd792020-06-11 13:16:15 -07006904 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6905 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006906 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006907 if (isDisplayActiveLocked(display)) {
6908 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6909 toggleKernelIdleTimer();
6910 } else {
6911 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6912 }
Ady Abraham838de062019-02-04 10:24:03 -08006913
Ady Abraham690f4612021-07-01 23:24:03 -07006914 const DisplayModePtr preferredDisplayMode = [&] {
6915 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6916 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6917 return schedulerMode;
6918 }
6919
6920 return display->getMode(currentPolicy.defaultMode);
6921 }();
6922
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006923 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006924 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006925
Ady Abraham690f4612021-07-01 23:24:03 -07006926 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006927 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006928 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006929 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006930 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006931 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006932 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006933 }
6934
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006935 return NO_ERROR;
6936}
6937
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006938status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6939 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6940 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6941 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006942 ATRACE_CALL();
6943
6944 if (!displayToken) {
6945 return BAD_VALUE;
6946 }
6947
Dominik Laskowski756b7892021-08-04 12:53:59 -07006948 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006949 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006950 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006951 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006952 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006953 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006954 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006955 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006956 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006957 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006958 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006959 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006960 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006961 {Fps::fromValue(primaryRefreshRateMin),
6962 Fps::fromValue(primaryRefreshRateMax)},
6963 {Fps::fromValue(appRequestRefreshRateMin),
6964 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006965 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006966
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006967 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006968 }
6969 });
6970
6971 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006972}
6973
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006974status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6975 ui::DisplayModeId* outDefaultMode,
6976 bool* outAllowGroupSwitching,
6977 float* outPrimaryRefreshRateMin,
6978 float* outPrimaryRefreshRateMax,
6979 float* outAppRequestRefreshRateMin,
6980 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006981 ATRACE_CALL();
6982
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006983 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006984 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006985 return BAD_VALUE;
6986 }
6987
6988 Mutex::Autolock lock(mStateLock);
6989 const auto display = getDisplayDeviceLocked(displayToken);
6990 if (!display) {
6991 return NAME_NOT_FOUND;
6992 }
6993
Ady Abraham3efa3942021-06-24 19:01:25 -07006994 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006995 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006996 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006997
6998 scheduler::RefreshRateConfigs::Policy policy =
6999 display->refreshRateConfigs().getDisplayManagerPolicy();
7000 *outDefaultMode = policy.defaultMode.value();
7001 *outAllowGroupSwitching = policy.allowGroupSwitching;
7002 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
7003 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
7004 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
7005 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
7006 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07007007}
7008
Vishnu Nairf9096652021-07-20 18:49:42 -07007009wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
7010 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07007011}
7012
Dominik Laskowski75848362019-11-11 17:57:20 -08007013void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007014 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07007015 if (!layer->isRemovedFromCurrentState()) {
7016 mScheduler->registerLayer(layer);
7017 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007018}
7019
7020void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
7021 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07007022 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07007023 if (!layer->isRemovedFromCurrentState()) {
7024 mScheduler->deregisterLayer(layer);
7025 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08007026 if (mTransactionTracing) {
7027 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08007028 }
Valerie Hauc5686802019-11-22 14:18:09 -08007029}
7030
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007031void SurfaceFlinger::onLayerUpdate() {
7032 scheduleCommit(FrameHint::kActive);
7033}
7034
Valerie Hauc5686802019-11-22 14:18:09 -08007035// WARNING: ONLY CALL THIS FROM LAYER DTOR
7036// Here we add children in the current state to offscreen layers and remove the
7037// layer itself from the offscreen layer list. Since
7038// this is the dtor, it is safe to access the current state. This keeps us
7039// from dangling children layers such that they are not reachable from the
7040// Drawing state nor the offscreen layer list
7041// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07007042void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08007043 for (auto& child : layer->getCurrentChildren()) {
7044 mOffscreenLayers.emplace(child.get());
7045 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007046 mOffscreenLayers.erase(layer);
7047}
7048
Robert Carr867be372021-06-29 17:36:02 -07007049void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
7050 mOffscreenLayers.erase(layer);
7051}
7052
Vishnu Nair08f6eae2019-11-26 14:01:39 -08007053status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
7054 float lightPosY, float lightPosZ,
7055 float lightRadius) {
7056 Mutex::Autolock _l(mStateLock);
7057 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
7058 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
7059 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
7060 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
7061 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
7062
7063 // these values are overridden when calculating the shadow settings for a layer.
7064 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
7065 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08007066 return NO_ERROR;
7067}
7068
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007069const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
7070 const {
7071 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
7072 // on the work to remove the table in that bug rather than adding more to
7073 // it.
7074 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007075 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
7076 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007077 };
7078 return genericLayerMetadataKeyMap;
7079}
7080
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007081status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7082 PhysicalDisplayId displayId = [&]() {
7083 Mutex::Autolock lock(mStateLock);
7084 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7085 }();
7086
7087 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7088 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7089 return NO_ERROR;
7090}
7091
Dominik Laskowski20134642020-04-20 22:36:44 -07007092void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007093 for (const auto& [ignored, display] : mDisplays) {
7094 if (display->isInternal()) {
7095 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007096 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007097 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007098}
7099
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007100status_t SurfaceFlinger::addTransactionTraceListener(
7101 const sp<gui::ITransactionTraceListener>& listener) {
7102 if (!listener) {
7103 return BAD_VALUE;
7104 }
7105
7106 mInterceptor->addTransactionTraceListener(listener);
7107
7108 return NO_ERROR;
7109}
7110
Huihong Luo02186fb2022-02-23 14:21:54 -08007111int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007112 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007113}
7114
Ady Abraham899dcdb2021-06-15 16:56:21 -07007115int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7116 std::chrono::nanoseconds presentLatency) {
7117 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7118 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007119 pipelineDepth++;
7120 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007121 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007122}
7123
Ady Abraham899dcdb2021-06-15 16:56:21 -07007124status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007125 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007126
7127 if (!getHwComposer().isHeadless()) {
7128 if (const auto display = getDefaultDisplayDevice()) {
7129 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007130 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007131 }
7132
7133 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007134 return NO_ERROR;
7135}
7136
rnleeed20fa42021-08-10 18:00:03 -07007137uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007138 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007139
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007140 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7141 refreshRate = *frameRateOverride;
7142 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007143 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007144 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007145 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007146 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007147
Ady Abraham899dcdb2021-06-15 16:56:21 -07007148 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7149}
7150
7151int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7152 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7153 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7154 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7155}
7156
Vishnu Nair286f4f92022-06-08 16:37:39 -07007157void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state, int64_t vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007158 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007159 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007160 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7161 return;
arthurhungdba591c2021-02-08 17:28:49 +08007162 }
7163
7164 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007165 bool addToRoot = state.addToRoot;
7166 if (state.initialParent != nullptr) {
7167 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007168 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007169 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007170 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007171 }
arthurhungdba591c2021-02-08 17:28:49 +08007172 }
7173
Garfield Tand712ad32021-10-27 13:44:22 -07007174 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007175 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007176 mCurrentState.layersSortedByZ.add(layer);
7177 } else if (parent == nullptr) {
7178 layer->onRemovedFromCurrentState();
7179 } else if (parent->isRemovedFromCurrentState()) {
7180 parent->addChild(layer);
7181 layer->onRemovedFromCurrentState();
7182 } else {
7183 parent->addChild(layer);
7184 }
7185
Ady Abraham1273ac12021-08-26 17:31:53 -07007186 layer->updateTransformHint(mActiveDisplayTransformHint);
Vishnu Nair286f4f92022-06-08 16:37:39 -07007187 if (mTransactionTracing) {
7188 mTransactionTracing->onLayerAddedToDrawingState(layer->getSequence(), vsyncId);
7189 }
Arthur Hung23e07502021-10-15 11:58:19 +00007190 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007191}
Ady Abraham562c2712021-05-07 15:10:42 -07007192
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007193void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007194 if (!mLumaSampling || !mRegionSamplingThread) {
7195 return;
7196 }
7197
Dominik Laskowski756b7892021-08-04 12:53:59 -07007198 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007199}
7200
Ady Abrahamed3290f2021-05-17 15:12:14 -07007201void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7202 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7203 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7204}
7205
7206void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7207 ATRACE_CALL();
7208
Ady Abrahamdb036a82021-07-16 14:18:34 -07007209 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7210 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7211 }
7212
Ady Abrahamed3290f2021-05-17 15:12:14 -07007213 if (!activeDisplay) {
7214 ALOGE("%s: activeDisplay is null", __func__);
7215 return;
7216 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007217 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007218 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007219 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007220 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007221 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007222 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007223 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007224
7225 // Update the kernel timer for the current active display, since the policy
7226 // for this display might have changed when it was not the active display.
7227 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007228}
7229
chaviw60c9d3e2021-06-04 12:52:17 -05007230status_t SurfaceFlinger::addWindowInfosListener(
7231 const sp<IWindowInfosListener>& windowInfosListener) const {
7232 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7233 return NO_ERROR;
7234}
7235
7236status_t SurfaceFlinger::removeWindowInfosListener(
7237 const sp<IWindowInfosListener>& windowInfosListener) const {
7238 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7239 return NO_ERROR;
7240}
7241
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007242std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7243 const BufferData& bufferData, const char* layerName) const {
7244 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7245 bool bufferSizeExceedsLimit = false;
7246 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7247 if (cacheIdChanged && bufferData.buffer != nullptr) {
7248 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7249 bufferData.buffer->getHeight());
7250 if (!bufferSizeExceedsLimit) {
7251 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7252 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7253 }
7254 } else if (cacheIdChanged) {
7255 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7256 } else if (bufferData.buffer != nullptr) {
7257 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7258 bufferData.buffer->getHeight());
7259 if (!bufferSizeExceedsLimit) {
7260 buffer = std::make_shared<
7261 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7262 renderengine::impl::ExternalTexture::
7263 Usage::READABLE);
7264 }
7265 }
7266 ALOGE_IF(bufferSizeExceedsLimit,
7267 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7268 "limit.",
7269 layerName);
7270 return buffer;
7271}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007272
Vishnu Nair286f4f92022-06-08 16:37:39 -07007273bool SurfaceFlinger::commitCreatedLayers(int64_t vsyncId) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007274 std::vector<LayerCreatedState> createdLayers;
7275 {
7276 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7277 createdLayers = std::move(mCreatedLayers);
7278 mCreatedLayers.clear();
7279 if (createdLayers.size() == 0) {
7280 return false;
7281 }
7282 }
7283
7284 Mutex::Autolock _l(mStateLock);
7285 for (const auto& createdLayer : createdLayers) {
Vishnu Nair286f4f92022-06-08 16:37:39 -07007286 handleLayerCreatedLocked(createdLayer, vsyncId);
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007287 }
7288 createdLayers.clear();
7289 mLayersAdded = true;
7290 return true;
7291}
Huihong Luof5029222021-12-16 14:33:46 -08007292
7293// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007294
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007295binder::Status SurfaceComposerAIDL::bootFinished() {
7296 status_t status = checkAccessPermission();
7297 if (status != OK) {
7298 return binderStatusFromStatusT(status);
7299 }
7300 mFlinger->bootFinished();
7301 return binder::Status::ok();
7302}
7303
7304binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7305 VsyncSource vsyncSource, EventRegistration eventRegistration,
7306 sp<IDisplayEventConnection>* outConnection) {
7307 sp<IDisplayEventConnection> conn =
7308 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration);
7309 if (conn == nullptr) {
7310 *outConnection = nullptr;
7311 return binderStatusFromStatusT(BAD_VALUE);
7312 } else {
7313 *outConnection = conn;
7314 return binder::Status::ok();
7315 }
7316}
7317
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007318binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
7319 const sp<Client> client = new Client(mFlinger);
7320 if (client->initCheck() == NO_ERROR) {
7321 *outClient = client;
7322 return binder::Status::ok();
7323 } else {
7324 *outClient = nullptr;
7325 return binderStatusFromStatusT(BAD_VALUE);
7326 }
7327}
7328
Huihong Luo07e72362022-02-14 14:26:04 -08007329binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7330 sp<IBinder>* outDisplay) {
7331 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007332 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007333 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007334 }
Huihong Luo37396db2022-02-15 10:43:00 -08007335 String8 displayName8 = String8::format("%s", displayName.c_str());
7336 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7337 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007338}
7339
7340binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7341 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007342 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007343 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007344 }
Huihong Luo37396db2022-02-15 10:43:00 -08007345 mFlinger->destroyDisplay(display);
7346 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007347}
7348
7349binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7350 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7351 std::vector<int64_t> displayIds;
7352 displayIds.reserve(physicalDisplayIds.size());
7353 for (auto item : physicalDisplayIds) {
7354 displayIds.push_back(static_cast<int64_t>(item.value));
7355 }
7356 *outDisplayIds = displayIds;
7357 return binder::Status::ok();
7358}
7359
7360binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7361 status_t status = checkAccessPermission();
7362 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007363 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007364 }
7365
7366 PhysicalDisplayId id;
7367 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7368 if (status == NO_ERROR) {
7369 *outDisplayId = id.value;
7370 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007371 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007372}
7373
7374binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7375 sp<IBinder>* outDisplay) {
7376 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7377 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7378 return binder::Status::ok();
7379}
7380
Huihong Luo37396db2022-02-15 10:43:00 -08007381binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7382 status_t status = checkAccessPermission();
7383 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007384 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007385 }
7386 mFlinger->setPowerMode(display, mode);
7387 return binder::Status::ok();
7388}
7389
Huihong Luo0a81aa32022-02-22 16:02:36 -08007390binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7391 std::vector<FrameEvent>* outSupported) {
7392 status_t status;
7393 if (!outSupported) {
7394 status = UNEXPECTED_NULL;
7395 } else {
7396 outSupported->clear();
7397 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7398 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007399 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007400}
7401
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007402binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7403 gui::DisplayStatInfo* outStatInfo) {
7404 DisplayStatInfo statInfo;
7405 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7406 if (status == NO_ERROR) {
7407 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7408 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7409 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007410 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007411}
7412
7413binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7414 gui::DisplayState* outState) {
7415 ui::DisplayState state;
7416 status_t status = mFlinger->getDisplayState(display, &state);
7417 if (status == NO_ERROR) {
7418 outState->layerStack = state.layerStack.id;
7419 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7420 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7421 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7422 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007423 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007424}
7425
Huihong Luoa79ddf42022-02-17 00:01:38 -08007426binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7427 gui::StaticDisplayInfo* outInfo) {
7428 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7429 ui::StaticDisplayInfo info;
7430 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7431 if (status == NO_ERROR) {
7432 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7433 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7434 outInfo->density = info.density;
7435 outInfo->secure = info.secure;
7436 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7437
7438 gui::DeviceProductInfo dinfo;
7439 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7440 dinfo.name = std::move(dpi->name);
7441 dinfo.manufacturerPnpId =
7442 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7443 dinfo.productId = dpi->productId;
Kriti Dang1de958d2022-05-30 15:26:58 +02007444 dinfo.relativeAddress =
7445 std::vector<uint8_t>(dpi->relativeAddress.begin(), dpi->relativeAddress.end());
Huihong Luoa79ddf42022-02-17 00:01:38 -08007446 if (const auto* model =
7447 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7448 gui::DeviceProductInfo::ModelYear modelYear;
7449 modelYear.year = model->year;
7450 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7451 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7452 &dpi->manufactureOrModelDate)) {
7453 gui::DeviceProductInfo::ManufactureYear date;
7454 date.modelYear.year = manufacture->year;
7455 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7456 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7457 &dpi->manufactureOrModelDate)) {
7458 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7459 date.manufactureYear.modelYear.year = manufacture->year;
7460 date.week = manufacture->week;
7461 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7462 }
7463
7464 outInfo->deviceProductInfo = dinfo;
7465 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007466 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007467}
7468
Huihong Luo38603fd2022-02-21 14:32:54 -08007469binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7470 gui::DynamicDisplayInfo* outInfo) {
7471 ui::DynamicDisplayInfo info;
7472 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7473 if (status == NO_ERROR) {
7474 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7475 outInfo->supportedDisplayModes.clear();
7476 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7477 for (const auto& mode : info.supportedDisplayModes) {
7478 gui::DisplayMode outMode;
7479 outMode.id = mode.id;
7480 outMode.resolution.width = mode.resolution.width;
7481 outMode.resolution.height = mode.resolution.height;
7482 outMode.xDpi = mode.xDpi;
7483 outMode.yDpi = mode.yDpi;
7484 outMode.refreshRate = mode.refreshRate;
7485 outMode.appVsyncOffset = mode.appVsyncOffset;
7486 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7487 outMode.presentationDeadline = mode.presentationDeadline;
7488 outMode.group = mode.group;
7489 outInfo->supportedDisplayModes.push_back(outMode);
7490 }
7491
7492 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7493
7494 outInfo->supportedColorModes.clear();
7495 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7496 for (const auto& cmode : info.supportedColorModes) {
7497 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7498 }
7499
7500 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7501
7502 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7503 hdrCapabilities.supportedHdrTypes.clear();
7504 hdrCapabilities.supportedHdrTypes.reserve(
7505 info.hdrCapabilities.getSupportedHdrTypes().size());
7506 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7507 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7508 }
7509 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7510 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7511 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7512
7513 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7514 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7515 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7516 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007517 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007518}
7519
Huihong Luoca3d9a42022-02-22 11:07:34 -08007520binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7521 gui::DisplayPrimaries* outPrimaries) {
7522 ui::DisplayPrimaries primaries;
7523 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7524 if (status == NO_ERROR) {
7525 outPrimaries->red.X = primaries.red.X;
7526 outPrimaries->red.Y = primaries.red.Y;
7527 outPrimaries->red.Z = primaries.red.Z;
7528
7529 outPrimaries->green.X = primaries.green.X;
7530 outPrimaries->green.Y = primaries.green.Y;
7531 outPrimaries->green.Z = primaries.green.Z;
7532
7533 outPrimaries->blue.X = primaries.blue.X;
7534 outPrimaries->blue.Y = primaries.blue.Y;
7535 outPrimaries->blue.Z = primaries.blue.Z;
7536
7537 outPrimaries->white.X = primaries.white.X;
7538 outPrimaries->white.Y = primaries.white.Y;
7539 outPrimaries->white.Z = primaries.white.Z;
7540 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007541 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007542}
7543
7544binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7545 status_t status = checkAccessPermission();
7546 if (status == OK) {
7547 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7548 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007549 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007550}
7551
7552binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7553 int displayModeId) {
7554 status_t status = checkAccessPermission();
7555 if (status == OK) {
7556 status = mFlinger->setBootDisplayMode(display,
7557 static_cast<ui::DisplayModeId>(displayModeId));
7558 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007559 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007560}
7561
Huihong Luo37396db2022-02-15 10:43:00 -08007562binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7563 status_t status = checkAccessPermission();
7564 if (status == OK) {
7565 status = mFlinger->clearBootDisplayMode(display);
7566 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007567 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007568}
7569
7570binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7571 status_t status = checkAccessPermission();
7572 if (status == OK) {
7573 status = mFlinger->getBootDisplayModeSupport(outMode);
7574 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007575 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007576}
7577
7578binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7579 status_t status = checkAccessPermission();
7580 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007581 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007582 }
7583 mFlinger->setAutoLowLatencyMode(display, on);
7584 return binder::Status::ok();
7585}
7586
7587binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7588 status_t status = checkAccessPermission();
7589 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007590 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007591 }
7592 mFlinger->setGameContentType(display, on);
7593 return binder::Status::ok();
7594}
7595
Huihong Luof5029222021-12-16 14:33:46 -08007596binder::Status SurfaceComposerAIDL::captureDisplay(
7597 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7598 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007599 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007600}
7601
7602binder::Status SurfaceComposerAIDL::captureDisplayById(
7603 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7604 status_t status;
7605 IPCThreadState* ipc = IPCThreadState::self();
7606 const int uid = ipc->getCallingUid();
7607 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7608 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7609 status = mFlinger->captureDisplay(*id, captureListener);
7610 } else {
7611 status = PERMISSION_DENIED;
7612 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007613 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007614}
7615
7616binder::Status SurfaceComposerAIDL::captureLayers(
7617 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7618 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007619 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007620}
7621
Huihong Luo4ed1c912022-02-22 14:30:01 -08007622binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7623 status_t status = checkAccessPermission();
7624 if (status == OK) {
7625 status = mFlinger->clearAnimationFrameStats();
7626 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007627 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007628}
7629
7630binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7631 status_t status = checkAccessPermission();
7632 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007633 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007634 }
7635
7636 FrameStats stats;
7637 status = mFlinger->getAnimationFrameStats(&stats);
7638 if (status == NO_ERROR) {
7639 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7640 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7641 for (const auto& t : stats.desiredPresentTimesNano) {
7642 outStats->desiredPresentTimesNano.push_back(t);
7643 }
7644 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7645 for (const auto& t : stats.actualPresentTimesNano) {
7646 outStats->actualPresentTimesNano.push_back(t);
7647 }
7648 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7649 for (const auto& t : stats.frameReadyTimesNano) {
7650 outStats->frameReadyTimesNano.push_back(t);
7651 }
7652 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007653 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007654}
7655
Huihong Luo05539a12022-02-23 10:29:40 -08007656binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7657 const std::vector<int32_t>& hdrTypes) {
7658 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7659 // permission dynamically. Don't use the permission cache for this check.
7660 status_t status = checkAccessPermission(false);
7661 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007662 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007663 }
7664
7665 std::vector<ui::Hdr> hdrTypesVector;
7666 for (int32_t i : hdrTypes) {
7667 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7668 }
7669 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007670 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007671}
7672
7673binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7674 status_t status;
7675 const int uid = IPCThreadState::self()->getCallingUid();
7676 if (uid != AID_SYSTEM) {
7677 status = PERMISSION_DENIED;
7678 } else {
7679 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7680 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007681 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007682}
7683
7684binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7685 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007686 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007687 }
7688
7689 status_t status = checkAccessPermission();
7690 if (status == OK) {
7691 status = mFlinger->enableVSyncInjections(enable);
7692 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007693 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007694}
7695
7696binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7697 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007698 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007699 }
7700
7701 status_t status = checkAccessPermission();
7702 if (status == OK) {
7703 status = mFlinger->injectVSync(when);
7704 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007705 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007706}
7707
7708binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7709 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007710 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007711 }
7712
7713 IPCThreadState* ipc = IPCThreadState::self();
7714 const int pid = ipc->getCallingPid();
7715 const int uid = ipc->getCallingUid();
7716 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7717 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007718 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007719 }
7720 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007721 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007722}
7723
7724binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7725 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007726 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007727}
7728
7729binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7730 ui::Dataspace dataspace;
7731 ui::PixelFormat pixelFormat;
7732 ui::Dataspace wideColorGamutDataspace;
7733 ui::PixelFormat wideColorGamutPixelFormat;
7734 status_t status =
7735 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7736 &wideColorGamutPixelFormat);
7737 if (status == NO_ERROR) {
7738 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7739 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7740 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7741 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7742 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007743 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007744}
7745
7746binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7747 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7748 status_t status = checkAccessPermission();
7749 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007750 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007751 }
7752
7753 ui::PixelFormat format;
7754 ui::Dataspace dataspace;
7755 uint8_t componentMask;
7756 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7757 &componentMask);
7758 if (status == NO_ERROR) {
7759 outAttrs->format = static_cast<int32_t>(format);
7760 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7761 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7762 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007763 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007764}
7765
7766binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7767 bool enable,
7768 int8_t componentMask,
7769 int64_t maxFrames) {
7770 status_t status = checkAccessPermission();
7771 if (status == OK) {
7772 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7773 static_cast<uint8_t>(componentMask),
7774 static_cast<uint64_t>(maxFrames));
7775 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007776 return binderStatusFromStatusT(status);
7777}
7778
7779binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7780 int64_t maxFrames, int64_t timestamp,
7781 gui::DisplayedFrameStats* outStats) {
7782 if (!outStats) {
7783 return binderStatusFromStatusT(BAD_VALUE);
7784 }
7785
7786 status_t status = checkAccessPermission();
7787 if (status != OK) {
7788 return binderStatusFromStatusT(status);
7789 }
7790
7791 DisplayedFrameStats stats;
7792 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7793 static_cast<uint64_t>(timestamp), &stats);
7794 if (status == NO_ERROR) {
7795 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7796 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7797 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7798 for (const auto& s : stats.component_0_sample) {
7799 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7800 }
7801 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7802 for (const auto& s : stats.component_1_sample) {
7803 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7804 }
7805 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7806 for (const auto& s : stats.component_2_sample) {
7807 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7808 }
7809 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7810 for (const auto& s : stats.component_3_sample) {
7811 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7812 }
7813 }
7814 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007815}
7816
7817binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7818 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007819 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007820}
7821
Huihong Luo37396db2022-02-15 10:43:00 -08007822binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7823 bool* outIsWideColorDisplay) {
7824 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007825 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007826}
7827
Huihong Luo02186fb2022-02-23 14:21:54 -08007828binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7829 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7830 const sp<gui::IRegionSamplingListener>& listener) {
7831 status_t status = checkReadFrameBufferPermission();
7832 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007833 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007834 }
7835 android::Rect rect;
7836 rect.left = samplingArea.left;
7837 rect.top = samplingArea.top;
7838 rect.right = samplingArea.right;
7839 rect.bottom = samplingArea.bottom;
7840 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007841 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007842}
7843
7844binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7845 const sp<gui::IRegionSamplingListener>& listener) {
7846 status_t status = checkReadFrameBufferPermission();
7847 if (status == OK) {
7848 status = mFlinger->removeRegionSamplingListener(listener);
7849 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007850 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007851}
7852
7853binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7854 const sp<gui::IFpsListener>& listener) {
7855 status_t status = checkReadFrameBufferPermission();
7856 if (status == OK) {
7857 status = mFlinger->addFpsListener(taskId, listener);
7858 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007859 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007860}
7861
7862binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7863 status_t status = checkReadFrameBufferPermission();
7864 if (status == OK) {
7865 status = mFlinger->removeFpsListener(listener);
7866 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007867 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007868}
7869
7870binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7871 const sp<gui::ITunnelModeEnabledListener>& listener) {
7872 status_t status = checkAccessPermission();
7873 if (status == OK) {
7874 status = mFlinger->addTunnelModeEnabledListener(listener);
7875 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007876 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007877}
7878
7879binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7880 const sp<gui::ITunnelModeEnabledListener>& listener) {
7881 status_t status = checkAccessPermission();
7882 if (status == OK) {
7883 status = mFlinger->removeTunnelModeEnabledListener(listener);
7884 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007885 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007886}
7887
7888binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7889 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7890 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7891 float appRequestRefreshRateMax) {
7892 status_t status = checkAccessPermission();
7893 if (status == OK) {
7894 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7895 static_cast<ui::DisplayModeId>(defaultMode),
7896 allowGroupSwitching, primaryRefreshRateMin,
7897 primaryRefreshRateMax,
7898 appRequestRefreshRateMin,
7899 appRequestRefreshRateMax);
7900 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007901 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007902}
7903
7904binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7905 gui::DisplayModeSpecs* outSpecs) {
7906 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007907 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007908 }
7909
7910 status_t status = checkAccessPermission();
7911 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007912 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007913 }
7914
7915 ui::DisplayModeId displayModeId;
7916 bool allowGroupSwitching;
7917 float primaryRefreshRateMin;
7918 float primaryRefreshRateMax;
7919 float appRequestRefreshRateMin;
7920 float appRequestRefreshRateMax;
7921 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7922 &allowGroupSwitching, &primaryRefreshRateMin,
7923 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7924 &appRequestRefreshRateMax);
7925 if (status == NO_ERROR) {
7926 outSpecs->defaultMode = displayModeId;
7927 outSpecs->allowGroupSwitching = allowGroupSwitching;
7928 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7929 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7930 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7931 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7932 }
7933
Huihong Luo3bdef862022-03-03 11:57:19 -08007934 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007935}
7936
Huihong Luo37396db2022-02-15 10:43:00 -08007937binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7938 bool* outSupport) {
7939 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007940 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007941}
7942
7943binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7944 const gui::DisplayBrightness& brightness) {
7945 status_t status = checkControlDisplayBrightnessPermission();
7946 if (status == OK) {
7947 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7948 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007949 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007950}
7951
7952binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7953 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7954 status_t status = checkControlDisplayBrightnessPermission();
7955 if (status == OK) {
7956 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7957 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007958 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007959}
7960
7961binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7962 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7963 status_t status = checkControlDisplayBrightnessPermission();
7964 if (status == OK) {
7965 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7966 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007967 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007968}
7969
7970binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7971 status_t status = checkAccessPermission();
7972 if (status == OK) {
7973 status = mFlinger->notifyPowerBoost(boostId);
7974 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007975 return binderStatusFromStatusT(status);
7976}
7977
7978binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7979 const gui::Color& spotColor,
7980 float lightPosY, float lightPosZ,
7981 float lightRadius) {
7982 status_t status = checkAccessPermission();
7983 if (status != OK) {
7984 return binderStatusFromStatusT(status);
7985 }
7986
7987 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7988 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7989 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7990 lightPosZ, lightRadius);
7991 return binderStatusFromStatusT(status);
7992}
7993
7994binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7995 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7996 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7997 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7998 if (status != NO_ERROR) {
7999 ALOGE("getDisplayDecorationSupport failed with error %d", status);
8000 return binderStatusFromStatusT(status);
8001 }
8002
8003 if (!support || !support.has_value()) {
8004 outSupport->reset();
8005 } else {
8006 outSupport->emplace();
8007 outSupport->value().format = static_cast<int32_t>(support->format);
8008 outSupport->value().alphaInterpretation =
8009 static_cast<int32_t>(support->alphaInterpretation);
8010 }
8011
8012 return binder::Status::ok();
8013}
8014
8015binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
8016 status_t status;
8017 const int c_uid = IPCThreadState::self()->getCallingUid();
8018 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
8019 status = mFlinger->setOverrideFrameRate(uid, frameRate);
8020 } else {
8021 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
8022 status = PERMISSION_DENIED;
8023 }
8024 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008025}
8026
Huihong Luo02186fb2022-02-23 14:21:54 -08008027binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
8028 const sp<gui::ITransactionTraceListener>& listener) {
8029 status_t status;
8030 IPCThreadState* ipc = IPCThreadState::self();
8031 const int uid = ipc->getCallingUid();
8032 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
8033 status = mFlinger->addTransactionTraceListener(listener);
8034 } else {
8035 status = PERMISSION_DENIED;
8036 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008037 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008038}
8039
8040binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
8041 *outPriority = mFlinger->getGpuContextPriority();
8042 return binder::Status::ok();
8043}
8044
8045binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
8046 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08008047 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008048}
8049
8050binder::Status SurfaceComposerAIDL::addWindowInfosListener(
8051 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8052 status_t status;
8053 const int uid = IPCThreadState::self()->getCallingUid();
8054 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8055 status = mFlinger->addWindowInfosListener(windowInfosListener);
8056 } else {
8057 status = PERMISSION_DENIED;
8058 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008059 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008060}
8061
8062binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
8063 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8064 status_t status;
8065 const int uid = IPCThreadState::self()->getCallingUid();
8066 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8067 status = mFlinger->removeWindowInfosListener(windowInfosListener);
8068 } else {
8069 status = PERMISSION_DENIED;
8070 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008071 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008072}
8073
Huihong Luo07e72362022-02-14 14:26:04 -08008074status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
8075 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
8076 IPCThreadState* ipc = IPCThreadState::self();
8077 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
8078 ipc->getCallingUid());
8079 return PERMISSION_DENIED;
8080 }
8081 return OK;
8082}
8083
Huihong Luo37396db2022-02-15 10:43:00 -08008084status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
8085 IPCThreadState* ipc = IPCThreadState::self();
8086 const int pid = ipc->getCallingPid();
8087 const int uid = ipc->getCallingUid();
8088 if ((uid != AID_GRAPHICS) &&
8089 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
8090 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
8091 return PERMISSION_DENIED;
8092 }
8093 return OK;
8094}
8095
Huihong Luo02186fb2022-02-23 14:21:54 -08008096status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
8097 IPCThreadState* ipc = IPCThreadState::self();
8098 const int pid = ipc->getCallingPid();
8099 const int uid = ipc->getCallingUid();
8100 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
8101 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
8102 return PERMISSION_DENIED;
8103 }
8104 return OK;
8105}
8106
Dominik Laskowski9dab3432019-03-27 13:21:10 -07008107} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07008108
Mathias Agopian3f844832013-08-07 21:24:32 -07008109#if defined(__gl_h_)
8110#error "don't include gl/gl.h in this file"
8111#endif
8112
8113#if defined(__gl2_h_)
8114#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008115#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008116
8117// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008118#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"