blob: 82d8580a9b354fb17bbe5ad0b7772565fd8a34b0 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020#pragma clang diagnostic ignored "-Wextra"
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080021
Alec Mourie7d1d4a2019-02-05 01:13:46 +000022//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080023#define ATRACE_TAG ATRACE_TAG_GRAPHICS
24
Alec Mouri5f487d42020-02-06 09:26:19 -080025#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080026
Dominik Laskowski298b08e2022-02-15 13:45:02 -080027#include <android-base/parseint.h>
Ana Krulecb9afd792020-06-11 13:16:15 -070028#include <android-base/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080029#include <android-base/stringprintf.h>
30#include <android-base/strings.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080031#include <android/configuration.h>
Huihong Luo6fac5232021-11-22 16:05:23 -080032#include <android/gui/IDisplayEventConnection.h>
Huihong Luoa79ddf42022-02-17 00:01:38 -080033#include <android/gui/StaticDisplayInfo.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080034#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
35#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
36#include <android/hardware/configstore/1.1/types.h>
Lais Andrade3a6e47d2020-04-02 11:20:16 +010037#include <android/hardware/power/Boost.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080038#include <android/native_window.h>
Chris Ye0783e992020-06-02 21:34:49 -070039#include <android/os/IInputFlinger.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070040#include <binder/IPCThreadState.h>
41#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070042#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070043#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080044#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070045#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070046#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070047#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080048#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080049#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070050#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070051#include <compositionengine/impl/OutputCompositionState.h>
John Reckdb1a16b2021-07-09 13:05:52 -040052#include <compositionengine/impl/OutputLayerCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080053#include <configstore/Utils.h>
54#include <cutils/compiler.h>
55#include <cutils/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080056#include <ftl/fake_guard.h>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080057#include <ftl/future.h>
Dominik Laskowski9f410f02022-01-08 16:22:46 -080058#include <ftl/small_map.h>
Huihong Luo3bdef862022-03-03 11:57:19 -080059#include <gui/AidlStatusUtil.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070060#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070061#include <gui/DebugEGLImageTracker.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080062#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080063#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080064#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080065#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080066#include <gui/Surface.h>
rnlee60f46b52021-05-21 15:14:07 -070067#include <gui/TraceUtils.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000068#include <hidl/ServiceManagement.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080069#include <layerproto/LayerProtoParser.h>
70#include <log/log.h>
71#include <private/android_filesystem_config.h>
72#include <private/gui/SyncFeatures.h>
Wei Wang976a6452021-06-11 15:26:00 -070073#include <processgroup/processgroup.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070074#include <renderengine/RenderEngine.h>
Vishnu Nairdbbe3852022-01-12 20:22:11 -080075#include <renderengine/impl/ExternalTexture.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080076#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <ui/ColorSpace.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070078#include <ui/DataspaceUtils.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070079#include <ui/DebugUtils.h>
Marin Shalamanov045b7002021-01-07 16:56:24 +010080#include <ui/DisplayId.h>
Marin Shalamanova7fe3042021-01-29 21:02:08 +010081#include <ui/DisplayMode.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070082#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080083#include <ui/DisplayState.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010084#include <ui/DynamicDisplayInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070085#include <ui/GraphicBufferAllocator.h>
86#include <ui/PixelFormat.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010087#include <ui/StaticDisplayInfo.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070089#include <utils/String16.h>
90#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070091#include <utils/Timers.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070092#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093
Alec Mouri5f487d42020-02-06 09:26:19 -080094#include <algorithm>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080095#include <cerrno>
Alec Mouri5f487d42020-02-06 09:26:19 -080096#include <cinttypes>
97#include <cmath>
98#include <cstdint>
99#include <functional>
Xiang Wang839fe5b2022-04-04 17:39:38 +0000100#include <memory>
Alec Mouri5f487d42020-02-06 09:26:19 -0800101#include <mutex>
102#include <optional>
Michael Wright44753b12020-07-08 13:48:11 +0100103#include <type_traits>
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105
Alec Mouriff793872022-01-13 17:45:06 -0800106#include <ui/DisplayIdentification.h>
Vishnu Nair03ccbd62021-12-01 17:21:16 -0800107#include "BackgroundExecutor.h"
Robert Carr578038f2018-03-09 12:25:24 -0800108#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -0700109#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -0700110#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200111#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200112#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800113#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800114#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700115#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700116#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700117#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100118#include "DisplayHardware/Hal.h"
Xiang Wang839fe5b2022-04-04 17:39:38 +0000119#include "DisplayHardware/PowerAdvisor.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700120#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200121#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800122#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700123#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700124#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800125#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700126#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700127#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400128#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800129#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500130#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200131#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800132#include "LayerVector.h"
133#include "MonitoredProducer.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800134#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800135#include "NativeWindowSurface.h"
136#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700137#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700138#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700139#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700140#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700141#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700142#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700143#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800144#include "StartPropertySetThread.h"
145#include "SurfaceFlingerProperties.h"
146#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800147#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200148#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500149#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800150
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500151#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500152#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
Alec Mourifcedb9c2022-04-11 20:02:17 +0000153#include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500154
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700155#undef NO_THREAD_SAFETY_ANALYSIS
156#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800157 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500158
Tianhao Yao67dd7122022-02-22 17:48:33 +0000159// To enable layer borders in the system, change the below flag to true.
160#undef DOES_CONTAIN_BORDER
161#define DOES_CONTAIN_BORDER false
162
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700164
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700165using namespace std::string_literals;
166
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800167using namespace hardware::configstore;
168using namespace hardware::configstore::V1_0;
169using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800170
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800171using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
172using aidl::android::hardware::graphics::composer3::Capability;
173using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800174using CompositionStrategyPredictionState = android::compositionengine::impl::
175 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800176
Yiwei Zhang5434a782018-12-05 18:06:32 -0800177using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700178using gui::DisplayInfo;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800179using gui::GameMode;
Huihong Luo6fac5232021-11-22 16:05:23 -0800180using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500181using gui::IWindowInfosListener;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800182using gui::LayerMetadata;
chaviw98318de2021-05-19 16:45:23 -0500183using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800184using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700185using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700186using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800187using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700188using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900189
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800190using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
191
Peiyong Line9d809e2020-04-14 13:10:48 -0700192namespace hal = android::hardware::graphics::composer::hal;
193
Steven Thomasb02664d2017-07-26 18:48:28 -0700194namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700195
196#pragma clang diagnostic push
197#pragma clang diagnostic error "-Wswitch-enum"
198
199bool isWideColorMode(const ColorMode colorMode) {
200 switch (colorMode) {
201 case ColorMode::DISPLAY_P3:
202 case ColorMode::ADOBE_RGB:
203 case ColorMode::DCI_P3:
204 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700205 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700206 case ColorMode::BT2100_PQ:
207 case ColorMode::BT2100_HLG:
208 return true;
209 case ColorMode::NATIVE:
210 case ColorMode::STANDARD_BT601_625:
211 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
212 case ColorMode::STANDARD_BT601_525:
213 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
214 case ColorMode::STANDARD_BT709:
215 case ColorMode::SRGB:
216 return false;
217 }
218 return false;
219}
220
221#pragma clang diagnostic pop
222
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100223// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700224constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800225
226float getDensityFromProperty(const char* property, bool required) {
227 char value[PROPERTY_VALUE_MAX];
228 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
229 if (!density && required) {
230 ALOGE("%s must be defined as a build property", property);
231 return FALLBACK_DENSITY;
232 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700233 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800234}
235
Peiyong Lin9d846a52018-11-05 13:18:20 -0800236// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
237bool validateCompositionDataspace(Dataspace dataspace) {
238 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
239}
240
ramindani32cf0602022-03-02 02:30:29 +0000241std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700242 const auto displayIdleTimerMsKey = [displayId] {
243 std::stringstream ss;
244 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
245 return ss.str();
246 }();
247
ramindani32cf0602022-03-02 02:30:29 +0000248 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
249 if (displayIdleTimerMs > 0) {
250 return std::chrono::milliseconds(displayIdleTimerMs);
251 }
252
253 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
254 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
255 return std::chrono::milliseconds(millis);
256}
257
258bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700259 const auto displaySupportKernelIdleTimerKey = [displayId] {
260 std::stringstream ss;
261 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
262 return ss.str();
263 }();
264
Ady Abraham6d885932021-09-03 18:05:48 -0700265 const auto displaySupportKernelIdleTimer =
266 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000267 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700268}
269
Steven Thomasb02664d2017-07-26 18:48:28 -0700270} // namespace anonymous
271
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272// ---------------------------------------------------------------------------
273
Mathias Agopian99b49842011-06-27 16:05:52 -0700274const String16 sHardwareTest("android.permission.HARDWARE_TEST");
275const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800276const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700277const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400278const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700279const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500280const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000281const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500282
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800283const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700284
285// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700286int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700287bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800288bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800289int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100290uint32_t SurfaceFlinger::maxGraphicsWidth;
291uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600292bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700293bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700294Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
295ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
296Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
297ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000298LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700299
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800300std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
301 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800302 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700303 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800304 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700305 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800306 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700307 return std::string("Enhanced");
308 default:
309 return std::string("Unknown ") +
310 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800311 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800312}
313
Hongwei Wang46213ea2020-12-04 17:17:31 -0800314bool callingThreadHasRotateSurfaceFlingerAccess() {
315 IPCThreadState* ipc = IPCThreadState::self();
316 const int pid = ipc->getCallingPid();
317 const int uid = ipc->getCallingUid();
318 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
319 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
320}
321
Leon Scroggins9a20f722021-12-28 14:43:12 +0000322bool callingThreadHasInternalSystemWindowAccess() {
323 IPCThreadState* ipc = IPCThreadState::self();
324 const int pid = ipc->getCallingPid();
325 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500326 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
327 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000328}
329
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700330SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
331 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800332 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000333 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700334 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800335 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800336 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700337 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700338 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700339 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800340 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700341 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000342 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Dominik Laskowski91f635e2022-01-08 05:46:09 -0800343 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make(*this)) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700344 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700345}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800346
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700347SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800348 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800349
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900350 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900352 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700353
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900354 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700355
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900356 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800357
Brian Lindahla13f2d52020-03-05 11:54:17 +0100358 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
359 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
360
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900361 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900362 mDefaultCompositionDataspace =
363 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700364 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
365 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900366 defaultCompositionDataspace = mDefaultCompositionDataspace;
367 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
368 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
369 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
370 wideColorGamutCompositionPixelFormat =
371 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700372
Yichi Chenda901bf2019-06-28 14:58:27 +0800373 mColorSpaceAgnosticDataspace =
374 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
375
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700376 mLayerCachingEnabled = [] {
377 const bool enable =
378 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
379 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
380 }();
381
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900382 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800383
Sundong Ahn85131bd2019-02-18 15:51:53 +0900384 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800385
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800386 // debugging stuff...
387 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700388
Mathias Agopianb4b17302013-03-20 18:36:41 -0700389 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700390 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700391
Alec Mouri5f487d42020-02-06 09:26:19 -0800392 property_get("ro.build.type", value, "user");
393 mIsUserBuild = strcmp(value, "user") == 0;
394
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700395 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000396
397 // DDMS debugging deprecated (b/120782499)
398 property_get("debug.sf.ddms", value, "0");
399 int debugDdms = atoi(value);
400 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700401
Ady Abrahamadb9a992019-09-19 21:21:55 +0000402 property_get("debug.sf.enable_gl_backpressure", value, "0");
403 mPropagateBackpressureClientComposition = atoi(value);
404 ALOGI_IF(mPropagateBackpressureClientComposition,
405 "Enabling backpressure propagation for Client Composition");
406
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800407 property_get("ro.surface_flinger.supports_background_blur", value, "0");
408 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700409 mSupportsBlur = supportsBlurs;
410 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800411 property_get("ro.sf.blurs_are_expensive", value, "0");
412 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800413
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700414 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700415 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
416 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800417 mGraphicBufferProducerListSizeLogThreshold =
418 std::max(static_cast<int>(0.95 *
419 static_cast<double>(mMaxGraphicBufferProducerListSize)),
420 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700421
Dan Stozaec460082018-12-17 15:35:09 -0800422 property_get("debug.sf.luma_sampling", value, "1");
423 mLumaSampling = atoi(value);
424
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800425 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800426 mDisableClientCompositionCache = atoi(value);
427
Vishnu Nair3539d812022-02-26 09:20:17 -0800428 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800429 mPredictCompositionStrategy = atoi(value);
430
Alec Mouridda07d92022-04-25 22:39:25 +0000431 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
432 mTreat170mAsSrgb = atoi(value);
433
Romain Guy11d63f42017-07-20 12:47:14 -0700434 // We should be reading 'persist.sys.sf.color_saturation' here
435 // but since /data may be encrypted, we need to wait until after vold
436 // comes online to attempt to read the property. The property is
437 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800438
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700439 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800440 // Without the override SurfaceFlinger cannot connect to HIDL
441 // services that are not listed in the manifests. Considered
442 // deriving the setting from the set service name, but it
443 // would be brittle if the name that's not 'default' is used
444 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700445 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000446 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800447 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800448
Ady Abraham29d0da32020-07-16 18:39:33 -0700449 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400450
Dominik Laskowski46471e62022-01-14 15:34:03 -0800451 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
452 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800453 }
John Reck49d9ad32022-02-23 19:03:31 -0500454
455 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
ramindani4d48f902021-09-20 21:07:45 +0000456}
457
458LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
459 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
460 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000461 }
Ady Abraham9dada822022-02-03 10:26:59 -0800462
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000463 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800464 return LatchUnsignaledConfig::AutoSingleLayer;
465 }
466
467 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800468}
469
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700470SurfaceFlinger::~SurfaceFlinger() = default;
471
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700472void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800473 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700474 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800475
Dominik Laskowski756b7892021-08-04 12:53:59 -0700476 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000477 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800478
Andy McFadden13a082e2012-08-24 10:16:42 -0700479 // restore initial conditions (default device unblank, etc)
480 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800481
482 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700483 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800484}
485
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700486void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700487 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800488}
489
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700490sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700491 // onTransact already checks for some permissions, but adding an additional check here.
492 // This is to ensure that only system and graphics can request to create a secure
493 // display. Secure displays can show secure content so we add an additional restriction on it.
494 const int uid = IPCThreadState::self()->getCallingUid();
495 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
496 ALOGE("Only privileged processes can create a secure display");
497 return nullptr;
498 }
499
Mathias Agopiane57f2922012-08-09 16:29:12 -0700500 class DisplayToken : public BBinder {
501 sp<SurfaceFlinger> flinger;
502 virtual ~DisplayToken() {
503 // no more references, this display must be terminated
504 Mutex::Autolock _l(flinger->mStateLock);
505 flinger->mCurrentState.displays.removeItem(this);
506 flinger->setTransactionFlags(eDisplayTransactionNeeded);
507 }
508 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700509 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510 : flinger(flinger) {
511 }
512 };
513
514 sp<BBinder> token = new DisplayToken(this);
515
516 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700517 // Display ID is assigned when virtual display is allocated by HWC.
518 DisplayDeviceState state;
519 state.isSecure = secure;
520 state.displayName = displayName;
521 mCurrentState.displays.add(token, state);
522 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523 return token;
524}
525
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700526void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700527 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700528
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700529 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700530 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800531 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700532 return;
533 }
534
Dominik Laskowski075d3172018-05-24 15:50:06 -0700535 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700536 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800537 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700538 return;
539 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700540 mInterceptor->saveDisplayDeletion(state.sequenceId);
541 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700542 setTransactionFlags(eDisplayTransactionNeeded);
543}
544
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800545void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
546 auto& generator = mVirtualDisplayIdGenerators.hal;
547 if (!generator && enable) {
548 ALOGI("Enabling HAL virtual displays");
549 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
550 } else if (generator && !enable) {
551 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
552 generator.reset();
553 }
554}
555
Dominik Laskowski263eec42021-07-21 23:13:24 -0700556VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
557 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800558 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
559 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700560 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800561 return *id;
562 }
563
564 generator->releaseId(*id);
565 } else {
566 ALOGW("%s: Exhausted HAL virtual displays", __func__);
567 }
568
569 ALOGW("%s: Falling back to GPU virtual display", __func__);
570 }
571
572 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
573 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
574 return *id;
575}
576
577void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
578 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
579 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
580 generator->releaseId(*id);
581 }
582 return;
583 }
584
585 const auto id = GpuVirtualDisplayId::tryCast(displayId);
586 LOG_ALWAYS_FATAL_IF(!id);
587 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
588}
589
Ady Abrahamed3290f2021-05-17 15:12:14 -0700590std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800591 std::vector<PhysicalDisplayId> displayIds;
592 displayIds.reserve(mPhysicalDisplayTokens.size());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700593
Dominik Laskowski3c363242022-04-07 10:44:12 -0700594 const auto defaultDisplayId = getDefaultDisplayDeviceLocked()->getPhysicalId();
Ady Abraham2a0066d2021-07-15 20:16:58 -0700595 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800596
597 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700598 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200599 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800600 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700601 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700602
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800603 return displayIds;
604}
605
Vishnu Nair8c8db542021-09-17 19:51:45 -0700606status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
607 Mutex::Autolock lock(mStateLock);
Dominik Laskowski3c363242022-04-07 10:44:12 -0700608 *id = getPrimaryDisplayIdLocked();
Vishnu Nair8c8db542021-09-17 19:51:45 -0700609 return NO_ERROR;
610}
611
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800612sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
613 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200614 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700615}
616
Ady Abraham37965d42018-11-01 13:43:32 -0700617status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
618 if (!outGetColorManagement) {
619 return BAD_VALUE;
620 }
621 *outGetColorManagement = useColorManagement;
622 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700623}
624
Lloyd Pique441d5042018-10-18 16:49:51 -0700625HWComposer& SurfaceFlinger::getHwComposer() const {
626 return mCompositionEngine->getHwComposer();
627}
628
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700629renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
630 return mCompositionEngine->getRenderEngine();
631}
632
Lloyd Pique70d91362018-10-18 16:02:55 -0700633compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
634 return *mCompositionEngine.get();
635}
636
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100637void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700638 if (mBootFinished == true) {
639 ALOGE("Extra call to bootFinished");
640 return;
641 }
642 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700643 if (mStartPropertySetThread->join() != NO_ERROR) {
644 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800645 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700646
647 if (mRenderEnginePrimeCacheFuture.valid()) {
648 mRenderEnginePrimeCacheFuture.get();
649 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800650 const nsecs_t now = systemTime();
651 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000652 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700653
Mikael Pessa90092f42019-08-26 17:22:04 -0700654 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700655 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700656 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700657
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700658 // wait patiently for the window manager death
659 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700660 mWindowManager = defaultServiceManager()->getService(name);
661 if (mWindowManager != 0) {
662 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700663 }
664
665 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700666 // formerly we would just kill the process, but we now ask it to exit so it
667 // can choose where to stop the animation.
668 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700669
670 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
671 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
672 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700673
Denis Hsue70cc6c2020-06-17 10:17:30 +0800674 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
675
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000676 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800677 if (input == nullptr) {
678 ALOGE("Failed to link to input service");
679 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700680 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800681 }
682
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800683 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000684 mPowerAdvisor->onBootFinished();
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000685 const bool powerHintEnabled = mFlagManager.use_adpf_cpu_hint();
686 mPowerAdvisor->enablePowerHint(powerHintEnabled);
687 const bool powerHintUsed = mPowerAdvisor->usePowerHintSession();
688 ALOGD("Power hint is %s",
689 powerHintUsed ? "supported" : (powerHintEnabled ? "unsupported" : "disabled"));
690 if (powerHintUsed) {
Xiang Wang76236e12022-03-22 17:25:30 +0000691 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
692 std::vector<int32_t> tidList;
693 tidList.emplace_back(gettid());
694 if (renderEngineTid.has_value()) {
695 tidList.emplace_back(*renderEngineTid);
696 }
Xiang Wang839fe5b2022-04-04 17:39:38 +0000697 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000698 ALOGW("Cannot start power hint session");
699 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000700 }
701
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800702 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800703
Ady Abraham8a82ba62020-01-17 12:43:17 -0800704 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800705 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800706 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800707 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800708}
709
Dan Stoza436ccf32018-06-21 12:10:12 -0700710uint32_t SurfaceFlinger::getNewTexture() {
711 {
712 std::lock_guard lock(mTexturePoolMutex);
713 if (!mTexturePool.empty()) {
714 uint32_t name = mTexturePool.back();
715 mTexturePool.pop_back();
716 ATRACE_INT("TexturePoolSize", mTexturePool.size());
717 return name;
718 }
719
720 // The pool was too small, so increase it for the future
721 ++mTexturePoolSize;
722 }
723
724 // The pool was empty, so we need to get a new texture name directly using a
725 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700726 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700727 uint32_t name = 0;
728 getRenderEngine().genTextures(1, &name);
729 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700730 };
731 if (std::this_thread::get_id() == mMainThreadId) {
732 return genTextures();
733 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700734 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700735 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700736}
737
Mathias Agopian3f844832013-08-07 21:24:32 -0700738void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700739 std::lock_guard lock(mTexturePoolMutex);
740 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
741 // to actually delete this or not based on mTexturePoolSize
742 mTexturePool.push_back(texture);
743 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700744}
745
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500746static std::optional<renderengine::RenderEngine::RenderEngineType>
747chooseRenderEngineTypeViaSysProp() {
748 char prop[PROPERTY_VALUE_MAX];
749 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
750
751 if (strcmp(prop, "gles") == 0) {
752 return renderengine::RenderEngine::RenderEngineType::GLES;
753 } else if (strcmp(prop, "threaded") == 0) {
754 return renderengine::RenderEngine::RenderEngineType::THREADED;
755 } else if (strcmp(prop, "skiagl") == 0) {
756 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
757 } else if (strcmp(prop, "skiaglthreaded") == 0) {
758 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
759 } else {
760 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
761 return {};
762 }
763}
764
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765// Do not call property_set on main thread which will be blocked by init
766// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700767void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700768 ALOGI( "SurfaceFlinger's main thread ready to run. "
769 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700770 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800771
Steven Thomasb02664d2017-07-26 18:48:28 -0700772 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700773 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800774 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500775 auto builder = renderengine::RenderEngineCreationArgs::Builder()
776 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
777 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
778 .setUseColorManagerment(useColorManagement)
779 .setEnableProtectedContext(enable_protected_contents(false))
780 .setPrecacheToneMapperShaderOnly(false)
781 .setSupportsBackgroundBlur(mSupportsBlur)
782 .setContextPriority(
783 useContextPriority
784 ? renderengine::RenderEngine::ContextPriority::REALTIME
785 : renderengine::RenderEngine::ContextPriority::MEDIUM);
786 if (auto type = chooseRenderEngineTypeViaSysProp()) {
787 builder.setRenderEngineType(type.value());
788 }
789 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700790 mMaxRenderTargetSize =
791 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700792
793 // Set SF main policy after initializing RenderEngine which has its own policy.
794 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
795 ALOGW("Failed to set main task profile");
796 }
797
Alec Mourie4034bb2019-11-19 12:45:54 -0800798 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700799 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800800 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000801 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800802
Ady Abraham9dada822022-02-03 10:26:59 -0800803 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
804
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800805 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
806 enableHalVirtualDisplays(true);
807 }
808
Lloyd Piqueba04e622017-12-14 17:11:26 -0800809 // Process any initial hotplug and resulting display changes.
810 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700811 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700812 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200813 const auto displayId = display->getPhysicalId();
814 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700815 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800816
Mathias Agopian92a979a2012-08-02 18:32:23 -0700817 // initialize our drawing state
818 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700819
Andy McFadden13a082e2012-08-24 10:16:42 -0700820 // set initial conditions (e.g. unblank default device)
821 initializeDisplays();
822
Xiang Wang839fe5b2022-04-04 17:39:38 +0000823 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700824
Steven Thomas137d4bc2019-07-25 16:55:14 -0700825 char primeShaderCache[PROPERTY_VALUE_MAX];
826 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
827 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700828 if (setSchedFifo(false) != NO_ERROR) {
829 ALOGW("Can't set SCHED_OTHER for primeCache");
830 }
831
832 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
833
834 if (setSchedFifo(true) != NO_ERROR) {
835 ALOGW("Can't set SCHED_OTHER for primeCache");
836 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700837 }
Dan Stoza4e637772016-07-28 13:31:51 -0700838
Ady Abrahamed3290f2021-05-17 15:12:14 -0700839 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400840
Wei Wangf9b05ee2017-07-19 20:59:39 -0700841 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700842
843 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800844 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700845 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700846
847 if (mStartPropertySetThread->Start() != NO_ERROR) {
848 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800849 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800850
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700852}
853
Romain Guy11d63f42017-07-20 12:47:14 -0700854void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700855 Mutex::Autolock _l(mStateLock);
856
Romain Guy11d63f42017-07-20 12:47:14 -0700857 char value[PROPERTY_VALUE_MAX];
858
859 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800860 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700861 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800862 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100863
864 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700865 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800866
867 property_get("persist.sys.sf.color_mode", value, "0");
868 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700869}
870
Mathias Agopiana67e4182012-06-19 17:26:12 -0700871void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800872 // Start boot animation service by setting a property mailbox
873 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700874 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800875 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700876 if (mStartPropertySetThread->join() != NO_ERROR) {
877 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800878 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700879}
880
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800881// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800882
Brian Anderson6b376712017-04-04 10:51:39 -0700883status_t SurfaceFlinger::getSupportedFrameTimestamps(
884 std::vector<FrameEvent>* outSupported) const {
885 *outSupported = {
886 FrameEvent::REQUESTED_PRESENT,
887 FrameEvent::ACQUIRE,
888 FrameEvent::LATCH,
889 FrameEvent::FIRST_REFRESH_START,
890 FrameEvent::LAST_REFRESH_START,
891 FrameEvent::GPU_COMPOSITION_DONE,
892 FrameEvent::DEQUEUE_READY,
893 FrameEvent::RELEASE,
894 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800895
896 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
897
Ady Abrahamde549d42022-01-26 19:19:17 -0800898 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700899 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
900 }
901 return NO_ERROR;
902}
903
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800904status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
905 if (!displayToken || !state) {
906 return BAD_VALUE;
907 }
908
909 Mutex::Autolock lock(mStateLock);
910
911 const auto display = getDisplayDeviceLocked(displayToken);
912 if (!display) {
913 return NAME_NOT_FOUND;
914 }
915
916 state->layerStack = display->getLayerStack();
917 state->orientation = display->getOrientation();
918
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200919 const Rect layerStackRect = display->getLayerStackSpaceRect();
920 state->layerStackSpaceRect =
921 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800922
923 return NO_ERROR;
924}
925
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100926status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
927 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800928 if (!displayToken || !info) {
929 return BAD_VALUE;
930 }
931
932 Mutex::Autolock lock(mStateLock);
933
934 const auto display = getDisplayDeviceLocked(displayToken);
935 if (!display) {
936 return NAME_NOT_FOUND;
937 }
938
Dominik Laskowski55c85402020-01-21 16:25:47 -0800939 if (const auto connectionType = display->getConnectionType())
940 info->connectionType = *connectionType;
941 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800942 return INVALID_OPERATION;
943 }
944
945 if (mEmulatedDisplayDensity) {
946 info->density = mEmulatedDisplayDensity;
947 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100948 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800949 ? mInternalDisplayDensity
950 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800951 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700952 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800953
954 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200955 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000956 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800957
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800958 return NO_ERROR;
959}
960
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100961status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
962 ui::DynamicDisplayInfo* info) {
963 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700964 return BAD_VALUE;
965 }
966
Dominik Laskowski22488f62019-03-28 09:53:04 -0700967 Mutex::Autolock lock(mStateLock);
968
Marin Shalamanov5801c942020-12-17 17:00:13 +0100969 const auto display = getDisplayDeviceLocked(displayToken);
970 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700971 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700972 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700973
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700974 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
975 if (!displayId) {
976 return INVALID_OPERATION;
977 }
978
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800979 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700980
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100981 const auto& supportedModes = display->getSupportedModes();
982 info->supportedDisplayModes.clear();
983 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800984
985 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100986 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800987 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700988
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800989 auto [width, height] = mode->getResolution();
990 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700991
ramindani06e518e2022-03-14 18:47:53 +0000992 if (const auto physicalOrientation = display->getPhysicalOrientation();
993 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800994 std::swap(width, height);
995 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700996 }
997
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100998 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800999
Huan Songf7eeb102022-03-28 11:02:38 -07001000 outMode.xDpi = xDpi;
1001 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001002
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001003 const nsecs_t period = mode->getVsyncPeriod();
1004 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001005
Ady Abraham8287e852020-08-12 14:44:58 -07001006 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001007 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001008 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1009 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1010 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001011
Andy McFadden91b2ca82014-06-13 14:04:23 -07001012 // This is how far in advance a buffer must be queued for
1013 // presentation at a given time. If you want a buffer to appear
1014 // on the screen at time N, you must submit the buffer before
1015 // (N - presentationDeadline).
1016 //
1017 // Normally it's one full refresh period (to give SF a chance to
1018 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001019 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001020 // composer or panel must be accounted for here.
1021 //
1022 // We add an additional 1ms to allow for processing time and
1023 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001024 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001025
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001026 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001027 }
1028
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001029 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001030 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001031 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001032
Marin Shalamanovb173f752021-02-16 19:38:36 +01001033 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001034 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001035 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001036 info->gameContentTypeSupported =
1037 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001038
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001039 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001040
1041 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001042 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1043 if (const auto modeId = display->translateModeId(*hwcId)) {
1044 info->preferredBootDisplayMode = modeId->value();
1045 }
1046 }
1047 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001048
Dan Stoza7f7da322014-05-02 15:26:25 -07001049 return NO_ERROR;
1050}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001051
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001052status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
1053 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001054 return BAD_VALUE;
1055 }
1056
Ady Abrahame90dd522020-12-29 12:08:45 -08001057 *stats = mScheduler->getDisplayStatInfo(systemTime());
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001058 return NO_ERROR;
1059}
1060
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001061void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001062 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001063
1064 if (!info.mode) {
1065 ALOGW("requested display mode is null");
1066 return;
1067 }
1068 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001069 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001070 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001071 return;
1072 }
1073
Ady Abraham690f4612021-07-01 23:24:03 -07001074 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001075 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001076
Alec Mouri754c98a2019-03-18 18:53:42 -07001077 // Start receiving vsync samples now, so that we can detect a period
1078 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001079 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001080 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001081 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001082 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001083
Ady Abraham690f4612021-07-01 23:24:03 -07001084 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001085 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001086 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001087}
1088
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001089status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001090 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001091
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001092 if (!displayToken) {
1093 return BAD_VALUE;
1094 }
Ady Abraham838de062019-02-04 10:24:03 -08001095
Dominik Laskowski756b7892021-08-04 12:53:59 -07001096 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001097 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001098 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001099 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001100 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001101 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001102 }
1103
1104 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001105 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001106 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001107 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001108
1109 const auto mode = display->getMode(DisplayModeId{modeId});
1110 if (!mode) {
1111 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1112 return BAD_VALUE;
1113 }
1114
1115 const auto fps = mode->getFps();
1116 // Keep the old switching type.
1117 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001118 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001119 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1120 allowGroupSwitching,
1121 {fps, fps}};
1122 constexpr bool kOverridePolicy = false;
1123
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001124 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001125 });
1126
1127 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001128}
1129
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001130void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001131 ATRACE_CALL();
1132
Dominik Laskowski22488f62019-03-28 09:53:04 -07001133 const auto display = getDefaultDisplayDeviceLocked();
1134 if (!display) {
1135 return;
1136 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001137
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001138 const auto upcomingModeInfo =
1139 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1140
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001141 if (!upcomingModeInfo.mode) {
1142 // There is no pending mode change. This can happen if the active
1143 // display changed and the mode change happened on a different display.
1144 return;
1145 }
1146
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001147 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001148 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1149 // We need to generate new sequenceId in order to recreate the display (and this
1150 // way the framebuffer).
1151 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001152 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001153 processDisplayChangesLocked();
1154
1155 // processDisplayChangesLocked will update all necessary components so we're done here.
1156 return;
1157 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001158
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001159 // We just created this display so we can call even if we are not on the main thread.
1160 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001161 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001162
Ady Abraham690f4612021-07-01 23:24:03 -07001163 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001164 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001165 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001166
Dominik Laskowski068173d2021-08-11 17:22:59 -07001167 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001168 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001169 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001170}
1171
Ady Abraham690f4612021-07-01 23:24:03 -07001172void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1173 display->clearDesiredActiveModeState();
1174 if (isDisplayActiveLocked(display)) {
1175 mScheduler->setModeChangePending(false);
1176 }
Ady Abraham53852a52019-05-28 18:07:44 -07001177}
1178
Ady Abraham690f4612021-07-01 23:24:03 -07001179void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1180 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1181 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001182 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001183 updatePhaseConfiguration(refreshRate);
1184}
1185
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001186void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001187 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001188
Marin Shalamanovdd594312021-11-09 16:37:37 +01001189 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1190
Ady Abraham690f4612021-07-01 23:24:03 -07001191 for (const auto& iter : mDisplays) {
1192 const auto& display = iter.second;
1193 if (!display || !display->isInternal()) {
1194 continue;
1195 }
1196
1197 // Store the local variable to release the lock.
1198 const auto desiredActiveMode = display->getDesiredActiveMode();
1199 if (!desiredActiveMode) {
1200 // No desired active mode pending to be applied
1201 continue;
1202 }
1203
1204 if (!isDisplayActiveLocked(display)) {
1205 // display is no longer the active display, so abort the mode change
1206 clearDesiredActiveModeState(display);
1207 continue;
1208 }
1209
1210 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1211 if (!desiredMode) {
1212 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1213 desiredActiveMode->mode->getId().value());
1214 clearDesiredActiveModeState(display);
1215 continue;
1216 }
1217
1218 const auto refreshRate = desiredMode->getFps();
1219 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1220 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1221 to_string(display->getId()).c_str());
1222
1223 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001224 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001225 desiredActiveModeChangeDone(display);
1226 continue;
1227 }
1228
1229 // Desired active mode was set, it is different than the mode currently in use, however
1230 // allowed modes might have changed by the time we process the refresh.
1231 // Make sure the desired mode is still allowed
1232 const auto displayModeAllowed =
1233 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1234 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001235 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001236 continue;
1237 }
1238
1239 // TODO(b/142753666) use constrains
1240 hal::VsyncPeriodChangeConstraints constraints;
1241 constraints.desiredTimeNanos = systemTime();
1242 constraints.seamlessRequired = false;
1243 hal::VsyncPeriodChangeTimeline outTimeline;
1244
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001245 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1246 display->initiateModeChange(*desiredActiveMode,
1247 constraints, &outTimeline));
1248
Ady Abraham690f4612021-07-01 23:24:03 -07001249 if (status != NO_ERROR) {
1250 // initiateModeChange may fail if a hotplug event is just about
1251 // to be sent. We just log the error in this case.
1252 ALOGW("initiateModeChange failed: %d", status);
1253 continue;
1254 }
1255 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1256
Marin Shalamanovdd594312021-11-09 16:37:37 +01001257 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001258 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001259 mSetActiveModePending = true;
1260 } else {
1261 // Updating the internal state should be done outside the loop,
1262 // because it can recreate a DisplayDevice and modify mDisplays
1263 // which will invalidate the iterator.
1264 displayToUpdateImmediately = display->getPhysicalId();
1265 }
1266 }
1267
1268 if (displayToUpdateImmediately) {
1269 updateInternalStateWithChangedMode();
1270
1271 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1272 const auto desiredActiveMode = display->getDesiredActiveMode();
1273 if (desiredActiveMode &&
1274 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1275 desiredActiveModeChangeDone(display);
1276 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001277 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001278}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001279
Alec Mouridea1ac52021-06-23 18:12:18 -07001280void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001281 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001282 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001283 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001284 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001285 for (const auto& [_, display] : mDisplays) {
1286 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001287 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001288 }
1289 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001290 });
1291
1292 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001293}
1294
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001295std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1296 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001297
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001298 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001299 // filter out all wide color modes. The typical reason why this happens is that the
1300 // hardware is not good enough to support GPU composition of wide color, and thus the
1301 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001302 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1303 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001304 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1305 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001306 }
Michael Wright28f24d02016-07-12 13:30:53 -07001307
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001308 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001309}
1310
Daniel Solomon42d04562019-01-20 21:03:19 -08001311status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001312 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001313 if (!displayToken) {
1314 return BAD_VALUE;
1315 }
1316
Dominik Laskowski3c363242022-04-07 10:44:12 -07001317 Mutex::Autolock lock(mStateLock);
1318
1319 const auto display = getDisplayDeviceLocked(displayToken);
1320 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001321 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001322 }
1323
Dominik Laskowski3c363242022-04-07 10:44:12 -07001324 const auto connectionType = display->getConnectionType();
1325 if (connectionType != ui::DisplayConnectionType::Internal) {
1326 return INVALID_OPERATION;
1327 }
1328
1329 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1330 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001331 return NO_ERROR;
1332}
1333
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001334status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001335 if (!displayToken) {
1336 return BAD_VALUE;
1337 }
1338
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001339 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001340 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001341 if (!display) {
1342 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1343 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001344 return NAME_NOT_FOUND;
1345 }
1346
1347 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001348 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1349 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001350 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001351 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001352
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001353 const auto modes = getDisplayColorModes(*display);
1354 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1355
1356 if (mode < ColorMode::NATIVE || !exists) {
1357 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1358 decodeColorMode(mode).c_str(), mode, displayToken.get());
1359 return BAD_VALUE;
1360 }
1361
1362 display->getCompositionDisplay()->setColorProfile(
1363 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1364
1365 return NO_ERROR;
1366 });
1367
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001368 // TODO(b/195698395): Propagate error.
1369 future.wait();
1370 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001371}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001372
Kriti Dang7defaf32021-11-15 11:55:43 +01001373status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001374 auto future = mScheduler->schedule(
1375 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1376
1377 *outSupport = future.get();
1378 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001379}
1380
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001381status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1382 ui::DisplayModeId modeId) {
1383 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001384 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001385 const auto display = getDisplayDeviceLocked(displayToken);
1386 if (!display) {
1387 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1388 return NAME_NOT_FOUND;
1389 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001390
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001391 if (display->isVirtual()) {
1392 ALOGE("%s: Invalid operation on virtual display", whence);
1393 return INVALID_OPERATION;
1394 }
1395
1396 const auto displayId = display->getPhysicalId();
1397 const auto mode = display->getMode(DisplayModeId{modeId});
1398 if (!mode) {
1399 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1400 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001401 return BAD_VALUE;
1402 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001403
1404 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001405 });
1406 return future.get();
1407}
1408
1409status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001410 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001411 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001412 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1413 return getHwComposer().clearBootDisplayMode(*displayId);
1414 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001415 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001416 return BAD_VALUE;
1417 }
1418 });
1419 return future.get();
1420}
1421
Galia Peycheva5492cb52019-10-30 14:13:16 +01001422void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001423 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001424 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001425 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1426 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1427 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001428 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001429 }
1430 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001431}
1432
Galia Peycheva5492cb52019-10-30 14:13:16 +01001433void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001434 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001435 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001436 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001437 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001438 getHwComposer().setContentType(*displayId, type);
1439 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001440 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001441 }
1442 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001443}
1444
Svetoslavd85084b2014-03-20 10:28:31 -07001445status_t SurfaceFlinger::clearAnimationFrameStats() {
1446 Mutex::Autolock _l(mStateLock);
1447 mAnimFrameTracker.clearStats();
1448 return NO_ERROR;
1449}
1450
1451status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1452 Mutex::Autolock _l(mStateLock);
1453 mAnimFrameTracker.getStats(outStats);
1454 return NO_ERROR;
1455}
1456
Kriti Dang49ad4132021-01-08 11:49:56 +01001457status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1458 const std::vector<ui::Hdr>& hdrTypes) {
1459 Mutex::Autolock lock(mStateLock);
1460
1461 auto display = getDisplayDeviceLocked(displayToken);
1462 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001463 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001464 return NAME_NOT_FOUND;
1465 }
1466
1467 display->overrideHdrTypes(hdrTypes);
1468 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1469 return NO_ERROR;
1470}
1471
Tej Singhe2751772021-04-06 22:05:29 -07001472status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1473 *success = mTimeStats->onPullAtom(atomId, pulledData);
1474 return NO_ERROR;
1475}
1476
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001477status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1478 ui::PixelFormat* outFormat,
1479 ui::Dataspace* outDataspace,
1480 uint8_t* outComponentMask) const {
1481 if (!outFormat || !outDataspace || !outComponentMask) {
1482 return BAD_VALUE;
1483 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001484
1485 Mutex::Autolock lock(mStateLock);
1486
1487 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1488 if (!displayId) {
1489 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001490 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001491
1492 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001493 outDataspace, outComponentMask);
1494}
1495
Kevin DuBois74e53772018-11-19 10:52:38 -08001496status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1497 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001498 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001499 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001500 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001501 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1502 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1503 componentMask, maxFrames);
1504 } else {
1505 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1506 return NAME_NOT_FOUND;
1507 }
1508 });
1509
1510 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001511}
1512
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001513status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1514 uint64_t maxFrames, uint64_t timestamp,
1515 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001516 Mutex::Autolock lock(mStateLock);
1517
1518 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1519 if (!displayId) {
1520 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001521 }
1522
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001523 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001524}
1525
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001526status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1527 if (!outSupported) {
1528 return BAD_VALUE;
1529 }
1530 *outSupported = getRenderEngine().supportsProtectedContent();
1531 return NO_ERROR;
1532}
1533
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001534status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1535 bool* outIsWideColorDisplay) const {
1536 if (!displayToken || !outIsWideColorDisplay) {
1537 return BAD_VALUE;
1538 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001539
1540 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001541 const auto display = getDisplayDeviceLocked(displayToken);
1542 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001543 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001544 }
Peiyong Linff84a152019-05-17 18:36:19 -07001545
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001546 *outIsWideColorDisplay =
1547 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001548 return NO_ERROR;
1549}
1550
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001551status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001552 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001553 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001554
Dominik Laskowski6505f792019-09-18 11:10:05 -07001555 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001556 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001557 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001558 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001559
Dominik Laskowski756b7892021-08-04 12:53:59 -07001560 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001561 return NO_ERROR;
1562}
1563
1564status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001565 Mutex::Autolock lock(mStateLock);
Ady Abrahame90dd522020-12-29 12:08:45 -08001566 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(when);
Ady Abraham56b42a42020-12-28 16:48:48 -08001567 const auto expectedPresent = calculateExpectedPresentTime(stats);
Ady Abraham9c53ee72020-07-22 21:16:18 -07001568 return mScheduler->injectVSync(when, /*expectedVSyncTime=*/expectedPresent,
1569 /*deadlineTimestamp=*/expectedPresent)
1570 ? NO_ERROR
1571 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001572}
1573
Huihong Luo05539a12022-02-23 10:29:40 -08001574status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001575 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001576 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001577 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001578 mDrawingState.traverseInZOrder([&](Layer* layer) {
1579 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1580 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001581 });
1582
1583 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001584 return NO_ERROR;
1585}
1586
Peiyong Linc6780972018-10-28 15:24:08 -07001587status_t SurfaceFlinger::getCompositionPreference(
1588 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1589 Dataspace* outWideColorGamutDataspace,
1590 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001591 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001592 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001593 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001594 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001595 return NO_ERROR;
1596}
1597
Dan Stozaec460082018-12-17 15:35:09 -08001598status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1599 const sp<IBinder>& stopLayerHandle,
1600 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001601 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001602 return BAD_VALUE;
1603 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001604
1605 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1606 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001607 return NO_ERROR;
1608}
1609
Dan Stozaec460082018-12-17 15:35:09 -08001610status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001611 if (!listener) {
1612 return BAD_VALUE;
1613 }
Dan Stozaec460082018-12-17 15:35:09 -08001614 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001615 return NO_ERROR;
1616}
Dan Gittik57e63c52019-01-18 16:37:54 +00001617
Alec Mouria9a68a62021-03-04 19:14:50 -08001618status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001619 if (!listener) {
1620 return BAD_VALUE;
1621 }
1622
Alec Mouria9a68a62021-03-04 19:14:50 -08001623 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001624 return NO_ERROR;
1625}
1626
1627status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1628 if (!listener) {
1629 return BAD_VALUE;
1630 }
1631 mFpsReporter->removeListener(listener);
1632 return NO_ERROR;
1633}
1634
Galia Peycheva8f04b302021-04-27 13:25:38 +02001635status_t SurfaceFlinger::addTunnelModeEnabledListener(
1636 const sp<gui::ITunnelModeEnabledListener>& listener) {
1637 if (!listener) {
1638 return BAD_VALUE;
1639 }
1640
1641 mTunnelModeEnabledReporter->addListener(listener);
1642 return NO_ERROR;
1643}
1644
1645status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1646 const sp<gui::ITunnelModeEnabledListener>& listener) {
1647 if (!listener) {
1648 return BAD_VALUE;
1649 }
1650
1651 mTunnelModeEnabledReporter->removeListener(listener);
1652 return NO_ERROR;
1653}
1654
Dan Gittik57e63c52019-01-18 16:37:54 +00001655status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1656 bool* outSupport) const {
1657 if (!displayToken || !outSupport) {
1658 return BAD_VALUE;
1659 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001660
1661 Mutex::Autolock lock(mStateLock);
1662
Dan Gittik57e63c52019-01-18 16:37:54 +00001663 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1664 if (!displayId) {
1665 return NAME_NOT_FOUND;
1666 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001667 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001668 return NO_ERROR;
1669}
1670
Alec Mouricdf16792021-12-10 13:16:06 -08001671bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1672 bool hasHdrLayers = false;
1673 mDrawingState.traverse([&,
1674 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1675 hasHdrLayers |= (layer->isVisible() &&
1676 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1677 isHdrDataspace(layer->getDataSpace()));
1678 });
1679 return hasHdrLayers;
1680}
1681
John Reck22be6962021-03-10 12:59:54 -05001682status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1683 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001684 if (!displayToken) {
1685 return BAD_VALUE;
1686 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001687
Dominik Laskowski756b7892021-08-04 12:53:59 -07001688 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001689 return ftl::chain(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001690 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001691 const bool supportsDisplayBrightnessCommand =
1692 getHwComposer().getComposer()->isSupported(
1693 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1694 // If we support applying display brightness as a command, then we also support
1695 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001696 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001697 auto compositionDisplay = display->getCompositionDisplay();
1698 float currentDimmingRatio =
1699 compositionDisplay->editState().sdrWhitePointNits /
1700 compositionDisplay->editState().displayBrightnessNits;
1701 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1702 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001703 FTL_FAKE_GUARD(kMainThreadContext,
1704 display->stageBrightness(brightness.displayBrightness));
1705
Alec Mouri6da0e272022-02-07 12:45:57 -08001706 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1707 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001708 scheduleComposite(FrameHint::kNone);
1709 } else {
1710 scheduleCommit(FrameHint::kNone);
1711 }
1712 return ftl::yield<status_t>(OK);
1713 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001714 return getHwComposer()
1715 .setDisplayBrightness(display->getPhysicalId(),
1716 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001717 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001718 Hwc2::Composer::DisplayBrightnessOptions{
1719 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001720 }
Alec Mouricdf16792021-12-10 13:16:06 -08001721
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001722 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001723 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001724 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001725 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001726 }))
1727 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001728 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001729}
1730
John Reck88270902021-03-18 11:27:35 -04001731status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1732 const sp<gui::IHdrLayerInfoListener>& listener) {
1733 if (!displayToken) {
1734 return BAD_VALUE;
1735 }
1736
1737 Mutex::Autolock lock(mStateLock);
1738
1739 const auto display = getDisplayDeviceLocked(displayToken);
1740 if (!display) {
1741 return NAME_NOT_FOUND;
1742 }
1743 const auto displayId = display->getId();
1744 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1745 if (!hdrInfoReporter) {
1746 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1747 }
1748 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001749
1750
1751 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001752 return OK;
1753}
1754
1755status_t SurfaceFlinger::removeHdrLayerInfoListener(
1756 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1757 if (!displayToken) {
1758 return BAD_VALUE;
1759 }
1760
1761 Mutex::Autolock lock(mStateLock);
1762
1763 const auto display = getDisplayDeviceLocked(displayToken);
1764 if (!display) {
1765 return NAME_NOT_FOUND;
1766 }
1767 const auto displayId = display->getId();
1768 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1769 if (hdrInfoReporter) {
1770 hdrInfoReporter->removeListener(listener);
1771 }
1772 return OK;
1773}
1774
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001775status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001776 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001777 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001778
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001779 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001780 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001781 }
1782
1783 return NO_ERROR;
1784}
1785
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001786status_t SurfaceFlinger::getDisplayDecorationSupport(
1787 const sp<IBinder>& displayToken,
1788 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001789 if (!displayToken || !outSupport) {
1790 return BAD_VALUE;
1791 }
1792
1793 Mutex::Autolock lock(mStateLock);
1794
1795 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1796 if (!displayId) {
1797 return NAME_NOT_FOUND;
1798 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001799 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001800 return NO_ERROR;
1801}
1802
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001803// ----------------------------------------------------------------------------
1804
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001805sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001806 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001807 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001808 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1809 ? mSfConnectionHandle
1810 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001811
Ady Abraham62f216c2020-10-13 19:07:23 -07001812 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001813}
1814
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001815void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001816 if (hint == FrameHint::kActive) {
1817 mScheduler->resetIdleTimer();
1818 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001819 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001820 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001821}
1822
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001823void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1824 mMustComposite = true;
1825 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001826}
1827
1828void SurfaceFlinger::scheduleRepaint() {
1829 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001830 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001831}
1832
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001833void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001834 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001835}
1836
Ady Abraham2492a022020-07-24 11:09:55 -07001837nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001838 if (const auto display = getDefaultDisplayDeviceLocked()) {
1839 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001840 }
1841
Marin Shalamanov045b7002021-01-07 16:56:24 +01001842 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001843}
1844
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001845void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1846 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001847 const std::string tracePeriod = [vsyncPeriod]() {
1848 if (ATRACE_ENABLED() && vsyncPeriod) {
1849 std::stringstream ss;
1850 ss << "(" << *vsyncPeriod << ")";
1851 return ss.str();
1852 }
1853 return std::string();
1854 }();
1855 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001856
Steven Thomas3cfac282017-02-06 12:29:30 -08001857 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001858 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1859 if (displayId) {
1860 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1861 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001862 display->onVsync(timestamp);
1863 }
1864
Dominik Laskowski075d3172018-05-24 15:50:06 -07001865 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001866 return;
1867 }
1868
Ady Abrahame1166472021-07-15 10:56:06 -07001869 const bool isActiveDisplay =
1870 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1871 if (!isActiveDisplay) {
1872 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001873 return;
1874 }
1875
Alec Mourif8e689c2019-05-20 18:32:22 -07001876 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001877 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001878 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001879 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001880 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001881}
1882
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001883void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001884 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1885 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001886}
1887
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001888void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1889 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001890 const bool connected = connection == hal::Connection::CONNECTED;
1891 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001892
Steven Thomasb02664d2017-07-26 18:48:28 -07001893 // Only lock if we're not on the main thread. This function is normally
1894 // called on a hwbinder thread, but for the primary display it's called on
1895 // the main thread with the state lock already held, so don't attempt to
1896 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001897 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001898
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001899 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001900
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001901 if (std::this_thread::get_id() == mMainThreadId) {
1902 // Process all pending hot plug events immediately if we are on the main thread.
1903 processDisplayHotplugEventsLocked();
1904 }
1905
Lloyd Piqueba04e622017-12-14 17:11:26 -08001906 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001907}
1908
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001909void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1910 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001911 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001912 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001913
1914 if (timeline.refreshRequired) {
1915 scheduleComposite(FrameHint::kNone);
1916 }
Ady Abraham7159f572019-10-11 11:10:18 -07001917}
1918
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001919void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001920 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001921 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1922}
1923
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001924void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001925 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001926 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001927}
1928
Yichi Chen3401b562022-01-17 15:42:35 +08001929void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001930 ATRACE_CALL();
1931 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001932}
1933
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001934void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001935 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001936
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001937 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001938 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001939 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001940
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001941 if (const auto display = getDefaultDisplayDeviceLocked();
1942 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001943 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001944 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001945 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001946}
1947
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001948SurfaceFlinger::FenceWithFenceTime SurfaceFlinger::previousFrameFence() {
Ady Abrahamccf4b472021-05-11 19:53:01 -07001949 const auto now = systemTime();
1950 const auto vsyncPeriod = mScheduler->getDisplayStatInfo(now).vsyncPeriod;
1951 const bool expectedPresentTimeIsTheNextVsync = mExpectedPresentTime - now <= vsyncPeriod;
1952 return expectedPresentTimeIsTheNextVsync ? mPreviousPresentFences[0]
1953 : mPreviousPresentFences[1];
Alec Mouri6d414b52020-03-17 11:18:05 -07001954}
1955
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001956bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001957 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001958 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001959
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001960 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001961 return false;
1962 }
1963
Dan Stoza59083052020-04-28 10:13:20 -07001964 const status_t status = fence->wait(graceTimeMs);
1965 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1966 // which calls wait(0) again internally
1967 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001968}
1969
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001970nsecs_t SurfaceFlinger::previousFramePresentTime() {
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001971 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001972
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001973 if (fence == FenceTime::NO_FENCE) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001974 return Fence::SIGNAL_TIME_INVALID;
1975 }
1976
1977 return fence->getSignalTime();
1978}
1979
Ady Abraham56b42a42020-12-28 16:48:48 -08001980nsecs_t SurfaceFlinger::calculateExpectedPresentTime(DisplayStatInfo stats) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001981 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham8cb21882020-08-26 18:22:05 -07001982 return mVsyncModulator->getVsyncConfig().sfOffset > 0 ? stats.vsyncTime
1983 : stats.vsyncTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001984}
1985
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001986bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1987 FTL_FAKE_GUARD(kMainThreadContext) {
Matt Buckleyef51fba2021-10-12 19:30:12 +00001988 // we set this once at the beginning of commit to ensure consistency throughout the whole frame
Xiang Wang839fe5b2022-04-04 17:39:38 +00001989 mPowerHintSessionData.sessionEnabled = mPowerAdvisor->usePowerHintSession();
Matt Buckleyef51fba2021-10-12 19:30:12 +00001990 if (mPowerHintSessionData.sessionEnabled) {
1991 mPowerHintSessionData.commitStart = systemTime();
1992 }
1993
Dan Stoza28d46a52020-04-28 09:54:54 -07001994 // calculate the expected present time once and use the cached
1995 // value throughout this frame to make sure all layers are
1996 // seeing this same value.
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001997 if (expectedVsyncTime >= frameTime) {
1998 mExpectedPresentTime = expectedVsyncTime;
Snild Dolkow819636c2021-01-22 14:42:08 +01001999 } else {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002000 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(frameTime);
Snild Dolkow819636c2021-01-22 14:42:08 +01002001 mExpectedPresentTime = calculateExpectedPresentTime(stats);
2002 }
2003
2004 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002005 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07002006
Matt Buckleyef51fba2021-10-12 19:30:12 +00002007 if (mPowerHintSessionData.sessionEnabled) {
Xiang Wang839fe5b2022-04-04 17:39:38 +00002008 mPowerAdvisor->setTargetWorkDuration(mExpectedPresentTime -
2009 mPowerHintSessionData.commitStart);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002010 }
Ady Abraham893c99d2021-04-30 16:00:23 -07002011 const auto vsyncIn = [&] {
2012 if (!ATRACE_ENABLED()) return 0.f;
2013 return (mExpectedPresentTime - systemTime()) / 1e6f;
2014 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002015 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
2016 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002017
Dan Stoza28d46a52020-04-28 09:54:54 -07002018 // When Backpressure propagation is enabled we want to give a small grace period
2019 // for the present fence to fire instead of just giving up on this frame to handle cases
2020 // where present fence is just about to get signaled.
2021 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002022 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002023
2024 // Pending frames may trigger backpressure propagation.
2025 const TracedOrdinal<bool> framePending = {"PrevFramePending",
2026 previousFramePending(graceTimeForPresentFenceMs)};
2027
2028 // Frame missed counts for metrics tracking.
2029 // A frame is missed if the prior frame is still pending. If no longer pending,
2030 // then we still count the frame as missed if the predicted present time
2031 // was further in the past than when the fence actually fired.
2032
2033 // Add some slop to correct for drift. This should generally be
2034 // smaller than a typical frame duration, but should not be so small
2035 // that it reports reasonable drift as a missed frame.
Ady Abrahame90dd522020-12-29 12:08:45 -08002036 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(systemTime());
Dan Stoza28d46a52020-04-28 09:54:54 -07002037 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
2038 const nsecs_t previousPresentTime = previousFramePresentTime();
2039 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2040 framePending ||
2041 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002042 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002043 previousPresentTime - frameMissedSlop))};
2044 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2045 mHadDeviceComposition && frameMissed};
2046 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2047 mHadClientComposition && frameMissed};
2048
2049 if (frameMissed) {
2050 mFrameMissedCount++;
2051 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002052 }
2053
2054 if (hwcFrameMissed) {
2055 mHwcFrameMissedCount++;
2056 }
2057
2058 if (gpuFrameMissed) {
2059 mGpuFrameMissedCount++;
2060 }
2061
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002062 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002063 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002064 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002065 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002066 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002067 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002068 }
2069
2070 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002071 // the mode, hence we update SF.
2072 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002073 {
2074 Mutex::Autolock lock(mStateLock);
2075 updateInternalStateWithChangedMode();
2076 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002077 }
2078
John Reck2ec53912020-07-07 16:53:55 -07002079 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002080 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002081 scheduleCommit(FrameHint::kNone);
2082 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002083 }
2084 }
2085
Dan Stoza28d46a52020-04-28 09:54:54 -07002086 if (mTracingEnabledChanged) {
Vishnu Nair7891e962021-11-11 12:07:21 -08002087 mLayerTracingEnabled = mLayerTracing.isEnabled();
Dan Stoza28d46a52020-04-28 09:54:54 -07002088 mTracingEnabledChanged = false;
2089 }
2090
Ady Abraham29d0da32020-07-16 18:39:33 -07002091 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002092 Mutex::Autolock lock(mStateLock);
2093 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002094 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002095 }
2096 }
2097
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002098 // Composite if transactions were committed, or if requested by HWC.
2099 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002100 {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002101 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(stats.vsyncPeriod));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002102
chaviw6b9ffea2021-11-08 09:25:48 -06002103 bool needsTraversal = false;
2104 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002105 needsTraversal |= commitCreatedLayers();
2106 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002107 }
2108
2109 const bool shouldCommit =
2110 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2111 if (shouldCommit) {
2112 commitTransactions();
2113 }
2114
2115 if (transactionFlushNeeded()) {
2116 setTransactionFlags(eTransactionFlushNeeded);
2117 }
2118
2119 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002120 mustComposite |= latchBuffers();
2121
chaviw6b9ffea2021-11-08 09:25:48 -06002122 // This has to be called after latchBuffers because we want to include the layers that have
2123 // been latched in the commit callback
2124 if (!needsTraversal) {
2125 // Invoke empty transaction callbacks early.
2126 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2127 } else {
2128 // Invoke OnCommit callbacks.
2129 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2130 }
2131
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002132 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002133 }
2134
2135 // Layers need to get updated (in the previous line) before we can use them for
2136 // choosing the refresh rate.
2137 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2138 // and may eventually call to ~Layer() if it holds the last reference
2139 {
2140 Mutex::Autolock _l(mStateLock);
2141 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002142 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002143 }
2144
Dan Stoza28d46a52020-04-28 09:54:54 -07002145 updateCursorAsync();
2146 updateInputFlinger();
2147
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002148 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2149 // This will block and tracing should only be enabled for debugging.
2150 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
2151 }
2152
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002153 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002154
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002155 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002156}
2157
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002158void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2159 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002160 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002161
Matt Buckleyef51fba2021-10-12 19:30:12 +00002162 if (mPowerHintSessionData.sessionEnabled) {
2163 mPowerHintSessionData.compositeStart = systemTime();
2164 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07002165
Lloyd Piqueab039b52019-02-13 14:22:42 -08002166 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002167 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002168 refreshArgs.outputs.reserve(displays.size());
2169 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002170 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2171 }
2172 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002173 if (auto layerFE = layer->getCompositionEngineLayerFE())
2174 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002175 });
Tianhao Yao67dd7122022-02-22 17:48:33 +00002176
2177 if (DOES_CONTAIN_BORDER) {
2178 refreshArgs.borderInfoList.clear();
2179 mDrawingState.traverse([&refreshArgs](Layer* layer) {
2180 if (layer->isBorderEnabled()) {
2181 compositionengine::BorderRenderInfo info;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00002182 info.width = layer->getBorderWidth();
2183 info.color = layer->getBorderColor();
Tianhao Yao67dd7122022-02-22 17:48:33 +00002184 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2185 info.layerIds.push_back(ilayer->getSequence());
2186 });
2187 refreshArgs.borderInfoList.emplace_back(std::move(info));
2188 }
2189 });
2190 }
2191
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002192 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002193 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002194 if (auto layerFE = layer->getCompositionEngineLayerFE())
2195 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002196 }
2197
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002198 refreshArgs.outputColorSetting = useColorManagement
2199 ? mDisplayColorSetting
2200 : compositionengine::OutputColorSetting::kUnmanaged;
2201 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2202 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002203
2204 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002205 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002206 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002207 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002208
2209 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2210 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2211 mDrawingState.colorMatrixChanged = false;
2212 }
2213
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002214 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002215
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002216 if (mDebugFlashDelay != 0) {
2217 refreshArgs.devOptForceClientComposition = true;
2218 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002219 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002220
Ady Abraham43065bd2021-12-10 17:22:15 -08002221 const auto expectedPresentTime = mExpectedPresentTime.load();
2222 const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
Ady Abrahamcaba2982021-06-16 16:45:04 -07002223 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2224 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002225 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002226 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002227 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002228
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002229 // Store the present time just before calling to the composition engine so we could notify
2230 // the scheduler.
2231 const auto presentTime = systemTime();
2232
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002233 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002234
2235 if (mPowerHintSessionData.sessionEnabled) {
2236 mPowerHintSessionData.presentEnd = systemTime();
2237 }
2238
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002239 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002240
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002241 if (mScheduler->onPostComposition(presentTime)) {
2242 scheduleComposite(FrameHint::kNone);
2243 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002244
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002245 postFrame();
2246 postComposition();
2247
Midas Chien50f52e22020-09-26 17:57:42 +08002248 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002249
Vishnu Nair9cf89262022-02-26 09:17:49 -08002250 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2251 TimeStats::ClientCompositionRecord clientCompositionRecord;
2252 for (const auto& [_, display] : displays) {
2253 const auto& state = display->getCompositionDisplay()->getState();
2254 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2255 mHadDeviceComposition |= state.usesDeviceComposition;
2256 mReusedClientComposition |= state.reusedClientComposition;
2257 clientCompositionRecord.predicted |=
2258 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2259 clientCompositionRecord.predictionSucceeded |=
2260 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002261 }
2262
Vishnu Nair9cf89262022-02-26 09:17:49 -08002263 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2264 clientCompositionRecord.reused = mReusedClientComposition;
2265 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2266 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2267
Yichi Chen28dee2c2020-07-06 21:24:14 +08002268 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002269 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2270 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002271
David Sodman7e4ae112018-02-09 15:02:28 -08002272 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002273 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002274 // This will block and should only be used for debugging.
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002275 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
Vishnu Nairdf529052019-06-07 14:53:14 -07002276 }
Robert Carr167bdde2021-07-28 11:26:51 -07002277
2278 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002279 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002280
2281 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002282 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002283 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002284
2285 // calculate total render time for performance hinting if adpf cpu hint is enabled,
2286 if (mPowerHintSessionData.sessionEnabled) {
2287 const nsecs_t flingerDuration =
2288 (mPowerHintSessionData.presentEnd - mPowerHintSessionData.commitStart);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002289 mPowerAdvisor->sendActualWorkDuration(flingerDuration, mPowerHintSessionData.presentEnd);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002290 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002291}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002292
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002293void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002294 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002295
Vishnu Nair4351ad52019-02-11 14:13:02 -08002296 if (mVisibleRegionsDirty) {
2297 computeLayerBounds();
2298 }
2299
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002300 for (auto& layer : mLayersPendingRefresh) {
2301 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002302 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002303 invalidateLayerStack(layer, visibleReg);
2304 }
2305 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002306}
2307
Ana Krulece588e312018-09-18 12:32:24 -07002308void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2309 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002310 // Update queue of past composite+present times and determine the
2311 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002312 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002313 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002314 while (!getBE().mCompositePresentTimes.empty()) {
2315 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002316 // Cached values should have been updated before calling this method,
2317 // which helps avoid duplicate syscalls.
2318 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2319 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2320 break;
2321 }
2322 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002323 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002324 }
2325
2326 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002327 while (getBE().mCompositePresentTimes.size() > 16) {
2328 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002329 }
2330
Ana Krulece588e312018-09-18 12:32:24 -07002331 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002332}
2333
Ana Krulece588e312018-09-18 12:32:24 -07002334void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2335 nsecs_t compositeToPresentLatency) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002336 // Avoid division by 0 by defaulting to 60Hz
2337 const auto vsyncPeriod = stats.vsyncPeriod ?: (60_Hz).getPeriodNsecs();
2338
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002339 // Integer division and modulo round toward 0 not -inf, so we need to
2340 // treat negative and positive offsets differently.
Ady Abraham8287e852020-08-12 14:44:58 -07002341 nsecs_t idealLatency = (mVsyncConfiguration->getCurrentConfigs().late.sfOffset > 0)
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002342 ? (vsyncPeriod -
2343 (mVsyncConfiguration->getCurrentConfigs().late.sfOffset % vsyncPeriod))
2344 : ((-mVsyncConfiguration->getCurrentConfigs().late.sfOffset) % vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002345
Ady Abraham8287e852020-08-12 14:44:58 -07002346 // Just in case mVsyncConfiguration->getCurrentConfigs().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002347 if (idealLatency <= 0) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002348 idealLatency = vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002349 }
2350
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002351 // Snap the latency to a value that removes scheduling jitter from the
2352 // composition and present times, which often have >1ms of jitter.
2353 // Reducing jitter is important if an app attempts to extrapolate
2354 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002355 // Snapping also allows an app to precisely calculate
Ady Abraham8287e852020-08-12 14:44:58 -07002356 // mVsyncConfiguration->getCurrentConfigs().late.sf with (presentLatency % interval).
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002357 const nsecs_t bias = vsyncPeriod / 2;
2358 const int64_t extraVsyncs = ((compositeToPresentLatency - idealLatency + bias) / vsyncPeriod);
Ady Abraham8d7e7842022-02-03 01:42:45 +00002359 const nsecs_t snappedCompositeToPresentLatency =
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002360 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002361
David Sodman99974d22017-11-28 12:04:33 -08002362 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002363 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002364 getBE().mCompositorTiming.interval = vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002365 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002366}
2367
John Reck49d9ad32022-02-23 19:03:31 -05002368bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002369 // Treat all layers as non-HDR if:
2370 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2371 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2372 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2373 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2374 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002375 return false;
2376 }
2377 if (mIgnoreHdrCameraLayers) {
2378 auto buffer = layer->getBuffer();
2379 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2380 return false;
2381 }
2382 }
2383 return true;
2384}
2385
ramindani06e518e2022-03-14 18:47:53 +00002386ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2387 bool isPrimary) const {
2388 const auto id = PhysicalDisplayId::tryCast(displayId);
2389 if (!id) {
2390 return ui::ROTATION_0;
2391 }
2392 if (getHwComposer().getComposer()->isSupported(
2393 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2394 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2395 case Hwc2::AidlTransform::ROT_90:
2396 return ui::ROTATION_90;
2397 case Hwc2::AidlTransform::ROT_180:
2398 return ui::ROTATION_180;
2399 case Hwc2::AidlTransform::ROT_270:
2400 return ui::ROTATION_270;
2401 default:
2402 return ui::ROTATION_0;
2403 }
2404 }
2405
2406 if (isPrimary) {
2407 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2408 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2409 case Values::ORIENTATION_90:
2410 return ui::ROTATION_90;
2411 case Values::ORIENTATION_180:
2412 return ui::ROTATION_180;
2413 case Values::ORIENTATION_270:
2414 return ui::ROTATION_270;
2415 default:
2416 break;
2417 }
2418 }
2419 return ui::ROTATION_0;
2420}
2421
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002422void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002423 ATRACE_CALL();
2424 ALOGV("postComposition");
2425
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002426 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002427
David Sodman73beded2017-11-15 11:56:06 -08002428 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002429 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002430 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002431 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002432 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002433 ->getRenderSurface()
2434 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002435 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002436 } else {
2437 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2438 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002439
David Sodman73beded2017-11-15 11:56:06 -08002440 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002441 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002442 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002443 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002444 mPreviousPresentFences[0].fenceTime =
2445 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2446
2447 getBE().mDisplayTimeline.push(mPreviousPresentFences[0].fenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002448
Vishnu Nair9a69a042021-06-18 13:19:49 -07002449 nsecs_t now = systemTime();
2450
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002451 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2452 // information from previous' frame classification is already available when sending jank info
2453 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002454 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002455 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002456
Vishnu Nair9a69a042021-06-18 13:19:49 -07002457 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002458
Lloyd Piqueab039b52019-02-13 14:22:42 -08002459 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2460 // be sampled a little later than when we started doing work for this frame,
2461 // but that should be okay since updateCompositorTiming has snapping logic.
2462 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002463 mPreviousPresentFences[0].fenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002464 CompositorTiming compositorTiming;
2465 {
David Sodman99974d22017-11-28 12:04:33 -08002466 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2467 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002468 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002469
Robert Carrc747ad02021-06-11 14:01:24 -07002470 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002471 layer->onPostComposition(display, glCompositionDoneFenceTime,
2472 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002473 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002474 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002475
John Reck88270902021-03-18 11:27:35 -04002476 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2477 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002478 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002479 {
2480 Mutex::Autolock lock(mStateLock);
2481 if (mFpsReporter) {
2482 mFpsReporter->dispatchLayerFps();
2483 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002484
2485 if (mTunnelModeEnabledReporter) {
2486 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2487 }
John Reck88270902021-03-18 11:27:35 -04002488 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002489 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2490 if (reporter && reporter->hasListeners()) {
2491 if (const auto display = getDisplayDeviceLocked(displayId)) {
2492 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002493 }
2494 }
2495 }
Robert Carr167bdde2021-07-28 11:26:51 -07002496 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2497 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002498 }
2499
Robert Carr167bdde2021-07-28 11:26:51 -07002500 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2501 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2502 HdrLayerInfoReporter::HdrLayerInfo info;
2503 int32_t maxArea = 0;
2504 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2505 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002506 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002507 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002508 const auto* outputLayer =
2509 compositionDisplay->getOutputLayerForLayer(layerFe);
2510 if (outputLayer) {
2511 info.numberOfHdrLayers++;
2512 const auto displayFrame = outputLayer->getState().displayFrame;
2513 const int32_t area = displayFrame.width() * displayFrame.height();
2514 if (area > maxArea) {
2515 maxArea = area;
2516 info.maxW = displayFrame.width();
2517 info.maxH = displayFrame.height();
2518 }
John Reckdb1a16b2021-07-09 13:05:52 -04002519 }
John Reck88270902021-03-18 11:27:35 -04002520 }
2521 }
Robert Carr167bdde2021-07-28 11:26:51 -07002522 });
2523 listener->dispatchHdrLayerInfo(info);
2524 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002525 }
2526
Robert Carr167bdde2021-07-28 11:26:51 -07002527 mSomeDataspaceChanged = false;
2528 mVisibleRegionsWereDirtyThisFrame = false;
2529
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002530 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002531 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002532 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002533
Ady Abrahamed3290f2021-05-17 15:12:14 -07002534 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002535 mPreviousPresentFences[0].fenceTime->isValid()) {
2536 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002537 }
2538
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002539 const bool isDisplayConnected =
2540 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002541
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002542 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002543 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002544 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002545 }
2546 }
2547
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002548 if (mAnimCompositionPending) {
2549 mAnimCompositionPending = false;
2550
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002551 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2552 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002553 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002554 // The HWC doesn't support present fences, so use the refresh
2555 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002556 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002557 mAnimFrameTracker.setActualPresentTime(presentTime);
2558 }
2559 mAnimFrameTracker.advanceFrame();
2560 }
Dan Stozab90cf072015-03-05 11:05:59 -08002561
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002562 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002563
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002564 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002565
Alec Mouri717bcb62020-02-10 17:07:19 -08002566 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2567 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2568 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2569
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002570 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002571 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002572 return;
2573 }
2574
2575 nsecs_t currentTime = systemTime();
2576 if (mHasPoweredOff) {
2577 mHasPoweredOff = false;
2578 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002579 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002580 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002581 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2582 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002583 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002584 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002585 }
David Sodman4a36e932017-11-07 14:29:47 -08002586 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002587 }
David Sodman4a36e932017-11-07 14:29:47 -08002588 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002589
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002590 // Cleanup any outstanding resources due to rendering a prior frame.
2591 getRenderEngine().cleanupPostRender();
2592
Dan Stoza436ccf32018-06-21 12:10:12 -07002593 {
2594 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002595 if (mTexturePool.size() < mTexturePoolSize) {
2596 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002597 const size_t offset = mTexturePool.size();
2598 mTexturePool.resize(mTexturePoolSize);
2599 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2600 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002601 } else if (mTexturePool.size() > mTexturePoolSize) {
2602 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2603 const size_t offset = mTexturePoolSize;
2604 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2605 mTexturePool.resize(mTexturePoolSize);
2606 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002607 }
2608 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002609
Dan Stoza45de5ba2019-04-25 14:12:09 -07002610 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2611 // side-effect of getTotalSize(), so we check that again here
2612 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002613 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002614 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2615 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002616}
2617
chaviw79468ab2021-10-27 11:11:24 -05002618FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002619 const ui::Size maxSize = [this] {
2620 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002621
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002622 // The LayerTraceGenerator tool runs without displays.
2623 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002624
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002625 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2626 [](ui::Size size, const auto& pair) -> ui::Size {
2627 const auto& display = pair.second;
2628 return {std::max(size.getWidth(), display->getWidth()),
2629 std::max(size.getHeight(), display->getHeight())};
2630 });
2631 }();
chaviwb09c6552021-08-12 17:20:43 -05002632
2633 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2634 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002635 const float xMax = maxSize.getWidth() * 10.f;
2636 const float yMax = maxSize.getHeight() * 10.f;
2637
2638 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002639}
2640
2641void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002642 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002643 for (const auto& layer : mDrawingState.layersSortedByZ) {
2644 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002645 }
2646}
2647
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002648void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002649 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002650 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002651 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002652 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2653 logFrameStats();
2654 }
2655 }
2656}
2657
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002658void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002659 ATRACE_CALL();
2660
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002661 // Keep a copy of the drawing state (that is going to be overwritten
2662 // by commitTransactionsLocked) outside of mStateLock so that the side
2663 // effects of the State assignment don't happen with mStateLock held,
2664 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002665 State drawingState(mDrawingState);
2666
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002667 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002668 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669
Mathias Agopianca4d3602011-05-19 15:38:14 -07002670 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002671 // so we can call commitTransactionsLocked unconditionally.
2672 // We clear the flags with mStateLock held to guarantee that
2673 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002674 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002675 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002676
Mathias Agopianca4d3602011-05-19 15:38:14 -07002677 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002678}
2679
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002680std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2681 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002682 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2683 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002684
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002685 int attempt = 0;
2686 constexpr int kMaxAttempts = 3;
2687 do {
2688 hwcModes = getHwComposer().getModes(displayId);
2689 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2690 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2691
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002692 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2693 return mode.hwcId == *activeModeHwcId;
2694 };
2695
2696 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2697 break;
2698 }
2699 } while (++attempt < kMaxAttempts);
2700
2701 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002702 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002703 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002704 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002705
2706 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002707 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2708 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002709 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002710
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002711 ui::DisplayModeId nextModeId = 1 +
2712 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2713 [](ui::DisplayModeId max, const auto& pair) {
2714 return std::max(max, pair.first.value());
2715 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002716
2717 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002718 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002719 const DisplayModeId id{nextModeId++};
2720 newModes.try_emplace(id,
2721 DisplayMode::Builder(hwcMode.hwcId)
2722 .setId(id)
2723 .setPhysicalDisplayId(displayId)
2724 .setResolution({hwcMode.width, hwcMode.height})
2725 .setVsyncPeriod(hwcMode.vsyncPeriod)
2726 .setDpiX(hwcMode.dpiX)
2727 .setDpiY(hwcMode.dpiY)
2728 .setGroup(hwcMode.configGroup)
2729 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002730 }
2731
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002732 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002733 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002734 [](const auto& lhs, const auto& rhs) {
2735 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002736 });
2737
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002738 // Keep IDs if modes have not changed.
2739 const auto& modes = sameModes ? oldModes : newModes;
2740 const DisplayModePtr activeMode =
2741 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2742 return pair.second->getHwcId() == activeModeHwcId;
2743 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002744
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002745 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002746}
2747
Lloyd Piqueba04e622017-12-14 17:11:26 -08002748void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2749 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002750 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002751 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002752
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002754 continue;
2755 }
2756
Marin Shalamanova524a092020-07-27 21:39:55 +02002757 const auto displayId = info->id;
Dominik Laskowskieb627312022-04-07 09:13:16 -07002758 const auto token = mPhysicalDisplayTokens.get(displayId);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002759
Peiyong Line9d809e2020-04-14 13:10:48 -07002760 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002761 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002762
Dominik Laskowskieb627312022-04-07 09:13:16 -07002763 if (!token) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002764 ALOGV("Creating display %s", to_string(displayId).c_str());
2765
Dominik Laskowski075d3172018-05-24 15:50:06 -07002766 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002767 state.physical = {.id = displayId,
2768 .type = getHwComposer().getDisplayConnectionType(displayId),
2769 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002770 .deviceProductInfo = std::move(info->deviceProductInfo),
2771 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002772 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002773 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002774 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002775
2776 sp<IBinder> token = new BBinder();
2777 mCurrentState.displays.add(token, state);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002778 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002779 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002780 } else {
2781 ALOGV("Recreating display %s", to_string(displayId).c_str());
2782
Dominik Laskowskieb627312022-04-07 09:13:16 -07002783 auto& state = mCurrentState.displays.editValueFor(token->get());
2784 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
Marin Shalamanova903d032020-12-29 20:35:13 +01002785 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002786 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002787 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2788 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2789 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002790 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002791 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002792 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002793
Dominik Laskowskieb627312022-04-07 09:13:16 -07002794 if (const ssize_t index = mCurrentState.displays.indexOfKey(token->get()); index >= 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002795 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2796 mInterceptor->saveDisplayDeletion(state.sequenceId);
2797 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002798 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002799
2800 mPhysicalDisplayTokens.erase(displayId);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002801 }
2802
2803 processDisplayChangesLocked();
2804 }
2805
2806 mPendingHotplugEvents.clear();
2807}
2808
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002809void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002810 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2811 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002812 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2813 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002814}
2815
Lloyd Pique99d3da52018-01-22 17:48:03 -08002816sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002817 const wp<IBinder>& displayToken,
2818 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002819 const DisplayDeviceState& state,
2820 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002821 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002822 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002823 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002824 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002825 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002826 creationArgs.hasWideColorGamut = false;
2827 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002828
Dominik Laskowski55c85402020-01-21 16:25:47 -08002829 if (const auto& physical = state.physical) {
2830 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002831 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002832 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002833 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2834 getKernelIdleTimerProperties(compositionDisplay->getId());
2835
Ady Abraham3efa3942021-06-24 19:01:25 -07002836 scheduler::RefreshRateConfigs::Config config =
2837 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2838 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002839 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002840 .idleTimerTimeout = idleTimerTimeoutMs,
2841 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002842 creationArgs.refreshRateConfigs =
2843 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2844 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002845 }
2846
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002847 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002848 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002849
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002850 if (useColorManagement) {
2851 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2852 for (ColorMode colorMode : modes) {
2853 if (isWideColorMode(colorMode)) {
2854 creationArgs.hasWideColorGamut = true;
2855 }
2856
2857 std::vector<RenderIntent> renderIntents =
2858 getHwComposer().getRenderIntents(*id, colorMode);
2859 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002860 }
2861 }
tangrobin6753a022018-08-10 10:58:54 +08002862 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002863
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002864 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2865 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2866 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002867 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002868
Lloyd Pique90c115d2018-09-18 21:39:42 -07002869 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002870 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002871 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002872
Lloyd Pique99d3da52018-01-22 17:48:03 -08002873 // Make sure that composition can never be stalled by a virtual display
2874 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002875 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002876 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002877 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2878 }
2879
Dominik Laskowski718f9602019-11-09 20:01:35 -08002880 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002881 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2882 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002883
Lloyd Pique99d3da52018-01-22 17:48:03 -08002884 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002885 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002886
Lloyd Pique9370a482019-10-03 17:58:30 -07002887 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002888
Ady Abraham8565ad22021-06-22 17:45:44 -07002889 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002890
2891 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002892 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002893 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002894 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002895 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002896 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002897 display->getCompositionDisplay()->setColorProfile(
2898 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2899 RenderIntent::COLORIMETRIC,
2900 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002901 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002902 FTL_FAKE_GUARD(kMainThreadContext,
2903 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002904 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002905 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002906
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002907 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002908 display->setProjection(state.orientation, state.layerStackSpaceRect,
2909 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002910 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002911 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002912
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002913 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002914}
2915
Marin Shalamanovae685592020-02-12 17:12:22 +01002916void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2917 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002918 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002919 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2920 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002921 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002922 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2923 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002924 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002925 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002926 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002927 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002928 int format;
2929 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002930 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002931 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002932 } else {
2933 // Virtual displays without a surface are dormant:
2934 // they have external state (layer stack, projection,
2935 // etc.) but no internal state (i.e. a DisplayDevice).
2936 return;
2937 }
2938
2939 compositionengine::DisplayCreationArgsBuilder builder;
2940 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002941 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002942 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002943 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002944 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002945
Marin Shalamanov045b7002021-01-07 16:56:24 +01002946 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002947 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002948 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002949 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002950 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002951 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002952
2953 sp<compositionengine::DisplaySurface> displaySurface;
2954 sp<IGraphicBufferProducer> producer;
2955 sp<IGraphicBufferProducer> bqProducer;
2956 sp<IGraphicBufferConsumer> bqConsumer;
2957 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2958
Marin Shalamanovae685592020-02-12 17:12:22 +01002959 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002960 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2961 LOG_FATAL_IF(!displayId);
2962 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2963 bqProducer, bqConsumer, state.displayName);
2964 displaySurface = surface;
2965 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002966 } else {
2967 ALOGE_IF(state.surface != nullptr,
2968 "adding a supported display, but rendering "
2969 "surface is provided (%p), ignoring it",
2970 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002971 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2972 LOG_FATAL_IF(!displayId);
2973 displaySurface =
2974 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002975 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002976 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002977 producer = bqProducer;
2978 }
2979
Marin Shalamanov700e6392020-02-12 20:22:26 +01002980 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002981 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2982 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002983 if (display->isPrimary()) {
2984 initScheduler(display);
2985 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002986 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002987 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002988 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002989
2990 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01002991}
2992
2993void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002994 auto display = getDisplayDeviceLocked(displayToken);
2995 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002996 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002997
2998 if (display->isVirtual()) {
2999 releaseVirtualDisplay(display->getVirtualId());
3000 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003001 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01003002 }
3003 }
3004
3005 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08003006
3007 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07003008 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08003009 // Destroy the display without holding the mStateLock.
3010 // This is a temporary solution until we can manage transaction queues without
3011 // holding the mStateLock.
3012 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
3013 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
3014 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
3015 // ends up running on the main thread causing a deadlock since setTransactionstate
3016 // will try to acquire the mStateLock. Instead we extend the lifetime of
3017 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
3018 // The display will be disconnected and removed from the mDisplays list so it will
3019 // not be accessible.
3020 }));
3021 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003022}
3023
3024void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
3025 const DisplayDeviceState& currentState,
3026 const DisplayDeviceState& drawingState) {
3027 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3028 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003029
3030 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01003031 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02003032 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003033
Marin Shalamanovae685592020-02-12 17:12:22 +01003034 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3035 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003036 if (display->isVirtual()) {
3037 releaseVirtualDisplay(display->getVirtualId());
3038 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003039 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003040
Marin Shalamanovae685592020-02-12 17:12:22 +01003041 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003042
Marin Shalamanov700e6392020-02-12 20:22:26 +01003043 if (const auto& physical = currentState.physical) {
3044 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3045 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003046
Marin Shalamanovae685592020-02-12 17:12:22 +01003047 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003048
Marin Shalamanov700e6392020-02-12 20:22:26 +01003049 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003050 const auto display = getDisplayDeviceLocked(displayToken);
3051 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003052
3053 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003054 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003055 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003056 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003057 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003058 return;
3059 }
3060
3061 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3062 if (currentState.layerStack != drawingState.layerStack) {
3063 display->setLayerStack(currentState.layerStack);
3064 }
Evan Rosky2239b372021-05-20 13:43:47 -07003065 if (currentState.flags != drawingState.flags) {
3066 display->setFlags(currentState.flags);
3067 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003068 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003069 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3070 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3071 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3072 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003073 if (isDisplayActiveLocked(display)) {
3074 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003075 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003076 }
3077 if (currentState.width != drawingState.width ||
3078 currentState.height != drawingState.height) {
3079 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003080
Ady Abrahamed3290f2021-05-17 15:12:14 -07003081 if (isDisplayActiveLocked(display)) {
3082 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003083 }
3084 }
3085 }
3086}
Ady Abraham3efa3942021-06-24 19:01:25 -07003087void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003088 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003089 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003090 updatePhaseConfiguration(refreshRate);
3091 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003092}
Marin Shalamanovae685592020-02-12 17:12:22 +01003093
Lloyd Pique347200f2017-12-14 17:00:15 -08003094void SurfaceFlinger::processDisplayChangesLocked() {
3095 // here we take advantage of Vector's copy-on-write semantics to
3096 // improve performance by skipping the transaction entirely when
3097 // know that the lists are identical
3098 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3099 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3100 if (!curr.isIdenticalTo(draw)) {
3101 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003102
3103 // find the displays that were removed
3104 // (ie: in drawing state but not in current state)
3105 // also handle displays that changed
3106 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003107 for (size_t i = 0; i < draw.size(); i++) {
3108 const wp<IBinder>& displayToken = draw.keyAt(i);
3109 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003110 if (j < 0) {
3111 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003112 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003113 } else {
3114 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003115 const DisplayDeviceState& currentState = curr[j];
3116 const DisplayDeviceState& drawingState = draw[i];
3117 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003118 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003119 }
3120
3121 // find displays that were added
3122 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003123 for (size_t i = 0; i < curr.size(); i++) {
3124 const wp<IBinder>& displayToken = curr.keyAt(i);
3125 if (draw.indexOfKey(displayToken) < 0) {
3126 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003127 }
3128 }
3129 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003130
3131 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003132}
3133
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003134void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3135 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003136 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3137 if (displayTransactionNeeded) {
3138 processDisplayChangesLocked();
3139 processDisplayHotplugEventsLocked();
3140 }
Robert Carrb552ff52021-06-11 13:35:54 -07003141 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142
Robert Carre450fb52021-06-11 13:21:09 -07003143 if (mSomeChildrenChanged) {
3144 mVisibleRegionsDirty = true;
3145 mSomeChildrenChanged = false;
3146 }
3147
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003148 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003149 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003150 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003151 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003152 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003153 // the hint is set before we acquire a buffer from the surface texture.
3154 //
3155 // NOTE: layer transactions have taken place already, so we use their
3156 // drawing state. However, SurfaceFlinger's own transaction has not
3157 // happened yet, so we must use the current state layer list
3158 // (soon to become the drawing state list).
3159 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003160 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003161 ui::LayerStack layerStack;
3162
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003163 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003164 // NOTE: we rely on the fact that layers are sorted by
3165 // layerStack first (so we don't have to traverse the list
3166 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003167 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3168 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003169 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003170
3171 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003172 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003173 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3174 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003175 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003176
3177 // Pick the primary display if another display mirrors the layer.
3178 if (hintDisplay) {
3179 hintDisplay = nullptr;
3180 break;
3181 }
3182
3183 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003184 }
3185 }
Chet Haase91d25932013-04-11 15:24:55 -07003186
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003187 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003188 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3189 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003190
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003191 // could be null when this layer is using a layerStack
3192 // that is not visible on any display. Also can occur at
3193 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003194 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003195 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003196
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003197 layer->updateTransformHint(hintDisplay->getTransformHint());
Robert Carr2047fae2016-11-28 14:09:09 -08003198 });
Mathias Agopian84300952012-11-21 16:02:13 -08003199 }
3200
Robert Carr1f0a16a2016-10-24 16:27:39 -07003201 if (mLayersAdded) {
3202 mLayersAdded = false;
3203 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003204 mVisibleRegionsDirty = true;
3205 }
3206
3207 // some layers might have been removed, so
3208 // we need to update the regions they're exposing.
3209 if (mLayersRemoved) {
3210 mLayersRemoved = false;
3211 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003212 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003213 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003214 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003215 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003216 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003217 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003218 }
Robert Carr2047fae2016-11-28 14:09:09 -08003219 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 }
3221
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003222 doCommitTransactions();
3223 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3224 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003225}
3226
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003227void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003228 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003229 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003230 return;
3231 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003232
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003233 std::vector<WindowInfo> windowInfos;
3234 std::vector<DisplayInfo> displayInfos;
3235 bool updateWindowInfo = false;
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003236 if (mVisibleRegionsDirty || mInputInfoChanged) {
3237 mInputInfoChanged = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003238 updateWindowInfo = true;
3239 buildWindowInfos(windowInfos, displayInfos);
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003240 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003241 if (!updateWindowInfo && mInputWindowCommands.empty()) {
3242 return;
3243 }
3244 BackgroundExecutor::getInstance().execute([updateWindowInfo,
3245 windowInfos = std::move(windowInfos),
3246 displayInfos = std::move(displayInfos),
3247 inputWindowCommands =
3248 std::move(mInputWindowCommands),
3249 inputFlinger = mInputFlinger, this]() {
3250 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3251 if (updateWindowInfo) {
3252 mWindowInfosListenerInvoker->windowInfosChanged(windowInfos, displayInfos,
3253 inputWindowCommands.syncInputWindows);
3254 } else if (inputWindowCommands.syncInputWindows) {
3255 // If the caller requested to sync input windows, but there are no
3256 // changes to input windows, notify immediately.
3257 windowInfosReported();
3258 }
3259 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3260 inputFlinger->setFocusedWindow(focusRequest);
3261 }
3262 });
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003263
Arthur Hung6cbb9752019-09-05 16:38:18 +08003264 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003265}
3266
Alec Mouricdf16792021-12-10 13:16:06 -08003267void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3268 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3269 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3270 if (!supportsDisplayBrightnessCommand) {
3271 return;
3272 }
3273
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003274 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003275 if (const auto brightness = display->getStagedBrightness(); brightness) {
3276 if (!needsComposite) {
3277 const status_t error =
3278 getHwComposer()
3279 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003280 display->getCompositionDisplay()
3281 ->getState()
3282 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003283 Hwc2::Composer::DisplayBrightnessOptions{
3284 .applyImmediately = true})
3285 .get();
3286
3287 ALOGE_IF(error != NO_ERROR,
3288 "Error setting display brightness for display %s: %d (%s)",
3289 display->getDebugName().c_str(), error, strerror(error));
3290 }
3291 display->persistBrightness(needsComposite);
3292 }
3293 }
3294}
3295
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003296void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3297 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003298 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3299
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003300 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003301 const auto layerStack = display->getLayerStack();
3302 const auto info = display->getInputInfo();
3303
3304 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003305 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003306 continue;
3307 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003308
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003309 // If the layer stack is mirrored on multiple displays, the first display that is configured
3310 // to receive input takes precedence.
3311 auto& otherInfo = it->second;
3312 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003313 ALOGW_IF(display->receivesInput(),
3314 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003315 layerStack.id);
3316 } else {
3317 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003318 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003319 }
Robert Carr720e5062018-07-30 17:45:14 -07003320
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003321 static size_t sNumWindowInfos = 0;
3322 outWindowInfos.reserve(sNumWindowInfos);
3323 sNumWindowInfos = 0;
3324
Robert Carr720e5062018-07-30 17:45:14 -07003325 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003326 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003327
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003328 // Do not create WindowInfos for windows on displays that cannot receive input.
3329 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3330 const auto& info = opt->get();
3331 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003332 }
Robert Carr720e5062018-07-30 17:45:14 -07003333 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003334
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003335 sNumWindowInfos = outWindowInfos.size();
3336
3337 outDisplayInfos.reserve(displayInputInfos.size());
3338 for (const auto& [_, info] : displayInputInfos) {
3339 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003340 }
Robert Carr720e5062018-07-30 17:45:14 -07003341}
3342
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003343void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003344 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003345 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003346 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003347 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003348 }
3349 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003350
3351 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003352}
3353
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003354void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003355 // If this is called from the main thread mStateLock must be locked before
3356 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003357 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003358
3359 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003360
3361 const auto display = getDefaultDisplayDeviceLocked();
3362 if (!display || mBootStage != BootStage::FINISHED) {
3363 return;
3364 }
3365 ATRACE_CALL();
3366
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003367 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3368 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003369 return;
3370 }
3371
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003372 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003373}
3374
Ady Abraham62a0be22020-12-08 16:54:10 -08003375void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3376 PhysicalDisplayId displayId = [&]() {
3377 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3378 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3379 }();
3380
3381 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3382}
3383
Ady Abraham3efa3942021-06-24 19:01:25 -07003384void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003385 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003386 // If the scheduler is already initialized, this means that we received
3387 // a hotplug(connected) on the primary display. In that case we should
3388 // update the scheduler with the most recent display information.
3389 ALOGW("Scheduler already initialized, updating instead");
3390 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003391 return;
3392 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003393 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003394 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3395 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003396
Marin Shalamanova903d032020-12-29 20:35:13 +01003397 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003398 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003399
Dominik Laskowski068173d2021-08-11 17:22:59 -07003400 using Feature = scheduler::Feature;
3401 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003402
Dominik Laskowski068173d2021-08-11 17:22:59 -07003403 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3404 features |= Feature::kContentDetection;
3405 }
3406 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3407 features |= Feature::kTracePredictedVsync;
3408 }
3409 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003410 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003411 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003412 }
3413
Dominik Laskowski068173d2021-08-11 17:22:59 -07003414 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3415 static_cast<ISchedulerCallback&>(*this),
3416 features);
3417 {
3418 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003419 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003420 features |= Feature::kKernelIdleTimer;
3421 }
3422
3423 mScheduler->createVsyncSchedule(features);
3424 mScheduler->setRefreshRateConfigs(std::move(configs));
3425 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003426 setVsyncEnabled(false);
3427 mScheduler->startTimers();
3428
Ady Abraham9c53ee72020-07-22 21:16:18 -07003429 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003430 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003431 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003432 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003433 /*workDuration=*/configs.late.appWorkDuration,
3434 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003435 impl::EventThread::InterceptVSyncsCallback());
3436 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003437 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3438 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3439 /*readyDuration=*/configs.late.sfWorkDuration,
3440 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003441 mInterceptor->saveVSyncEvent(timestamp);
3442 });
3443
Dominik Laskowski756b7892021-08-04 12:53:59 -07003444 mScheduler->initVsync(mScheduler->getVsyncDispatch(), *mFrameTimeline->getTokenManager(),
3445 configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003446
3447 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003448 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003449 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003450 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003451 // initialization, so that the EventThreads always contain a reference to a
3452 // prior configuration.
3453 //
3454 // This is a bit hacky, but this avoids a back-pointer into the main SF
3455 // classes from EventThread, and there should be no run-time binder cost
3456 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003457 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003458}
3459
Marin Shalamanov5801c942020-12-17 17:00:13 +01003460void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3461 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003462 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003463 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003464}
3465
Ady Abraham55fa7272020-09-30 19:19:27 -07003466void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3467 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003468 mScheduler->setDuration(mAppConnectionHandle,
3469 /*workDuration=*/config.appWorkDuration,
3470 /*readyDuration=*/config.sfWorkDuration);
3471 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003472 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3473 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003474 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003475}
3476
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003477void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003478 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003479
Lloyd Pique58e24a32019-08-01 15:50:14 -07003480 if (!mLayersPendingRemoval.isEmpty()) {
3481 // Notify removed layers now that they can't be drawn from
3482 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003483 // Ensure any buffers set to display on any children are released.
3484 if (l->isRemovedFromCurrentState()) {
3485 l->latchAndReleaseBuffer();
3486 }
3487
chaviw6852bff2022-04-19 17:35:11 -05003488 // If a layer has a parent, we allow it to out-live it's handle
3489 // with the idea that the parent holds a reference and will eventually
3490 // be cleaned up. However no one cleans up the top-level so we do so
3491 // here.
3492 if (l->isAtRoot()) {
3493 l->setIsAtRoot(false);
3494 mCurrentState.layersSortedByZ.remove(l);
3495 }
3496
Lloyd Pique58e24a32019-08-01 15:50:14 -07003497 // If the layer has been removed and has no parent, then it will not be reachable
3498 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3499 // ensure we can copy its current to drawing state.
3500 if (!l->getParent()) {
3501 mOffscreenLayers.emplace(l.get());
3502 }
3503 }
3504 mLayersPendingRemoval.clear();
3505 }
3506
3507 // If this transaction is part of a window animation then the next frame
3508 // we composite should be considered an animation as well.
3509 mAnimCompositionPending = mAnimTransactionPending;
3510
3511 mDrawingState = mCurrentState;
3512 // clear the "changed" flags in current state
3513 mCurrentState.colorMatrixChanged = false;
3514
Robert Carra70e91c2021-06-11 13:59:52 -07003515 if (mVisibleRegionsDirty) {
3516 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3517 rootLayer->commitChildList();
3518 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003519 }
Robert Carra70e91c2021-06-11 13:59:52 -07003520
Lloyd Pique58e24a32019-08-01 15:50:14 -07003521 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003522 if (mNumClones > 0) {
3523 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3524 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003525}
3526
chaviw74d90ad2019-04-26 14:45:26 -07003527void SurfaceFlinger::commitOffscreenLayers() {
3528 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003529 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003530 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3531 layer->doTransaction(0);
3532 layer->commitChildList();
3533 }
chaviw74d90ad2019-04-26 14:45:26 -07003534 });
3535 }
3536}
3537
Chia-I Wuab0c3192017-08-01 11:29:00 -07003538void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003539 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003540 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003541 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003542 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003543 }
3544 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003545}
3546
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003547bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003548 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003549
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003550 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003551
Mathias Agopian4fec8732012-06-29 14:12:52 -07003552 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003553 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003554 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003555
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003556 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3557
Eric Penner51c59cd2014-07-28 19:51:58 -07003558 // Store the set of layers that need updates. This set must not change as
3559 // buffers are being latched, as this could result in a deadlock.
3560 // Example: Two producers share the same command stream and:
3561 // 1.) Layer 0 is latched
3562 // 2.) Layer 0 gets a new frame
3563 // 2.) Layer 1 gets a new frame
3564 // 3.) Layer 1 is latched.
3565 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3566 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003567 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003568 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3569 const uint32_t flags = layer->doTransaction(0);
3570 if (flags & Layer::eVisibleRegion) {
3571 mVisibleRegionsDirty = true;
3572 }
3573 }
Robert Carrb552ff52021-06-11 13:35:54 -07003574
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003575 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003576 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003577 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003578 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003579 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003580 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003581 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003582 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003583 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003584 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003585 }
Robert Carr2047fae2016-11-28 14:09:09 -08003586 });
Robert Carrb552ff52021-06-11 13:35:54 -07003587 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003588
chaviw49a108c2019-08-12 11:23:06 -07003589 // The client can continue submitting buffers for offscreen layers, but they will not
3590 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3591 // layers to ensure dequeueBuffer doesn't block indefinitely.
3592 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003593 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003594 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3595 }
3596
Lloyd Piquef2c79392018-12-20 16:23:33 -08003597 if (!mLayersWithQueuedFrames.empty()) {
3598 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3599 // writes to Layer current state. See also b/119481871
3600 Mutex::Autolock lock(mStateLock);
3601
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003602 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003603 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003604 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003605 newDataLatched = true;
3606 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003607 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003608 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003609 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003610
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003611 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003612
3613 // If we will need to wake up at some time in the future to deal with a
3614 // queued frame that shouldn't be displayed during this vsync period, wake
3615 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003616 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003617 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003618 }
3619
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003620 // enter boot animation on first buffer latch
3621 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3622 ALOGI("Enter boot animation");
3623 mBootStage = BootStage::BOOTANIMATION;
3624 }
3625
Robert Carr6a0382d2021-07-01 15:57:17 -07003626 if (mNumClones > 0) {
3627 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3628 }
chaviw74b03172019-08-19 11:09:03 -07003629
Dan Stoza6b9454d2014-11-07 16:00:59 -08003630 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003631 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632}
3633
Robert Carrc0df3122019-04-11 13:18:21 -07003634status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003635 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003636 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003637 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003638 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003639 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003640 static_cast<void>(mScheduler->schedule([=] {
3641 ALOGE("Dumping random sampling of on-screen layers: ");
3642 mDrawingState.traverse([&](Layer *layer) {
3643 // Aim to dump about 200 layers to avoid totally trashing
3644 // logcat. On the other hand, if there really are 4096 layers
3645 // something has gone totally wrong its probably the most
3646 // useful information in logcat.
3647 if (rand() % 20 == 13) {
3648 ALOGE("Layer: %s", layer->getName().c_str());
3649 }
3650 });
3651 for (Layer* offscreenLayer : mOffscreenLayers) {
3652 if (rand() % 20 == 13) {
3653 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3654 }
3655 }
3656 }));
arthurhungdba591c2021-02-08 17:28:49 +08003657 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003658 }
3659
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003660 {
3661 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3662 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3663 }
arthurhungdba591c2021-02-08 17:28:49 +08003664
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003665 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003666 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003667 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003668 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003669 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003670 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003671 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003672 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003673
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003674 setTransactionFlags(eTransactionNeeded);
3675 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003676}
3677
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003678uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003679 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003680}
3681
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003682uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3683 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003684}
3685
Dominik Laskowski94000c42022-03-17 12:55:14 -07003686void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003687 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003688 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003689
3690 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003691 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003692 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003693}
3694
Ady Abraham9dada822022-02-03 10:26:59 -08003695bool SurfaceFlinger::stopTransactionProcessing(
3696 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3697 applyTokensWithUnsignaledTransactions) const {
3698 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3699 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3700 // then we should have only one applyToken for processing.
3701 // so we can stop further transactions on this applyToken.
3702 return !applyTokensWithUnsignaledTransactions.empty();
3703 }
3704
3705 return false;
3706}
3707
ramindani9eff2492022-03-23 00:28:26 +00003708int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3709 std::vector<TransactionState>& transactions,
3710 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3711 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3712 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3713 applyTokensWithUnsignaledTransactions,
3714 /*tryApplyUnsignaled*/ true);
3715}
3716
Robert Carr79dc06a2022-02-22 15:28:59 -08003717int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003718 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003719 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003720 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3721 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003722 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003723 auto it = mPendingTransactionQueues.begin();
3724 while (it != mPendingTransactionQueues.end()) {
3725 auto& [applyToken, transactionQueue] = *it;
3726 while (!transactionQueue.empty()) {
3727 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3728 ATRACE_NAME("stopTransactionProcessing");
3729 break;
3730 }
3731
3732 auto& transaction = transactionQueue.front();
3733 const auto ready =
Robert Carr4c1b6462021-12-21 10:30:50 -08003734 transactionIsReadyToBeApplied(transaction,
3735 transaction.frameTimelineInfo,
3736 transaction.isAutoTimestamp,
3737 transaction.desiredPresentTime,
3738 transaction.originUid, transaction.states,
3739 bufferLayersReadyToPresent, transactions.size(),
3740 tryApplyUnsignaled);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003741 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3742 if (ready == TransactionReadiness::NotReady) {
3743 setTransactionFlags(eTransactionFlushNeeded);
3744 break;
3745 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003746 if (ready == TransactionReadiness::NotReadyBarrier) {
3747 transactionsPendingBarrier++;
3748 setTransactionFlags(eTransactionFlushNeeded);
3749 break;
3750 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003751 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003752 const bool frameNumberChanged = state.bufferData->flags.test(
3753 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003754 if (frameNumberChanged) {
3755 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3756 } else {
3757 // Barrier function only used for BBQ which always includes a frame number
3758 bufferLayersReadyToPresent[state.surface] =
3759 std::numeric_limits<uint64_t>::max();
3760 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003761 });
3762 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3763 if (appliedUnsignaled) {
3764 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3765 }
3766
3767 transactions.emplace_back(std::move(transaction));
3768 transactionQueue.pop();
3769 }
3770
3771 if (transactionQueue.empty()) {
3772 it = mPendingTransactionQueues.erase(it);
3773 mTransactionQueueCV.broadcast();
3774 } else {
3775 it = std::next(it, 1);
3776 }
3777 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003778 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003779}
3780
Vishnu Nair7891e962021-11-11 12:07:21 -08003781bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003782 // to prevent onHandleDestroyed from being called while the lock is held,
3783 // we must keep a copy of the transactions (specifically the composer
3784 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003785 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003786 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003787 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003788 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003789 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003790 Mutex::Autolock _l(mStateLock);
3791 {
3792 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003793
Robert Carr79dc06a2022-02-22 15:28:59 -08003794 int lastTransactionsPendingBarrier = 0;
3795 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003796 // First collect transactions from the pending transaction queues.
3797 // We are not allowing unsignaled buffers here as we want to
3798 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003799 transactionsPendingBarrier =
3800 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3801 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003802
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003803 // Second, collect transactions from the transaction queue.
3804 // Here as well we are not allowing unsignaled buffers for the same
3805 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003806 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003807 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003808 const bool pendingTransactions =
3809 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003810 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003811 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003812 if (pendingTransactions) {
3813 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003814 return TransactionReadiness::NotReady;
3815 }
3816
Robert Carr4c1b6462021-12-21 10:30:50 -08003817 return transactionIsReadyToBeApplied(transaction, transaction.frameTimelineInfo,
Ady Abraham9dada822022-02-03 10:26:59 -08003818 transaction.isAutoTimestamp,
3819 transaction.desiredPresentTime,
3820 transaction.originUid, transaction.states,
3821 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003822 transactions.size(),
3823 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003824 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003825 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003826 if (ready != TransactionReadiness::Ready) {
3827 if (ready == TransactionReadiness::NotReadyBarrier) {
3828 transactionsPendingBarrier++;
3829 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003830 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003831 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003832 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003833 const bool frameNumberChanged = state.bufferData->flags.test(
3834 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003835 if (frameNumberChanged) {
3836 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3837 } else {
3838 // Barrier function only used for BBQ which always includes a frame number.
3839 // This value only used for barrier logic.
3840 bufferLayersReadyToPresent[state.surface] =
3841 std::numeric_limits<uint64_t>::max();
3842 }
Xiang Wang76236e12022-03-22 17:25:30 +00003843 });
Ady Abraham9dada822022-02-03 10:26:59 -08003844 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003845 }
ramindani4d48f902021-09-20 21:07:45 +00003846 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003847 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003848 }
Arthur Hung58144272021-01-16 03:43:53 +00003849
Robert Carr79dc06a2022-02-22 15:28:59 -08003850 // Transactions with a buffer pending on a barrier may be on a different applyToken
3851 // than the transaction which satisfies our barrier. In fact this is the exact use case
3852 // that the primitive is designed for. This means we may first process
3853 // the barrier dependent transaction, determine it ineligible to complete
3854 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3855 // The barrier dependent transaction was eligible to be presented in this frame
3856 // but we would have prevented it without case. To fix this we continually
3857 // loop through flushPendingTransactionQueues until we perform an iteration
3858 // where the number of transactionsPendingBarrier doesn't change. This way
3859 // we can continue to resolve dependency chains of barriers as far as possible.
3860 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3861 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3862 transactionsPendingBarrier =
3863 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3864 applyTokensWithUnsignaledTransactions,
3865 /*tryApplyUnsignaled*/ false);
3866 }
3867
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003868 // We collected all transactions that could apply without latching unsignaled buffers.
3869 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3870 // transactions that were not applied and try to apply them unsignaled.
3871 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003872 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3873 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003874 }
3875
Vishnu Nair7891e962021-11-11 12:07:21 -08003876 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003877 }
ramindani4d48f902021-09-20 21:07:45 +00003878 }
3879}
3880
Vishnu Nair7891e962021-11-11 12:07:21 -08003881bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3882 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003883 bool needsTraversal = false;
3884 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003885 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003886 needsTraversal |=
3887 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3888 transaction.displays, transaction.flags,
3889 transaction.inputWindowCommands,
3890 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3891 transaction.buffer, transaction.postTime,
3892 transaction.permissions, transaction.hasListenerCallbacks,
3893 transaction.listenerCallbacks, transaction.originPid,
3894 transaction.originUid, transaction.id);
3895 if (transaction.transactionCommittedSignal) {
3896 mTransactionCommittedSignals.emplace_back(
3897 std::move(transaction.transactionCommittedSignal));
3898 }
3899 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003900
Dominik Laskowski46471e62022-01-14 15:34:03 -08003901 if (mTransactionTracing) {
3902 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003903 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003904 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003905}
3906
3907bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003908 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003909 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003910}
3911
Ady Abraham8db10102021-03-15 17:19:23 -07003912bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3913 // The amount of time SF can delay a frame if it is considered early based
3914 // on the VsyncModulator::VsyncConfig::appWorkDuration
3915 constexpr static std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3916
3917 const auto currentVsyncPeriod = mScheduler->getDisplayStatInfo(systemTime()).vsyncPeriod;
3918 const auto earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
3919
3920 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3921 if (!prediction.has_value()) {
3922 return false;
3923 }
3924
3925 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3926 kEarlyLatchMaxThreshold.count()) {
3927 return false;
3928 }
3929
3930 return prediction->presentTime >= expectedPresentTime &&
3931 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3932}
Ady Abraham9dada822022-02-03 10:26:59 -08003933bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003934 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003935 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3936 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3937 return false;
3938 }
Ady Abraham8db10102021-03-15 17:19:23 -07003939
Ady Abraham9dada822022-02-03 10:26:59 -08003940 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3941 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3942 return true;
3943 }
3944
3945 // We only want to latch unsignaled when a single layer is updated in this
3946 // transaction (i.e. not a blast sync transaction).
3947 if (numStates != 1) {
3948 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3949 return false;
3950 }
3951
Ady Abraham2739e832022-02-14 17:42:00 -08003952 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3953 if (totalTXapplied > 0) {
3954 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3955 __func__, totalTXapplied);
3956 return false;
3957 }
3958
3959 // We don't want to latch unsignaled if are in early / client composition
3960 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3961 // or window animations being slow.
3962 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3963 if (!isDefaultVsyncConfig) {
3964 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3965 __func__);
3966 return false;
3967 }
Ady Abraham9dada822022-02-03 10:26:59 -08003968 }
3969
3970 if (!layer->simpleBufferUpdate(state)) {
3971 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3972 return false;
3973 }
3974
3975 ALOGV("%s: true", __func__);
3976 return true;
3977}
3978
Robert Carr4c1b6462021-12-21 10:30:50 -08003979auto SurfaceFlinger::transactionIsReadyToBeApplied(TransactionState& transaction,
Ady Abraham43752eb2021-03-04 16:24:25 -08003980 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003981 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003982 const std::unordered_map<
3983 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003984 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003985 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003986 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003987 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3988 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003989 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08003990 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003991 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003992 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003993 }
3994
Ady Abraham5690bda2021-03-12 15:01:18 -08003995 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
3996 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003997 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003998 }
3999
Ady Abraham8db10102021-03-15 17:19:23 -07004000 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
4001 // present time of this transaction.
4002 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
4003 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08004004 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07004005 }
4006
Ady Abraham9dada822022-02-03 10:26:59 -08004007 bool fenceUnsignaled = false;
Robert Carr4c1b6462021-12-21 10:30:50 -08004008 auto queueProcessTime = systemTime();
Marissa Wall713b63f2018-10-17 15:42:43 -07004009 for (const ComposerState& state : states) {
4010 const layer_state_t& s = state.state;
Robert Carr4c1b6462021-12-21 10:30:50 -08004011
Ady Abrahamf20c1922020-12-21 18:39:01 -08004012 sp<Layer> layer = nullptr;
4013 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07004014 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004015 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08004016 ALOGW("Transaction with buffer, but no Layer?");
4017 continue;
4018 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08004019 if (!layer) {
4020 continue;
4021 }
Ady Abraham43752eb2021-03-04 16:24:25 -08004022
Robert Carr79dc06a2022-02-22 15:28:59 -08004023 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
4024 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
4025 const bool willApplyBarrierFrame =
4026 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
4027 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
4028 if (!willApplyBarrierFrame) {
4029 ATRACE_NAME("NotReadyBarrier");
4030 return TransactionReadiness::NotReadyBarrier;
4031 }
4032 }
4033
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004034 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08004035 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08004036 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
4037 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08004038
4039 const bool acquireFenceChanged = s.bufferData &&
4040 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
4041 s.bufferData->acquireFence;
4042 fenceUnsignaled = fenceUnsignaled ||
4043 (acquireFenceChanged &&
4044 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
4045
4046 if (fenceUnsignaled && !allowLatchUnsignaled) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004047 if (!transaction.sentFenceTimeoutWarning &&
4048 queueProcessTime - transaction.queueTime > std::chrono::nanoseconds(4s).count()) {
4049 transaction.sentFenceTimeoutWarning = true;
4050 auto listener = s.bufferData->releaseBufferListener;
4051 if (listener) {
4052 listener->onTransactionQueueStalled();
4053 }
4054 }
4055
Ady Abraham9dada822022-02-03 10:26:59 -08004056 ATRACE_NAME("fence unsignaled");
4057 return TransactionReadiness::NotReady;
4058 }
4059
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004060 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08004061 // If backpressure is enabled and we already have a buffer to commit, keep the
4062 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004063 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4064 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004065 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004066 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004067 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004068 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004069 }
4070 }
Ady Abraham9dada822022-02-03 10:26:59 -08004071 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004072}
4073
arthurhungf1b7c7b2021-03-03 17:42:23 +08004074void SurfaceFlinger::queueTransaction(TransactionState& state) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004075 state.queueTime = systemTime();
4076
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004077 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004078
arthurhungf1b7c7b2021-03-03 17:42:23 +08004079 // Generate a CountDownLatch pending state if this is a synchronous transaction.
4080 if ((state.flags & eSynchronous) || state.inputWindowCommands.syncInputWindows) {
4081 state.transactionCommittedSignal = std::make_shared<CountDownLatch>(
Arthur Hung2274a312021-04-28 15:13:06 +00004082 (state.inputWindowCommands.syncInputWindows
4083 ? (CountDownLatch::eSyncInputWindows | CountDownLatch::eSyncTransaction)
4084 : CountDownLatch::eSyncTransaction));
arthurhungf1b7c7b2021-03-03 17:42:23 +08004085 }
4086
ramindani4d48f902021-09-20 21:07:45 +00004087 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004088 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4089
Ady Abrahame46243a2021-02-23 19:33:49 -08004090 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004091 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4092 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004093 return TransactionSchedule::Late;
4094 }(state.flags);
4095
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004096 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4097
4098 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004099}
4100
arthurhungf1b7c7b2021-03-03 17:42:23 +08004101void SurfaceFlinger::waitForSynchronousTransaction(
4102 const CountDownLatch& transactionCommittedSignal) {
4103 // applyTransactionState is called on the main SF thread. While a given process may wish
4104 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4105 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004106 if (!transactionCommittedSignal.wait_until(
4107 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004108 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004109 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004110}
Ady Abrahame46243a2021-02-23 19:33:49 -08004111
Arthur Hung2274a312021-04-28 15:13:06 +00004112void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004113 for (auto it = mTransactionCommittedSignals.begin();
4114 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004115 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004116 it = mTransactionCommittedSignals.erase(it);
4117 } else {
4118 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004119 }
4120 }
4121}
4122
chaviw308ddba2020-08-11 16:23:51 -07004123status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004124 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004125 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4126 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004127 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004128 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004129 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004130
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004131 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004132 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4133 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004134 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4135 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004136 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004137 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004138 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004139 }
4140
Leon Scroggins9a20f722021-12-28 14:43:12 +00004141 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004142 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004143 }
4144
Robert Carrde6d7b42022-01-07 18:23:06 -08004145 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004146 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4147 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4148 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004149 }
4150
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004151 const int64_t postTime = systemTime();
4152
4153 IPCThreadState* ipc = IPCThreadState::self();
4154 const int originPid = ipc->getCallingPid();
4155 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004156 TransactionState state{frameTimelineInfo, states,
4157 displays, flags,
4158 applyToken, inputWindowCommands,
4159 desiredPresentTime, isAutoTimestamp,
4160 uncacheBuffer, postTime,
4161 permissions, hasListenerCallbacks,
4162 listenerCallbacks, originPid,
4163 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004164
4165 // Check for incoming buffer updates and increment the pending buffer count.
4166 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4167 mBufferCountTracker.increment(state.surface->localBinder());
4168 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004169
Dominik Laskowski46471e62022-01-14 15:34:03 -08004170 if (mTransactionTracing) {
4171 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004172 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004173 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004174
arthurhungf1b7c7b2021-03-03 17:42:23 +08004175 // Check the pending state to make sure the transaction is synchronous.
4176 if (state.transactionCommittedSignal) {
4177 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004178 }
4179
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004180 return NO_ERROR;
4181}
Marissa Wall713b63f2018-10-17 15:42:43 -07004182
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004183bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004184 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004185 const Vector<DisplayState>& displays, uint32_t flags,
4186 const InputWindowCommands& inputWindowCommands,
4187 const int64_t desiredPresentTime, bool isAutoTimestamp,
4188 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004189 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004190 bool hasListenerCallbacks,
4191 const std::vector<ListenerCallbacks>& listenerCallbacks,
4192 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004193 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004194 for (const DisplayState& display : displays) {
4195 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004196 }
4197
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004198 // start and end registration for listeners w/ no surface so they can get their callback. Note
4199 // that listeners with SurfaceControls will start registration during setClientStateLocked
4200 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004201 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004202 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004203 }
4204
Marissa Walle2ffb422018-10-12 11:33:52 -07004205 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004206 for (int i = 0; i < states.size(); i++) {
4207 ComposerState& state = states.editItemAt(i);
4208 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004209 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004210 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004211 if (const auto layer = fromHandle(state.state.surface).promote()) {
4212 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004213 mScheduler->recordLayerHistory(layer.get(),
4214 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004215 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004216 }
4217 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004218 }
4219
Marissa Walle2ffb422018-10-12 11:33:52 -07004220 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004221
Robert Carrde6d7b42022-01-07 18:23:06 -08004222 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004223 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4224 } else if (!inputWindowCommands.empty()) {
4225 ALOGE("Only privileged callers are allowed to send input commands.");
4226 }
chaviw273171b2018-12-26 11:46:30 -08004227
Marissa Wall947d34e2019-03-29 14:03:53 -07004228 if (uncacheBuffer.isValid()) {
4229 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004230 }
4231
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004232 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4233 // anyway. This can be used as a flush mechanism for previous async transactions.
4234 // Empty animation transaction can be used to simulate back-pressure, so also force a
4235 // transaction for empty animation transactions.
4236 if (transactionFlags == 0 &&
4237 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004238 transactionFlags = eTransactionNeeded;
4239 }
4240
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004241 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004242 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004243 if (mInterceptor->isEnabled()) {
4244 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004245 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004246 }
4247
Arthur Hung58144272021-01-16 03:43:53 +00004248 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4249 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4250 if (transactionFlags & eTraversalNeeded) {
4251 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004252 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004253 }
Arthur Hung58144272021-01-16 03:43:53 +00004254 if (transactionFlags) {
4255 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004256 }
4257
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004258 if (flags & eAnimation) {
4259 mAnimTransactionPending = true;
4260 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004261 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004262
4263 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004264}
4265
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004266uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4267 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4268 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004269
Mathias Agopiane57f2922012-08-09 16:29:12 -07004270 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004271 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4272
4273 const uint32_t what = s.what;
4274 if (what & DisplayState::eSurfaceChanged) {
4275 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4276 state.surface = s.surface;
4277 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004278 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004279 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004280 if (what & DisplayState::eLayerStackChanged) {
4281 if (state.layerStack != s.layerStack) {
4282 state.layerStack = s.layerStack;
4283 flags |= eDisplayTransactionNeeded;
4284 }
4285 }
Evan Rosky2239b372021-05-20 13:43:47 -07004286 if (what & DisplayState::eFlagsChanged) {
4287 if (state.flags != s.flags) {
4288 state.flags = s.flags;
4289 flags |= eDisplayTransactionNeeded;
4290 }
4291 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004292 if (what & DisplayState::eDisplayProjectionChanged) {
4293 if (state.orientation != s.orientation) {
4294 state.orientation = s.orientation;
4295 flags |= eDisplayTransactionNeeded;
4296 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004297 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4298 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004299 flags |= eDisplayTransactionNeeded;
4300 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004301 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4302 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004303 flags |= eDisplayTransactionNeeded;
4304 }
4305 }
4306 if (what & DisplayState::eDisplaySizeChanged) {
4307 if (state.width != s.width) {
4308 state.width = s.width;
4309 flags |= eDisplayTransactionNeeded;
4310 }
4311 if (state.height != s.height) {
4312 state.height = s.height;
4313 flags |= eDisplayTransactionNeeded;
4314 }
4315 }
4316
Mathias Agopiane57f2922012-08-09 16:29:12 -07004317 return flags;
4318}
4319
Steven Thomasd4071902020-03-24 16:02:53 -07004320bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004321 IPCThreadState* ipc = IPCThreadState::self();
4322 const int pid = ipc->getCallingPid();
4323 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004324 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004325 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4326 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004327 return false;
4328 }
4329 return true;
4330}
4331
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004332uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004333 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004334 int64_t desiredPresentTime, bool isAutoTimestamp,
4335 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004336 layer_state_t& s = composerState.state;
4337 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004338
4339 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004340 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004341 // Starts a registration but separates the callback ids according to callback type. This
4342 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004343 // note that startRegistration will not re-register if the listener has
4344 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004345
4346 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4347 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004348 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004349 }
4350
4351 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4352 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004353 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004354 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004355 }
4356
arthurhungdba591c2021-02-08 17:28:49 +08004357 const uint64_t what = s.what;
4358 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004359 sp<Layer> layer = nullptr;
4360 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004361 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004362 } else {
4363 // The client may provide us a null handle. Treat it as if the layer was removed.
4364 ALOGW("Attempt to set client state with a null layer handle");
4365 }
chaviw8b3871a2017-11-01 17:41:01 -07004366 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004367 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004368 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004369 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004370 }
chaviw8b3871a2017-11-01 17:41:01 -07004371 return 0;
4372 }
4373
Valerie Hau871d6352020-01-29 08:44:02 -08004374 // Only set by BLAST adapter layers
4375 if (what & layer_state_t::eProducerDisconnect) {
4376 layer->onDisconnect();
4377 }
4378
chaviw8b3871a2017-11-01 17:41:01 -07004379 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004380 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004381 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004382 }
chaviw8b3871a2017-11-01 17:41:01 -07004383 }
4384 if (what & layer_state_t::eLayerChanged) {
4385 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004386 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004387 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004388 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004389 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004390 mCurrentState.layersSortedByZ.removeAt(idx);
4391 mCurrentState.layersSortedByZ.add(layer);
4392 // we need traversal (state changed)
4393 // AND transaction (list changed)
4394 flags |= eTransactionNeeded|eTraversalNeeded;
4395 }
chaviw8b3871a2017-11-01 17:41:01 -07004396 } else {
4397 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004398 flags |= eTransactionNeeded|eTraversalNeeded;
4399 }
4400 }
chaviw8b3871a2017-11-01 17:41:01 -07004401 }
4402 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004403 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004404 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004405 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4406 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004407 if (p == nullptr) {
4408 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004409 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004410 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004411 mCurrentState.layersSortedByZ.removeAt(idx);
4412 mCurrentState.layersSortedByZ.add(layer);
4413 // we need traversal (state changed)
4414 // AND transaction (list changed)
4415 flags |= eTransactionNeeded|eTraversalNeeded;
4416 }
4417 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004418 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004419 flags |= eTransactionNeeded|eTraversalNeeded;
4420 }
chaviw8b3871a2017-11-01 17:41:01 -07004421 }
4422 }
4423 if (what & layer_state_t::eSizeChanged) {
4424 if (layer->setSize(s.w, s.h)) {
4425 flags |= eTraversalNeeded;
4426 }
4427 }
4428 if (what & layer_state_t::eAlphaChanged) {
4429 if (layer->setAlpha(s.alpha))
4430 flags |= eTraversalNeeded;
4431 }
4432 if (what & layer_state_t::eColorChanged) {
4433 if (layer->setColor(s.color))
4434 flags |= eTraversalNeeded;
4435 }
Peiyong Lind3788632018-09-18 16:01:31 -07004436 if (what & layer_state_t::eColorTransformChanged) {
4437 if (layer->setColorTransform(s.colorTransform)) {
4438 flags |= eTraversalNeeded;
4439 }
4440 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004441 if (what & layer_state_t::eBackgroundColorChanged) {
4442 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4443 flags |= eTraversalNeeded;
4444 }
4445 }
chaviw8b3871a2017-11-01 17:41:01 -07004446 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004447 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004448 }
4449 if (what & layer_state_t::eTransparentRegionChanged) {
4450 if (layer->setTransparentRegionHint(s.transparentRegion))
4451 flags |= eTraversalNeeded;
4452 }
4453 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004454 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004455 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004456 if (what & layer_state_t::eCornerRadiusChanged) {
4457 if (layer->setCornerRadius(s.cornerRadius))
4458 flags |= eTraversalNeeded;
4459 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004460 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004461 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4462 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004463 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004464 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4465 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004466 if (what & layer_state_t::eRenderBorderChanged) {
Tianhao Yao10cea3c2022-03-30 01:37:22 +00004467 if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00004468 flags |= eTraversalNeeded;
4469 }
4470 }
chaviw8b3871a2017-11-01 17:41:01 -07004471 if (what & layer_state_t::eLayerStackChanged) {
4472 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4473 // We only allow setting layer stacks for top level layers,
4474 // everything else inherits layer stack from its parent.
4475 if (layer->hasParent()) {
4476 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004477 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004478 } else if (idx < 0) {
4479 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004480 "that also does not appear in the top level layer list. Something"
4481 " has gone wrong.",
4482 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004483 } else if (layer->setLayerStack(s.layerStack)) {
4484 mCurrentState.layersSortedByZ.removeAt(idx);
4485 mCurrentState.layersSortedByZ.add(layer);
4486 // we need traversal (state changed)
4487 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004488 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004489 }
4490 }
Marissa Wall61c58622018-07-18 10:12:20 -07004491 if (what & layer_state_t::eTransformChanged) {
4492 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4493 }
4494 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4495 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4496 flags |= eTraversalNeeded;
4497 }
4498 if (what & layer_state_t::eCropChanged) {
4499 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4500 }
Marissa Wall61c58622018-07-18 10:12:20 -07004501 if (what & layer_state_t::eDataspaceChanged) {
4502 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4503 }
4504 if (what & layer_state_t::eHdrMetadataChanged) {
4505 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4506 }
4507 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4508 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4509 }
4510 if (what & layer_state_t::eApiChanged) {
4511 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4512 }
4513 if (what & layer_state_t::eSidebandStreamChanged) {
4514 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4515 }
Robert Carr720e5062018-07-30 17:45:14 -07004516 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004517 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4518 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004519 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004520 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004521 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004522 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004523
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004524 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4525 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004526 // The transaction will be received on the Task layer and needs to be applied to all
4527 // child layers. Child layers that are added at a later point will obtain the game mode
4528 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004529 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004530 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004531
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004532 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4533 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004534 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4535 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4536 flags |= eTraversalNeeded;
4537 }
4538 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004539 if (what & layer_state_t::eShadowRadiusChanged) {
4540 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4541 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004542 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004543 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004544 flags |= eTraversalNeeded;
4545 }
4546 }
Steven Thomas3172e202020-01-06 19:25:30 -08004547 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004548 const auto compatibility =
4549 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4550 const auto strategy =
4551 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004552
Robert Carrde6d7b42022-01-07 18:23:06 -08004553 if (layer->setFrameRate(
4554 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4555 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004556 }
Steven Thomas3172e202020-01-06 19:25:30 -08004557 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004558 if (what & layer_state_t::eFixedTransformHintChanged) {
4559 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4560 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4561 }
4562 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004563 if (what & layer_state_t::eAutoRefreshChanged) {
4564 layer->setAutoRefresh(s.autoRefresh);
4565 }
Sally Qi421ffb02022-03-21 19:41:33 -07004566 if (what & layer_state_t::eDimmingEnabledChanged) {
4567 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4568 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004569 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004570 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4571 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004572 }
4573 }
John Reckcdb4ed72021-02-04 13:39:33 -05004574 if (what & layer_state_t::eStretchChanged) {
4575 if (layer->setStretchEffect(s.stretchEffect)) {
4576 flags |= eTraversalNeeded;
4577 }
4578 }
chaviwf3f40fe2021-04-27 15:54:02 -05004579 if (what & layer_state_t::eBufferCropChanged) {
4580 if (layer->setBufferCrop(s.bufferCrop)) {
4581 flags |= eTraversalNeeded;
4582 }
4583 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004584 if (what & layer_state_t::eDestinationFrameChanged) {
4585 if (layer->setDestinationFrame(s.destinationFrame)) {
4586 flags |= eTraversalNeeded;
4587 }
4588 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004589 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004590 if (layer->setDropInputMode(s.dropInputMode)) {
4591 flags |= eTraversalNeeded;
4592 mInputInfoChanged = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004593 }
4594 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004595 // This has to happen after we reparent children because when we reparent to null we remove
4596 // child layers from current state and remove its relative z. If the children are reparented in
4597 // the same transaction, then we have to make sure we reparent the children first so we do not
4598 // lose its relative z order.
4599 if (what & layer_state_t::eReparent) {
4600 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004601 auto parentHandle = (s.parentSurfaceControlForChild)
4602 ? s.parentSurfaceControlForChild->getHandle()
4603 : nullptr;
4604 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004605 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004606 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004607 mCurrentState.layersSortedByZ.remove(layer);
4608 }
4609 flags |= eTransactionNeeded | eTraversalNeeded;
4610 }
4611 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004612 std::vector<sp<CallbackHandle>> callbackHandles;
4613 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4614 for (auto& [listener, callbackIds] : filteredListeners) {
4615 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4616 }
4617 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004618
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004619 if (what & layer_state_t::eBufferChanged) {
4620 std::shared_ptr<renderengine::ExternalTexture> buffer =
4621 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4622 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4623 dequeueBufferTimestamp, frameTimelineInfo)) {
4624 flags |= eTraversalNeeded;
4625 }
Ady Abraham8db10102021-03-15 17:19:23 -07004626 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4627 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004628 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004629
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004630 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004631 // Do not put anything that updates layer state or modifies flags after
4632 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004633 return flags;
4634}
4635
chaviw273171b2018-12-26 11:46:30 -08004636uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004637 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004638 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004639}
4640
Vishnu Nair84125ac2021-12-02 08:47:48 -08004641status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4642 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4643 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004644 if (!mirrorFromHandle) {
4645 return NAME_NOT_FOUND;
4646 }
4647
4648 sp<Layer> mirrorLayer;
4649 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004650 {
4651 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004652 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004653 if (!mirrorFrom) {
4654 return NAME_NOT_FOUND;
4655 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004656 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004657 if (result != NO_ERROR) {
4658 return result;
4659 }
4660
Robert Carr6a0382d2021-07-01 15:57:17 -07004661 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004662 }
4663
Ady Abraham9f0a4002020-10-05 15:47:26 -07004664 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004665 if (mTransactionTracing) {
4666 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4667 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004668 }
4669 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004670 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004671}
4672
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004673status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004674 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4675 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004676 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4677 "Expected only one of parentLayer or parentHandle to be non-null. "
4678 "Programmer error?");
4679
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004680 status_t result = NO_ERROR;
4681
4682 sp<Layer> layer;
4683
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004684 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004685 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004686 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004687 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004688 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4689 if (pendingBufferCounter) {
4690 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004691 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004692 pendingBufferCounter);
4693 }
4694 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004695 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004696 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004697 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004698 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004699 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004700 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004701 default:
4702 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004703 break;
4704 }
4705
Dan Stoza7d89d062015-04-30 13:29:25 -07004706 if (result != NO_ERROR) {
4707 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004708 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004709
Vishnu Nair858a3b42022-01-12 20:42:28 -08004710 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004711 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4712 if (parentHandle != nullptr && parent == nullptr) {
4713 ALOGE("Invalid parent handle %p.", parentHandle.get());
4714 addToRoot = false;
4715 }
4716 if (parentLayer != nullptr) {
4717 addToRoot = false;
4718 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004719
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004720 int parentId = -1;
4721 // We can safely promote the layer in binder thread because we have a strong reference
4722 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4723 sp<Layer> parentSp = parent.promote();
4724 if (parentSp != nullptr) {
4725 parentId = parentSp->getSequence();
4726 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004727 if (mTransactionTracing) {
4728 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4729 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004730 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004731
Vishnu Nair047fb332021-12-09 09:54:36 -08004732 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4733 if (result != NO_ERROR) {
4734 return result;
4735 }
4736
Ady Abraham9f0a4002020-10-05 15:47:26 -07004737 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004738 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004739}
4740
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004741status_t SurfaceFlinger::createBufferQueueLayer(LayerCreationArgs& args, PixelFormat& format,
Evan Roskya1f1e152019-01-24 16:17:46 -08004742 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004743 sp<IGraphicBufferProducer>* gbp,
4744 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004745 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004746 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004747 case PIXEL_FORMAT_TRANSPARENT:
4748 case PIXEL_FORMAT_TRANSLUCENT:
4749 format = PIXEL_FORMAT_RGBA_8888;
4750 break;
4751 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004752 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004753 break;
4754 }
4755
chaviwb4c6e582019-08-16 14:35:07 -07004756 sp<BufferQueueLayer> layer;
chaviwb4c6e582019-08-16 14:35:07 -07004757 args.textureName = getNewTexture();
4758 {
4759 // Grab the SF state lock during this since it's the only safe way to access
4760 // RenderEngine when creating a BufferLayerConsumer
4761 // TODO: Check if this lock is still needed here
4762 Mutex::Autolock lock(mStateLock);
4763 layer = getFactory().createBufferQueueLayer(args);
4764 }
4765
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004766 status_t err = layer->setDefaultBufferProperties(0, 0, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004767 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004768 *handle = layer->getHandle();
4769 *gbp = layer->getProducer();
4770 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004771 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004772
Marissa Wallfd668622018-05-10 10:21:13 -07004773 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004774 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004775}
4776
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004777status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004778 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004779 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004780 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004781 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004782 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004783}
4784
Vishnu Nair84125ac2021-12-02 08:47:48 -08004785status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004786 sp<Layer>* outLayer) {
4787 *outLayer = getFactory().createEffectLayer(args);
4788 *handle = (*outLayer)->getHandle();
4789 return NO_ERROR;
4790}
4791
Vishnu Nair84125ac2021-12-02 08:47:48 -08004792status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004793 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004794 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004795 *handle = (*outLayer)->getHandle();
4796 return NO_ERROR;
4797}
4798
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004799void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004800 mLayersPendingRemoval.add(layer);
4801 mLayersRemoved = true;
4802 setTransactionFlags(eTransactionNeeded);
4803}
4804
Vishnu Nairf9096652021-07-20 18:49:42 -07004805void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004806 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004807 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004808 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004809 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004810 if (mTransactionTracing) {
4811 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004812 }
Rob Carr4bba3702018-10-08 21:53:30 +00004813}
4814
Mathias Agopianb60314a2012-04-10 22:09:54 -07004815// ---------------------------------------------------------------------------
4816
Andy McFadden13a082e2012-08-24 10:16:42 -07004817void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004818 const auto display = getDefaultDisplayDeviceLocked();
4819 if (!display) return;
4820
4821 const sp<IBinder> token = display->getDisplayToken().promote();
4822 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004823
Jesse Hall01e29052013-02-19 16:13:35 -08004824 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004825 Vector<ComposerState> state;
4826 Vector<DisplayState> displays;
4827 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004828 d.what = DisplayState::eDisplayProjectionChanged |
4829 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004830 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004831 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004832 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004833 d.orientedDisplaySpaceRect.makeInvalid();
4834 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004835 d.width = 0;
4836 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004837 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004838
Vishnu Nair9a69a042021-06-18 13:19:49 -07004839 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004840
4841 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004842 // It should be on the main thread, apply it directly.
4843 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004844 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004845 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004846
Peiyong Lin65248e02020-04-18 21:15:07 -07004847 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004848 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004849 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004850 mActiveDisplayTransformHint = display->getTransformHint();
Brian Andersond0010582017-03-07 13:20:31 -08004851 // Use phase of 0 since phase is not known.
4852 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004853 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004854 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004855}
4856
4857void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004858 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004859 static_cast<void>(
4860 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004861}
4862
Peiyong Lin65248e02020-04-18 21:15:07 -07004863void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004864 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004865 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004866 return;
4867 }
4868
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004869 const auto displayId = display->getPhysicalId();
4870 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004871
Peiyong Lin65248e02020-04-18 21:15:07 -07004872 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004873 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004874 return;
4875 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004876
Ady Abraham4f960d12021-10-13 16:59:49 -07004877 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4878 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4879 activeDisplay->isPoweredOn()) {
4880 ALOGW("Trying to change power mode on non active display while the active display is ON");
4881 }
4882
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004883 display->setPowerMode(mode);
4884
Lloyd Pique4dccc412018-01-22 17:21:36 -08004885 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004886 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004887 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004888 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004889 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004890 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004891 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004892 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004893 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004894 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4895 // We can merge the syscall later.
4896 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4897 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4898 }
Martin Liu4a322352020-03-24 21:30:38 +08004899 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4900 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4901 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004902 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004903 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004904 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004905 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004906 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004907 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004908
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004909 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004910 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004911 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004912 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004913 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004914 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4915 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004916 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004917 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4918 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4919 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004920 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004921 mScheduler->disableHardwareVsync(true);
4922 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004923 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004924
Ady Abraham27c70212019-06-11 10:52:26 -07004925 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004926 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004927
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004928 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004929 mVisibleRegionsDirty = true;
4930 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004931 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004932 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004933 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004934 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004935 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004936 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004937 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004938 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004939 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004940 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004941 mScheduler->disableHardwareVsync(true);
4942 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004943 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004944 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004945 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004946 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004947 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004948 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004949
Ady Abrahamadc914c2021-10-13 17:04:27 -07004950 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004951 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004952 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004953 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004954 }
4955
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004956 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004957}
4958
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004959void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004960 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004961 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004962 if (!display) {
4963 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4964 displayToken.get());
4965 } else if (display->isVirtual()) {
4966 ALOGW("Attempt to set power mode %d for virtual display", mode);
4967 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004968 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004969 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004970 });
4971
4972 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004973}
4974
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004975status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004976 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004977
Mathias Agopianbd115332013-04-18 16:41:04 -07004978 IPCThreadState* ipc = IPCThreadState::self();
4979 const int pid = ipc->getCallingPid();
4980 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004981
Mathias Agopianbd115332013-04-18 16:41:04 -07004982 if ((uid != AID_SHELL) &&
4983 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004984 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4985 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004986 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004987 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004988 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004989 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07004990 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004991 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004992 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004993 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4994 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4995 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4996 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004997 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004998 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4999 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005000 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005001 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005002 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005003 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005004
Dominik Laskowskic2867142019-01-21 11:33:38 -08005005 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005006
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005007 bool dumpLayers = true;
5008 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005009 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005010 if (!lock.locked()) {
5011 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
5012 strerror(-lock.status), lock.status);
5013 }
5014
5015 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
5016 (it->second)(args, asProto, result);
5017 dumpLayers = false;
5018 } else if (!asProto) {
5019 dumpAllLocked(args, result);
5020 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08005021 }
5022
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005023 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005024 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05005025 LayersTraceProto* layersTrace = traceFileProto.add_entry();
5026 LayersProto layersProto = dumpProtoFromMainThread();
5027 layersTrace->mutable_layers()->Swap(&layersProto);
5028 dumpDisplayProto(*layersTrace);
5029
Dominik Laskowski46470112019-08-02 13:13:11 -07005030 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05005031 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07005032 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07005033 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05005034 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07005035 result.append(LayerProtoParser::layerTreeToString(layerTree));
5036 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07005037 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07005038 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07005039 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005040 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005041 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005042 return NO_ERROR;
5043}
5044
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005045status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08005046 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005047 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005048 if (mTransactionTracing) {
5049 mTransactionTracing->writeToFile();
5050 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005051 }
5052
5053 return doDump(fd, DumpArgs(), asProto);
5054}
5055
Dominik Laskowskic2867142019-01-21 11:33:38 -08005056void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005057 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005058 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005059}
5060
Dominik Laskowskic2867142019-01-21 11:33:38 -08005061void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07005062 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005063
Dominik Laskowskic2867142019-01-21 11:33:38 -08005064 if (args.size() > 1) {
5065 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08005066 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005067 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005068 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005069 }
Robert Carr2047fae2016-11-28 14:09:09 -08005070 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005071 } else {
5072 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005073 }
5074}
5075
Dominik Laskowskic2867142019-01-21 11:33:38 -08005076void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005077 const bool clearAll = args.size() < 2;
5078 const auto name = clearAll ? String8() : String8(args[1]);
5079
Edgar Arriaga844fa672020-01-16 14:21:42 -08005080 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005081 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005082 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005083 }
Robert Carr2047fae2016-11-28 14:09:09 -08005084 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005085
Svetoslavd85084b2014-03-20 10:28:31 -07005086 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005087}
5088
Dominik Laskowskic2867142019-01-21 11:33:38 -08005089void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5090 mTimeStats->parseArgs(asProto, args, result);
5091}
5092
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005093void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5094 mFrameTimeline->parseArgs(args, result);
5095}
5096
Jamie Gennis6547ff42013-07-16 20:12:42 -07005097void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005098 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005099 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005100 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005101
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005102 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005103}
5104
Yiwei Zhang5434a782018-12-05 18:06:32 -08005105void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005106 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005107
Yiwei Zhang5434a782018-12-05 18:06:32 -08005108 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5109 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005110 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5111 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005112 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5113 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5114 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005115 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005116}
5117
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005118void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005119 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005120
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005121 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005122 result.append("\n");
5123
Ady Abraham8287e852020-08-12 14:44:58 -07005124 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005125 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005126 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005127 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005128
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005129 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5130 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005131
Ana Krulecc2870422019-01-29 19:00:58 -08005132 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005133 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005134 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5135 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005136}
5137
Dan Stoza269dc4d2021-01-15 15:07:43 -08005138void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5139 for (const auto& [token, display] : mDisplays) {
5140 const auto compositionDisplay = display->getCompositionDisplay();
5141 compositionDisplay->dumpPlannerInfo(args, result);
5142 }
5143}
5144
Yiwei Zhang5434a782018-12-05 18:06:32 -08005145void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5146 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005147 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5148 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005149 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005150 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005151 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005152 }
David Sodman4a36e932017-11-07 14:29:47 -08005153 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005154 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005155 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005156 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5157 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005158}
5159
Yiwei Zhang5434a782018-12-05 18:06:32 -08005160void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
5161 result.append("Layer frame timestamps:\n");
Josh Chienedaa9132020-12-04 18:30:46 +08005162 // Traverse all layers to dump frame-events for each layer
5163 mCurrentState.traverseInZOrder(
5164 [&] (Layer* layer) { layer->dumpFrameEvents(result); });
Brian Andersond6927fb2016-07-23 23:37:30 -07005165}
5166
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005167void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5168 for (const auto& [token, display] : mDisplays) {
5169 display->getCompositionDisplay()->dump(result);
5170 result += '\n';
5171 }
5172}
5173
5174void SurfaceFlinger::dumpDisplays(std::string& result) const {
5175 for (const auto& [token, display] : mDisplays) {
5176 display->dump(result);
5177 result += '\n';
5178 }
5179}
5180
Yiwei Zhang5434a782018-12-05 18:06:32 -08005181void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005182 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005183 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005184 if (!displayId) {
5185 continue;
5186 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005187 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005188 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005189 continue;
5190 }
5191
Yiwei Zhang5434a782018-12-05 18:06:32 -08005192 StringAppendF(&result,
5193 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5194 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005195 uint8_t port;
5196 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005197 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005198 result.append("no identification data\n");
5199 continue;
5200 }
5201
5202 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005203 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005204 continue;
5205 }
5206
5207 const auto edid = parseEdid(data);
5208 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005209 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005210 continue;
5211 }
5212
Yiwei Zhang5434a782018-12-05 18:06:32 -08005213 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005214 result.append(edid->displayName.data(), edid->displayName.length());
5215 result.append("\"\n");
5216 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005217}
5218
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005219void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5220 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005221 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005222 uint8_t port;
5223 DisplayIdentificationData data;
5224
5225 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5226 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5227 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5228 }
5229}
5230
Yiwei Zhang5434a782018-12-05 18:06:32 -08005231void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005232 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005233 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5234 StringAppendF(&result, "DisplayColorSetting: %s\n",
5235 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005236
5237 // TODO: print out if wide-color mode is active or not
5238
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005239 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005240 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005241 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005242 continue;
5243 }
5244
Yiwei Zhang5434a782018-12-05 18:06:32 -08005245 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005246 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005247 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005248 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005249 }
5250
Lloyd Pique32cbe282018-10-19 13:09:22 -07005251 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005252 StringAppendF(&result, " Current color mode: %s (%d)\n",
5253 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005254 }
5255 result.append("\n");
5256}
5257
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005258LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005259 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005260 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005261 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005262 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005263
chaviw1d044282017-09-27 12:19:28 -07005264 return layersProto;
5265}
5266
chaviw0a398992021-08-13 10:13:01 -05005267void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005268 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005269 DisplayProto* displayProto = layersTraceProto.add_displays();
5270 displayProto->set_id(display->getId().value);
5271 displayProto->set_name(display->getDisplayName());
5272 displayProto->set_layer_stack(display->getLayerStack().id);
5273 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5274 [&]() { return displayProto->mutable_size(); });
5275 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5276 return displayProto->mutable_layer_stack_space_rect();
5277 });
5278 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5279 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005280 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005281 }
5282}
5283
Alec Mouri6b9e9912020-01-21 10:50:24 -08005284void SurfaceFlinger::dumpHwc(std::string& result) const {
5285 getHwComposer().dump(result);
5286}
5287
Vishnu Nair0f085c62019-08-30 08:49:12 -07005288void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5289 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5290 // it.
5291 LayerProto* rootProto = layersProto.add_layers();
5292 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5293 rootProto->set_id(offscreenRootLayerId);
5294 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005295 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005296
5297 for (Layer* offscreenLayer : mOffscreenLayers) {
5298 // Add layer as child of the fake root
5299 rootProto->add_children(offscreenLayer->sequence);
5300
5301 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005302 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005303 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005304 }
5305}
5306
Vishnu Nair8406fd72019-07-30 11:29:31 -07005307LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005308 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005309}
5310
Vishnu Nair0f085c62019-08-30 08:49:12 -07005311void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005312 auto future = mScheduler->schedule([this] {
5313 std::string result;
5314 for (Layer* offscreenLayer : mOffscreenLayers) {
5315 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5316 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5317 }
5318 return result;
5319 });
5320
Vishnu Nair0f085c62019-08-30 08:49:12 -07005321 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005322 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005323}
5324
Dominik Laskowskic2867142019-01-21 11:33:38 -08005325void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5326 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005327 Colorizer colorizer(colorize);
5328
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005329 // figure out if we're stuck somewhere
5330 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005331 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005332 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5333
5334 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005335 * Dump library configuration.
5336 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005337
5338 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005339 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005340 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005341 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005342 result.append("\n");
5343
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005344 result.append("\nDisplay identification data:\n");
5345 dumpDisplayIdentificationData(result);
5346
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005347 result.append("\nWide-Color information:\n");
5348 dumpWideColorInfo(result);
5349
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005350 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005351 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005352 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005353 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005354 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005355
Andy McFadden41d67d72014-04-25 16:58:34 -07005356 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005357 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005358 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005359 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005360 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005361
Dan Stozab90cf072015-03-05 11:05:59 -08005362 dumpStaticScreenStats(result);
5363 result.append("\n");
5364
Alec Mouri40189b02019-03-05 15:07:54 -08005365 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5366 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5367 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005368
Andy McFadden4803b742012-09-24 19:07:20 -07005369 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005370 * Dump the visible layer list
5371 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005372 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005373 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005374 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005375
Chia-I Wu2f884132018-09-13 15:17:58 -07005376 {
Lloyd Pique207def92019-02-28 16:09:52 -08005377 StringAppendF(&result, "Composition layers\n");
5378 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005379 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005380 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005381
5382 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5383 layer->getDebugName() ? layer->getDebugName()
5384 : "<unknown>");
5385 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005386 });
5387 }
5388
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005389 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005390 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005391 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005392 dumpDisplays(result);
5393 dumpCompositionDisplays(result);
5394 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005395
5396 mCompositionEngine->dump(result);
5397
5398 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005399 * Dump SurfaceFlinger global state
5400 */
5401
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005402 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005403 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005404 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005405
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005406 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005407
Robert Carrbeba6f02021-02-10 21:06:27 -08005408 result.append("ClientCache state:\n");
5409 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005410 DebugEGLImageTracker::getInstance()->dump(result);
5411
Dominik Laskowski075d3172018-05-24 15:50:06 -07005412 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005413 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5414 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005415 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5416 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005417 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005418 StringAppendF(&result,
5419 " transaction-flags : %08x\n"
5420 " gpu_to_cpu_unsupported : %d\n",
5421 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005422
Marin Shalamanov045b7002021-01-07 16:56:24 +01005423 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005424 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005425 if (const auto activeMode = display->getActiveMode()) {
5426 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005427
5428 const auto dpi = activeMode->getDpi();
5429 xDpi = base::StringPrintf("%.2f", dpi.x);
5430 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005431 } else {
5432 fps = "unknown";
5433 xDpi = "unknown";
5434 yDpi = "unknown";
5435 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005436 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005437 " refresh-rate : %s\n"
5438 " x-dpi : %s\n"
5439 " y-dpi : %s\n",
5440 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005441 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005442
Yiwei Zhang5434a782018-12-05 18:06:32 -08005443 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005444
Dan Stozae22aec72016-08-01 13:20:59 -07005445 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005446 * Tracing state
5447 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005448 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005449
5450 result.append("\nTransaction tracing: ");
5451 if (mTransactionTracing) {
5452 result.append("enabled\n");
5453 mTransactionTracing->dump(result);
5454 } else {
5455 result.append("disabled\n");
5456 }
5457 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005458
5459 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005460 * HWC layer minidump
5461 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005462 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005463 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005464 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005465 continue;
5466 }
5467
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005468 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5469 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005470 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005471
5472 const DisplayDevice& ref = *display;
5473 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005474 result.append("\n");
5475 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005476
Ady Abraham2790e9f2021-04-28 13:14:20 -07005477 {
5478 DumpArgs plannerArgs;
5479 plannerArgs.add(); // first argument is ignored
5480 plannerArgs.add(String16("--layers"));
5481 dumpPlannerInfo(plannerArgs, result);
5482 }
5483
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005484 /*
5485 * Dump HWComposer state
5486 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005487 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005488 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005489 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005490 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005491 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005492 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005493
5494 /*
5495 * Dump gralloc state
5496 */
5497 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5498 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005499
rnleea2ecd832021-07-29 13:58:30 -07005500 /*
5501 * Dump flag/property manager state
5502 */
Robert Carr9b623c32022-03-21 15:55:22 -07005503 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005504
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005505 result.append(mTimeStats->miniDump());
5506 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005507}
5508
chaviw17ac24b2021-01-28 18:50:05 -08005509mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5510 if (saturation == 1) {
5511 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005512 }
5513
chaviw17ac24b2021-01-28 18:50:05 -08005514 float3 luminance{0.213f, 0.715f, 0.072f};
5515 luminance *= 1.0f - saturation;
5516 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5517 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5518 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5519 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5520 return saturationMatrix;
5521}
5522
5523void SurfaceFlinger::updateColorMatrixLocked() {
5524 mat4 colorMatrix =
5525 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5526
Chia-I Wu28f320b2018-05-03 11:02:56 -07005527 if (mCurrentState.colorMatrix != colorMatrix) {
5528 mCurrentState.colorMatrix = colorMatrix;
5529 mCurrentState.colorMatrixChanged = true;
5530 setTransactionFlags(eTransactionNeeded);
5531 }
5532}
5533
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005534status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005535#pragma clang diagnostic push
5536#pragma clang diagnostic error "-Wswitch-enum"
5537 switch (static_cast<ISurfaceComposerTag>(code)) {
5538 // These methods should at minimum make sure that the client requested
5539 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005540 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005541 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005542 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005543 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005544 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5545 // permission dynamically. Don't use the permission cache for this check.
5546 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005547 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005548 IPCThreadState* ipc = IPCThreadState::self();
5549 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5550 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005551 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005552 }
Robert Carr1db73f62016-12-21 12:58:51 -08005553 return OK;
5554 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005555 // The following calls are currently used by clients that do not
5556 // request necessary permissions. However, they do not expose any secret
5557 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005558 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005559 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005560 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005561 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005562 // Calling setTransactionState is safe, because you need to have been
5563 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005564 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005565 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005566 return OK;
5567 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005568 case BOOT_FINISHED:
5569 // Used by apps to hook Choreographer to SurfaceFlinger.
5570 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005571 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005572 case CREATE_DISPLAY:
5573 case DESTROY_DISPLAY:
5574 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5575 case GET_PHYSICAL_DISPLAY_IDS:
5576 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005577 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005578 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005579 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005580 case GET_DISPLAY_STATE:
5581 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005582 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005583 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005584 case GET_DISPLAY_NATIVE_PRIMARIES:
5585 case SET_ACTIVE_COLOR_MODE:
5586 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005587 case CLEAR_BOOT_DISPLAY_MODE:
5588 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5589 case SET_AUTO_LOW_LATENCY_MODE:
5590 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005591 case CAPTURE_LAYERS:
5592 case CAPTURE_DISPLAY:
5593 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005594 case CLEAR_ANIMATION_FRAME_STATS:
5595 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005596 case OVERRIDE_HDR_TYPES:
5597 case ON_PULL_ATOM:
5598 case ENABLE_VSYNC_INJECTIONS:
5599 case INJECT_VSYNC:
5600 case GET_LAYER_DEBUG_INFO:
5601 case GET_COLOR_MANAGEMENT:
5602 case GET_COMPOSITION_PREFERENCE:
5603 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5604 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005605 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005606 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005607 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005608 case ADD_REGION_SAMPLING_LISTENER:
5609 case REMOVE_REGION_SAMPLING_LISTENER:
5610 case ADD_FPS_LISTENER:
5611 case REMOVE_FPS_LISTENER:
5612 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5613 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5614 case ADD_WINDOW_INFOS_LISTENER:
5615 case REMOVE_WINDOW_INFOS_LISTENER:
5616 case SET_DESIRED_DISPLAY_MODE_SPECS:
5617 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005618 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5619 case SET_DISPLAY_BRIGHTNESS:
5620 case ADD_HDR_LAYER_INFO_LISTENER:
5621 case REMOVE_HDR_LAYER_INFO_LISTENER:
5622 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005623 case SET_GLOBAL_SHADOW_SETTINGS:
5624 case GET_DISPLAY_DECORATION_SUPPORT:
5625 case SET_FRAME_RATE:
5626 case SET_OVERRIDE_FRAME_RATE:
5627 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005628 case ADD_TRANSACTION_TRACE_LISTENER:
5629 case GET_GPU_CONTEXT_PRIORITY:
5630 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005631 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005632 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005633 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005634
5635 // These codes are used for the IBinder protocol to either interrogate the recipient
5636 // side of the transaction for its canonical interface descriptor or to dump its state.
5637 // We let them pass by default.
5638 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5639 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5640 code == IBinder::SYSPROPS_TRANSACTION) {
5641 return OK;
5642 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005643 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005644 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005645 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005646 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5647 return OK;
5648 }
5649 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5650 return PERMISSION_DENIED;
5651#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005652}
5653
Ana Krulec13be8ad2018-08-21 02:43:56 +00005654status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5655 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005656 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5657 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005658 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005659
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005660 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5661 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005662 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005663 IPCThreadState* ipc = IPCThreadState::self();
5664 const int uid = ipc->getCallingUid();
5665 if (CC_UNLIKELY(uid != AID_SYSTEM
5666 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005667 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005668 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005669 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005670 return PERMISSION_DENIED;
5671 }
5672 int n;
5673 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005674 case 1000: // Unused.
5675 case 1001:
5676 return NAME_NOT_FOUND;
5677 case 1002: // Toggle flashing on surface damage.
5678 if (const int delay = data.readInt32(); delay > 0) {
5679 mDebugFlashDelay = delay;
5680 } else {
5681 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5682 }
5683 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005684 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005685 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005686 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005687 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005688 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005689 case 1005: { // Force commit ahead of next VSYNC.
5690 Mutex::Autolock lock(mStateLock);
5691 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5692 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005693 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005694 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005695 case 1007: // Unused.
5696 return NAME_NOT_FOUND;
5697 case 1008: // Toggle forced GPU composition.
5698 mDebugDisableHWC = data.readInt32() != 0;
5699 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005700 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005701 case 1009: // Toggle use of transform hint.
5702 mDebugDisableTransformHint = data.readInt32() != 0;
5703 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005704 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005705 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005706 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005707 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005708 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005709 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005710 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005711 return NO_ERROR;
5712 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005713 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005714 if (!display) {
5715 return NAME_NOT_FOUND;
5716 }
5717
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005718 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005719 return NO_ERROR;
5720 }
5721 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005722 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005723 // daltonize
5724 n = data.readInt32();
5725 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005726 case 1:
5727 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5728 break;
5729 case 2:
5730 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5731 break;
5732 case 3:
5733 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5734 break;
5735 default:
5736 mDaltonizer.setType(ColorBlindnessType::None);
5737 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005738 }
5739 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005740 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005741 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005742 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005743 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005744
5745 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005746 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005747 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005748 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005749 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005750 // apply a color matrix
5751 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005752 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005753 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005754 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005755 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005756 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005757 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005758 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005759 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005760 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005761 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005762
5763 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5764 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005765 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005766 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5767 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5768 }
5769
Chia-I Wu28f320b2018-05-03 11:02:56 -07005770 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005771 return NO_ERROR;
5772 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005773 case 1016: { // Unused.
5774 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005775 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005776 case 1017: {
5777 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005778 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005779 return NO_ERROR;
5780 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005781 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005782 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005783 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005784 return NO_ERROR;
5785 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005786 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005787 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005788 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005789 return NO_ERROR;
5790 }
Irvel468051e2016-06-13 16:44:44 -07005791 case 1020: { // Layer updates interceptor
5792 n = data.readInt32();
5793 if (n) {
5794 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005795 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005796 }
5797 else{
5798 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005799 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005800 }
5801 return NO_ERROR;
5802 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005803 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005804 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005805 static_cast<void>(
5806 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005807 return NO_ERROR;
5808 }
Romain Guy0147a172017-06-01 13:53:56 -07005809 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005810 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005811 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005812
Chia-I Wu28f320b2018-05-03 11:02:56 -07005813 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005814 return NO_ERROR;
5815 }
Romain Guy54f154a2017-10-24 21:40:32 +01005816 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005817 int32_t colorMode;
5818
Chia-I Wu0d711262018-05-21 15:19:35 -07005819 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005820 if (data.readInt32(&colorMode) == NO_ERROR) {
5821 mForceColorMode = static_cast<ColorMode>(colorMode);
5822 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005823 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005824 return NO_ERROR;
5825 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005826 // Deprecate, use 1030 to check whether the device is color managed.
5827 case 1024: {
5828 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005829 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005830 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005831 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005832 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005833 if (n == 1) {
5834 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005835 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005836 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005837 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005838 int64_t startingTime =
5839 (fixedStartingTime) ? fixedStartingTime : systemTime();
5840 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005841 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005842 mLayerTracing.notify("start", startingTime);
5843 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005844 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005845 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005846 } else if (n == 2) {
5847 std::string filename = std::string(data.readCString());
5848 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5849 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005850 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005851 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005852 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005853 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005854 mTracingEnabledChanged = tracingEnabledChanged;
5855 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005856 return NO_ERROR;
5857 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005858 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005859 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005860 return NO_ERROR;
5861 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005862 // Is a DisplayColorSetting supported?
5863 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005864 const auto display = getDefaultDisplayDevice();
5865 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005866 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005867 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005868
5869 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5870 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005871 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005872 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005873 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005874 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005875 reply->writeBool(true);
5876 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005877 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005878 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005879 break;
5880 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005881 reply->writeBool(
5882 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005883 break;
5884 }
5885 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005886 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005887 case 1028: { // Unused.
5888 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005889 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005890 // Set buffer size for SF tracing (value in KB)
5891 case 1029: {
5892 n = data.readInt32();
5893 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5894 ALOGW("Invalid buffer size: %d KB", n);
5895 reply->writeInt32(BAD_VALUE);
5896 return BAD_VALUE;
5897 }
5898
5899 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005900 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005901 reply->writeInt32(NO_ERROR);
5902 return NO_ERROR;
5903 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005904 // Is device color managed?
5905 case 1030: {
5906 reply->writeBool(useColorManagement);
5907 return NO_ERROR;
5908 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005909 // Override default composition data space
5910 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5911 // && adb shell stop zygote && adb shell start zygote
5912 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5913 // adb shell stop zygote && adb shell start zygote
5914 case 1031: {
5915 Mutex::Autolock _l(mStateLock);
5916 n = data.readInt32();
5917 if (n) {
5918 n = data.readInt32();
5919 if (n) {
5920 Dataspace dataspace = static_cast<Dataspace>(n);
5921 if (!validateCompositionDataspace(dataspace)) {
5922 return BAD_VALUE;
5923 }
5924 mDefaultCompositionDataspace = dataspace;
5925 }
5926 n = data.readInt32();
5927 if (n) {
5928 Dataspace dataspace = static_cast<Dataspace>(n);
5929 if (!validateCompositionDataspace(dataspace)) {
5930 return BAD_VALUE;
5931 }
5932 mWideColorGamutCompositionDataspace = dataspace;
5933 }
5934 } else {
5935 // restore composition data space.
5936 mDefaultCompositionDataspace = defaultCompositionDataspace;
5937 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5938 }
5939 return NO_ERROR;
5940 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005941 // Set trace flags
5942 case 1033: {
5943 n = data.readUint32();
5944 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005945 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005946 reply->writeInt32(NO_ERROR);
5947 return NO_ERROR;
5948 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005949 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005950 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005951 switch (n = data.readInt32()) {
5952 case 0:
5953 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005954 FTL_FAKE_GUARD(mStateLock,
5955 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005956 break;
5957 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005958 reply->writeBool(
5959 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005960 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005961 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005962 });
5963
5964 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005965 return NO_ERROR;
5966 }
Ady Abraham34392f72019-04-10 11:29:27 -07005967 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005968 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005969
Dominik Laskowskif1833852021-03-23 15:06:50 -07005970 const auto display = [&]() -> sp<IBinder> {
5971 uint64_t value;
5972 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005973 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005974 }
5975
Dominik Laskowskif1833852021-03-23 15:06:50 -07005976 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5977 return getPhysicalDisplayToken(*id);
5978 }
5979
5980 ALOGE("Invalid physical display ID");
5981 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005982 }();
5983
Shiyong Li2bcece92021-08-30 20:38:50 +00005984 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005985 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005986 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5987 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005988 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005989 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5990 // manager frame rate policy a new policy which allows switching between all refresh
5991 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005992 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005993 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005994 return mScheduler
5995 ->schedule([this] {
5996 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005997 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005998
Dominik Laskowski756b7892021-08-04 12:53:59 -07005999 // This is a little racy, but not in a way that hurts anything. As
6000 // we grab the defaultMode from the display manager policy, we could
6001 // be setting a new display manager policy, leaving us using a stale
6002 // defaultMode. The defaultMode doesn't matter for the override
6003 // policy though, since we set allowGroupSwitching to true, so it's
6004 // not a problem.
6005 scheduler::RefreshRateConfigs::Policy overridePolicy;
6006 overridePolicy.defaultMode = display->refreshRateConfigs()
6007 .getDisplayManagerPolicy()
6008 .defaultMode;
6009 overridePolicy.allowGroupSwitching = true;
6010 constexpr bool kOverridePolicy = true;
6011 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
6012 kOverridePolicy);
6013 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006014 .get();
6015 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07006016 return mScheduler
6017 ->schedule([this] {
6018 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006019 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07006020 constexpr bool kOverridePolicy = true;
6021 return setDesiredDisplayModeSpecsInternal(display, {},
6022 kOverridePolicy);
6023 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006024 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07006025 }
Ady Abraham07e54702020-04-16 15:05:37 -07006026 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02006027 // Inject a hotplug connected event for the primary display. This will deallocate and
6028 // reallocate the display state including framebuffers.
6029 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006030 const hal::HWDisplayId hwcId =
6031 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
6032
6033 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02006034 return NO_ERROR;
6035 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07006036 // Modify the max number of display frames stored within FrameTimeline
6037 case 1038: {
6038 n = data.readInt32();
6039 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
6040 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
6041 return BAD_VALUE;
6042 }
6043 if (n == 0) {
6044 // restore to default
6045 mFrameTimeline->reset();
6046 return NO_ERROR;
6047 }
6048 mFrameTimeline->setMaxDisplayFrames(n);
6049 return NO_ERROR;
6050 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07006051 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07006052 PhysicalDisplayId displayId = [&]() {
6053 Mutex::Autolock lock(mStateLock);
6054 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6055 }();
6056
6057 auto inUid = static_cast<uid_t>(data.readInt32());
6058 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08006059 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
6060 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07006061 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08006062 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006063 // Toggle caching feature
6064 // First argument is an int32 - nonzero enables caching and zero disables caching
6065 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6066 // caching to a particular physical display
6067 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006068 auto future = mScheduler->schedule([&] {
6069 n = data.readInt32();
6070 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6071 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6072 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6073 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6074 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6075 return NAME_NOT_FOUND;
6076 }
6077 }
6078 {
6079 Mutex::Autolock lock(mStateLock);
6080 mLayerCachingEnabled = n != 0;
6081 for (const auto& [_, display] : mDisplays) {
6082 if (!inputId || *inputId == display->getPhysicalId()) {
6083 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006084 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006085 }
6086 }
6087 return OK;
6088 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006089
Dominik Laskowski756b7892021-08-04 12:53:59 -07006090 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006091 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006092 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006093 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006094 return NO_ERROR;
6095 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006096 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006097 if (mTransactionTracing) {
6098 if (data.readInt32()) {
6099 // Transaction tracing is always running but allow the user to temporarily
6100 // increase the buffer when actively debugging.
6101 mTransactionTracing->setBufferSize(
6102 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6103 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006104 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006105 mTransactionTracing->setBufferSize(
6106 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006107 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006108 }
6109 reply->writeInt32(NO_ERROR);
6110 return NO_ERROR;
6111 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006112 case 1042: { // Write layers trace or transaction trace to file
6113 if (mTransactionTracing) {
6114 mTransactionTracing->writeToFile();
6115 }
6116 if (mLayerTracingEnabled) {
6117 mLayerTracing.writeToFile();
6118 }
6119 reply->writeInt32(NO_ERROR);
6120 return NO_ERROR;
6121 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006122 }
6123 }
6124 return err;
6125}
6126
Ady Abrahama09852a2020-02-20 14:23:42 -08006127void SurfaceFlinger::kernelTimerChanged(bool expired) {
6128 static bool updateOverlay =
6129 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006130 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006131
6132 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006133 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006134 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006135 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006136 if (!display) {
6137 ALOGW("%s: default display is null", __func__);
6138 return;
6139 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006140 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006141
6142 const auto desiredActiveMode = display->getDesiredActiveMode();
6143 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6144 ? std::make_optional(desiredActiveMode->mode->getId())
6145 : std::nullopt;
6146
6147 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6148
Ady Abraham1b11bc62021-06-03 19:51:19 -07006149 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006150 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006151 }
6152 }));
6153}
6154
ramindani32cf0602022-03-02 02:30:29 +00006155std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6156SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6157 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6158 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6159 const auto timeout = getIdleTimerTimeout(displayId);
6160 if (isKernelIdleTimerHwcSupported) {
6161 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6162 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6163 // In order to decide if we can use the HWC api for idle timer
6164 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6165 // without relying on hasDisplayCapability.
6166 // hasDisplayCapability relies on DisplayCapabilities
6167 // which are updated after we set the PowerMode::ON.
6168 // DISPLAY_IDLE_TIMER is a display driver property
6169 // and is available before the PowerMode::ON
6170 return {KernelIdleTimerController::HwcApi, timeout};
6171 }
6172 return {std::nullopt, timeout};
6173 }
6174 if (getKernelIdleTimerSyspropConfig(displayId)) {
6175 return {KernelIdleTimerController::Sysprop, timeout};
6176 }
6177
6178 return {std::nullopt, timeout};
6179}
6180
6181void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6182 KernelIdleTimerController controller,
6183 PhysicalDisplayId displayId) {
6184 switch (controller) {
6185 case KernelIdleTimerController::HwcApi: {
6186 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6187 break;
6188 }
6189 case KernelIdleTimerController::Sysprop: {
6190 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6191 break;
6192 }
6193 }
6194}
6195
Ana Krulecb9afd792020-06-11 13:16:15 -07006196void SurfaceFlinger::toggleKernelIdleTimer() {
6197 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6198
Ady Abraham3efa3942021-06-24 19:01:25 -07006199 const auto display = getDefaultDisplayDeviceLocked();
6200 if (!display) {
6201 ALOGW("%s: default display is null", __func__);
6202 return;
6203 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006204
Ady Abrahame9316b72021-09-24 17:04:36 -07006205 // If the support for kernel idle timer is disabled for the active display,
6206 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006207 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6208 display->refreshRateConfigs().kernelIdleTimerController();
6209 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006210 return;
6211 }
6212
Ady Abraham3efa3942021-06-24 19:01:25 -07006213 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006214
Ana Krulecb9afd792020-06-11 13:16:15 -07006215 switch (action) {
6216 case KernelIdleTimerAction::TurnOff:
6217 if (mKernelIdleTimerEnabled) {
6218 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006219 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6220 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6221 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006222 mKernelIdleTimerEnabled = false;
6223 }
6224 break;
6225 case KernelIdleTimerAction::TurnOn:
6226 if (!mKernelIdleTimerEnabled) {
6227 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006228 const std::chrono::milliseconds timeout =
6229 display->refreshRateConfigs().getIdleTimerTimeout();
6230 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6231 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006232 mKernelIdleTimerEnabled = true;
6233 }
6234 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006235 }
6236}
6237
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006238// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6239class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006240public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006241 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6242 ~WindowDisconnector() {
6243 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006244 }
6245
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006246private:
6247 ANativeWindow* mWindow;
6248 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006249};
6250
chaviw93df2ea2019-04-30 16:45:12 -07006251static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6252 switch (colorMode) {
6253 case ColorMode::DISPLAY_P3:
6254 case ColorMode::BT2100_PQ:
6255 case ColorMode::BT2100_HLG:
6256 case ColorMode::DISPLAY_BT2020:
6257 return Dataspace::DISPLAY_P3;
6258 default:
6259 return Dataspace::V0_SRGB;
6260 }
6261}
6262
chaviwf5bb97b2021-04-28 15:35:37 -05006263static bool hasCaptureBlackoutContentPermission() {
6264 IPCThreadState* ipc = IPCThreadState::self();
6265 const int pid = ipc->getCallingPid();
6266 const int uid = ipc->getCallingUid();
6267 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6268 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6269}
6270
chaviw4b9d5e12020-08-04 18:30:35 -07006271static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6272 IPCThreadState* ipc = IPCThreadState::self();
6273 const int pid = ipc->getCallingPid();
6274 const int uid = ipc->getCallingUid();
6275 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6276 return OK;
6277 }
6278
6279 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6280 // itself, we allow it to continue.
6281 if (captureArgs.uid == uid) {
6282 return OK;
6283 }
6284
6285 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6286 return PERMISSION_DENIED;
6287}
6288
Peiyong Lin05cc0112020-10-14 16:16:37 -07006289status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6290 static constexpr int kFifoPriority = 2;
6291 static constexpr int kOtherPriority = 0;
6292
6293 struct sched_param param = {0};
6294 int sched_policy;
6295 if (enabled) {
6296 sched_policy = SCHED_FIFO;
6297 param.sched_priority = kFifoPriority;
6298 } else {
6299 sched_policy = SCHED_OTHER;
6300 param.sched_priority = kOtherPriority;
6301 }
6302
6303 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6304 return -errno;
6305 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006306
6307 return NO_ERROR;
6308}
6309
6310status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6311 static const unsigned int kUclampMin =
6312 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6313
6314 if (!kUclampMin) {
6315 // uclamp.min set to 0 (default), skip setting
6316 return NO_ERROR;
6317 }
6318
6319 // Currently, there is no wrapper in bionic: b/183240349.
6320 struct sched_attr {
6321 uint32_t size;
6322 uint32_t sched_policy;
6323 uint64_t sched_flags;
6324 int32_t sched_nice;
6325 uint32_t sched_priority;
6326 uint64_t sched_runtime;
6327 uint64_t sched_deadline;
6328 uint64_t sched_period;
6329 uint32_t sched_util_min;
6330 uint32_t sched_util_max;
6331 };
6332
6333 sched_attr attr = {};
6334 attr.size = sizeof(attr);
6335
6336 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6337 attr.sched_util_min = enabled ? kUclampMin : 0;
6338 attr.sched_util_max = 1024;
6339
6340 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6341 return -errno;
6342 }
6343
Peiyong Lin05cc0112020-10-14 16:16:37 -07006344 return NO_ERROR;
6345}
6346
chaviwd2432892020-07-24 17:42:39 -07006347status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006348 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006349 ATRACE_CALL();
6350
chaviw4b9d5e12020-08-04 18:30:35 -07006351 status_t validate = validateScreenshotPermissions(args);
6352 if (validate != OK) {
6353 return validate;
6354 }
6355
chaviwd2432892020-07-24 17:42:39 -07006356 if (!args.displayToken) return BAD_VALUE;
6357
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006358 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006359 ui::LayerStack layerStack;
6360 ui::Size reqSize(args.width, args.height);
6361 ui::Dataspace dataspace;
6362 {
6363 Mutex::Autolock lock(mStateLock);
6364 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6365 if (!display) return NAME_NOT_FOUND;
6366 displayWeak = display;
6367 layerStack = display->getLayerStack();
6368
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006369 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006370 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006371 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006372 }
6373
arthurhung79e81aa2020-08-28 00:09:19 +08006374 // The dataspace is depended on the color mode of display, that could use non-native mode
6375 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6376 // and failed if display is not in native mode. This provide a way to force using native
6377 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006378 dataspace = args.dataspace;
6379 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006380 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6381 dataspace = pickDataspaceFromColorMode(colorMode);
6382 }
chaviwd2432892020-07-24 17:42:39 -07006383 }
6384
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006385 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006386 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006387 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006388 });
6389
chaviw4b9d5e12020-08-04 18:30:35 -07006390 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6391 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006392 };
chaviw03900772020-08-18 12:34:51 -07006393
Sally Qi59a9f502021-10-12 18:53:23 +00006394 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6395 reqSize, args.pixelFormat, args.allowProtected,
6396 args.grayscale, captureListener);
6397 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006398}
6399
Dominik Laskowskif1833852021-03-23 15:06:50 -07006400status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006401 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006402 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006403 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006404 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006405 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006406 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006407 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006408
Dominik Laskowskif1833852021-03-23 15:06:50 -07006409 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006410 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006411 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006412 }
6413
chaviw93df2ea2019-04-30 16:45:12 -07006414 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006415 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006416 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006417
chaviw426b5c02020-07-27 11:20:15 -07006418 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006419 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6420 }
6421
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006422 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006423 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006424 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006425 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006426 });
chaviw93df2ea2019-04-30 16:45:12 -07006427
Marin Shalamanov1c434292020-06-12 01:47:29 +02006428 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006429 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006430 };
6431
Sally Qi59a9f502021-10-12 18:53:23 +00006432 if (captureListener == nullptr) {
6433 ALOGE("capture screen must provide a capture listener callback");
6434 return BAD_VALUE;
6435 }
6436 auto captureResultFuture =
6437 captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6438 ui::PixelFormat::RGBA_8888, false /* allowProtected */,
6439 false /* grayscale */, captureListener);
6440 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006441}
6442
chaviw3efadb12020-07-27 10:07:15 -07006443status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006444 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006445 ATRACE_CALL();
6446
chaviw4b9d5e12020-08-04 18:30:35 -07006447 status_t validate = validateScreenshotPermissions(args);
6448 if (validate != OK) {
6449 return validate;
6450 }
6451
Marin Shalamanov1c434292020-06-12 01:47:29 +02006452 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006453 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006454 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006455 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006456 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006457
6458 // Call this before holding mStateLock to avoid any deadlocking.
6459 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6460
Robert Carrc0df3122019-04-11 13:18:21 -07006461 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006462 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006463
Vishnu Nairf9096652021-07-20 18:49:42 -07006464 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006465 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006466 ALOGE("captureLayers called with an invalid or removed parent");
6467 return NAME_NOT_FOUND;
6468 }
6469
chaviwf5bb97b2021-04-28 15:35:37 -05006470 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006471 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006472 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6473 return PERMISSION_DENIED;
6474 }
6475
Robert Carr6a160312021-05-17 12:08:20 -07006476 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006477 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006478 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006479 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006480 }
6481
chaviw3efadb12020-07-27 10:07:15 -07006482 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006483 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006484 crop.bottom = parentSourceBounds.getHeight();
6485 }
6486
chaviw17ac24b2021-01-28 18:50:05 -08006487 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006488 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6489 // crop was not specified, or an invalid frame scale was provided.
6490 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006491 }
chaviw17ac24b2021-01-28 18:50:05 -08006492 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006493
chaviw3efadb12020-07-27 10:07:15 -07006494 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006495 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006496 if (excludeLayer != nullptr) {
6497 excludeLayers.emplace(excludeLayer);
6498 } else {
6499 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6500 return NAME_NOT_FOUND;
6501 }
6502 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006503
arthurhung79e81aa2020-08-28 00:09:19 +08006504 // The dataspace is depended on the color mode of display, that could use non-native mode
6505 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6506 // and failed if display is not in native mode. This provide a way to force using native
6507 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006508 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006509 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006510
Chia-I Wu20261cb2018-08-23 12:55:44 -07006511 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006512 if (reqSize.width <= 0 || reqSize.height <= 0) {
6513 ALOGW("Failed to captureLayes: crop or scale too small");
6514 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006515 }
6516
chaviw79468ab2021-10-27 11:11:24 -05006517 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006518 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006519 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006520 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006521 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006522 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006523 });
6524
chaviw03900772020-08-18 12:34:51 -07006525 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006526 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6527 if (!layer->isVisible()) {
6528 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006529 } else if (args.childrenOnly && layer == parent.get()) {
6530 return;
6531 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006532 return;
chaviwa76b2712017-09-20 12:02:26 -07006533 }
Robert Carr866455f2019-04-02 16:28:26 -07006534
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006535 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006536 while (p != nullptr) {
6537 if (excludeLayers.count(p) != 0) {
6538 return;
6539 }
6540 p = p->getParent();
6541 }
6542
chaviwa76b2712017-09-20 12:02:26 -07006543 visitor(layer);
6544 });
6545 };
Robert Carr108b2c72019-04-02 16:32:58 -07006546
Sally Qi59a9f502021-10-12 18:53:23 +00006547 if (captureListener == nullptr) {
6548 ALOGE("capture screen must provide a capture listener callback");
6549 return BAD_VALUE;
6550 }
6551
6552 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6553 reqSize, args.pixelFormat, args.allowProtected,
6554 args.grayscale, captureListener);
6555 return captureResultFuture.get().status;
chaviwa76b2712017-09-20 12:02:26 -07006556}
6557
Sally Qi59a9f502021-10-12 18:53:23 +00006558std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
6559 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6560 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6561 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006562 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006563
Garfield Tan9c9c1912021-07-19 12:02:16 -07006564 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6565 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6566 ") that exceeds render target size limit.",
6567 bufferSize.getWidth(), bufferSize.getHeight());
Sally Qi59a9f502021-10-12 18:53:23 +00006568 return ftl::yield<renderengine::RenderEngineResult>({BAD_VALUE, base::unique_fd()}).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006569 }
6570
Peiyong Lin05cc0112020-10-14 16:16:37 -07006571 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6572 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6573 // A protected layer has no implication on whether it's secure, which is explicitly set by
6574 // application to avoid being screenshot or drawn via unsecure display.
6575 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6576 bool hasProtectedLayer = false;
6577 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006578 auto future = mScheduler->schedule([=]() {
6579 bool protectedLayerFound = false;
6580 traverseLayers([&](Layer* layer) {
6581 protectedLayerFound =
6582 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6583 });
6584 return protectedLayerFound;
6585 });
6586 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006587 }
6588
Richard Liucbcb8952020-04-08 10:51:55 +00006589 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6590 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006591 (hasProtectedLayer && allowProtected && supportsProtected
6592 ? GRALLOC_USAGE_PROTECTED
6593 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006594 sp<GraphicBuffer> buffer =
6595 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6596 static_cast<android_pixel_format>(reqPixelFormat),
6597 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006598
6599 const status_t bufferStatus = buffer->initCheck();
6600 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6601 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006602 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6603 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6604 renderengine::impl::ExternalTexture::Usage::
6605 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006606 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006607 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006608}
6609
Sally Qi59a9f502021-10-12 18:53:23 +00006610std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006611 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6612 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6613 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006614 ATRACE_CALL();
6615
chaviwf5bb97b2021-04-28 15:35:37 -05006616 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006617
Dominik Laskowski756b7892021-08-04 12:53:59 -07006618 auto scheduleResultFuture = mScheduler->schedule([=,
6619 renderAreaFuture =
6620 std::move(renderAreaFuture)]() mutable
6621 -> std::shared_future<
6622 renderengine::RenderEngineResult> {
chaviw03900772020-08-18 12:34:51 -07006623 ScreenCaptureResults captureResults;
6624 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6625 if (!renderArea) {
6626 ALOGW("Skipping screen capture because of invalid render area.");
6627 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006628 captureListener->onScreenCaptureCompleted(captureResults);
Sally Qi59a9f502021-10-12 18:53:23 +00006629 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()})
6630 .share();
chaviw03900772020-08-18 12:34:51 -07006631 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006632
Sally Qi59a9f502021-10-12 18:53:23 +00006633 std::shared_future<renderengine::RenderEngineResult> renderEngineResultFuture;
6634
chaviw03900772020-08-18 12:34:51 -07006635 renderArea->render([&] {
Sally Qi59a9f502021-10-12 18:53:23 +00006636 renderEngineResultFuture =
Robert Carr12a3b9b2022-03-10 09:55:29 -08006637 renderScreenImpl(*renderArea, traverseLayers, buffer,
Sally Qi59a9f502021-10-12 18:53:23 +00006638 canCaptureBlackoutContent, regionSampling, grayscale,
6639 captureResults);
chaviw03900772020-08-18 12:34:51 -07006640 });
Sally Qi59a9f502021-10-12 18:53:23 +00006641 // spring up a thread to unblock SF main thread and wait for
6642 // RenderEngineResult to be available
6643 if (captureListener != nullptr) {
6644 std::async([=]() mutable {
6645 ATRACE_NAME("captureListener is nonnull!");
6646 auto& [status, drawFence] = renderEngineResultFuture.get();
6647 captureResults.result = status;
6648 captureResults.fence = new Fence(dup(drawFence));
6649 captureListener->onScreenCaptureCompleted(captureResults);
6650 });
6651 }
6652 return renderEngineResultFuture;
6653 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006654
Sally Qi59a9f502021-10-12 18:53:23 +00006655 // flatten scheduleResultFuture object to single shared_future object
6656 if (captureListener == nullptr) {
6657 std::future<renderengine::RenderEngineResult> captureScreenResultFuture =
6658 ftl::chain(std::move(scheduleResultFuture))
6659 .then([=](std::shared_future<renderengine::RenderEngineResult> futureObject)
6660 -> renderengine::RenderEngineResult {
6661 auto& [status, drawFence] = futureObject.get();
6662 return {status, base::unique_fd(dup(drawFence))};
6663 });
6664 return captureScreenResultFuture.share();
6665 } else {
6666 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()}).share();
6667 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006668}
6669
Robert Carr12a3b9b2022-03-10 09:55:29 -08006670std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006671 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006672 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6673 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6674 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006675 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006676
chaviw426b5c02020-07-27 11:20:15 -07006677 traverseLayers([&](Layer* layer) {
6678 captureResults.capturedSecureLayers =
6679 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6680 });
6681
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006682 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006683
chaviw426b5c02020-07-27 11:20:15 -07006684 // We allow the system server to take screenshots of secure layers for
6685 // use in situations like the Screen-rotation animation and place
6686 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006687 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006688 ALOGW("FB is protected: PERMISSION_DENIED");
Sally Qi59a9f502021-10-12 18:53:23 +00006689 return ftl::yield<renderengine::RenderEngineResult>({PERMISSION_DENIED, base::unique_fd()})
6690 .share();
chaviw426b5c02020-07-27 11:20:15 -07006691 }
6692
Alec Mouria90a5702021-04-16 16:36:21 +00006693 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006694 auto dataspace = renderArea.getReqDataSpace();
6695 auto parent = renderArea.getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00006696 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07006697 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
6698 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
6699
Robert Carr12a3b9b2022-03-10 09:55:29 -08006700 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6701 Mutex::Autolock lock(mStateLock);
6702 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6703 return display.getLayerStack() == layerStack;
6704 });
6705 if (!display) {
6706 // If the layer is not on a display, use the dataspace for the default display.
6707 display = getDefaultDisplayDeviceLocked();
6708 }
6709
6710 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6711 dataspace = pickDataspaceFromColorMode(colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00006712 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07006713 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
6714 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08006715 }
6716 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006717
chaviwa76b2712017-09-20 12:02:26 -07006718 const auto reqWidth = renderArea.getReqWidth();
6719 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006720 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006721 const auto transform = renderArea.getTransform();
6722 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006723 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006724
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006725 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006726 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006727
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006728 // assume that bounds are never offset, and that they are the same as the
6729 // buffer bounds.
6730 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006731 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006732 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006733
Robert Carr12a3b9b2022-03-10 09:55:29 -08006734 clientCompositionDisplay.outputDataspace = dataspace;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006735 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006736 clientCompositionDisplay.renderIntent =
6737 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006738
chaviw17ac24b2021-01-28 18:50:05 -08006739 const float colorSaturation = grayscale ? 0 : 1;
6740 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6741
chaviw50da5042018-04-09 13:49:37 -07006742 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006743
Vishnu Nair9b079a22020-01-21 14:36:08 -08006744 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006745 fillLayer.source.buffer.buffer = nullptr;
6746 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006747 fillLayer.geometry.boundaries =
6748 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006749 fillLayer.alpha = half(alpha);
6750 clientCompositionLayers.push_back(fillLayer);
6751
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006752 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006753 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006754 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006755 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006756 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006757
Lloyd Piquef16688f2019-02-19 17:47:57 -08006758 Region clip(renderArea.getBounds());
6759 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6760 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006761 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006762 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006763 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006764 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006765 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006766 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006767 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006768 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006769 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6770 BlurSetting::Disabled
6771 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6772 BlurSetting::Enabled,
Sally Qidb653012022-05-04 13:12:22 -07006773 isHdrLayer(layer) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006774
Lloyd Piquef16688f2019-02-19 17:47:57 -08006775 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006776 std::vector<compositionengine::LayerFE::LayerSettings> results =
6777 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006778 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006779 for (auto& settings : results) {
6780 settings.geometry.positionTransform =
6781 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006782 // There's no need to process blurs when we're executing region sampling,
6783 // we're just trying to understand what we're drawing, and doing so without
6784 // blurs is already a pretty good approximation.
6785 if (regionSampling) {
6786 settings.backgroundBlurRadius = 0;
6787 }
Sally Qidb653012022-05-04 13:12:22 -07006788 captureResults.capturedHdrLayers |= isHdrLayer(layer);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006789 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006790
Yichi Chen40773d92020-04-01 10:10:18 +08006791 clientCompositionLayers.insert(clientCompositionLayers.end(),
6792 std::make_move_iterator(results.begin()),
6793 std::make_move_iterator(results.end()));
6794 renderedLayers.push_back(layer);
6795 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006796
chaviwa76b2712017-09-20 12:02:26 -07006797 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006798
Sally Qi59a9f502021-10-12 18:53:23 +00006799 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6800 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006801 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006802 std::back_inserter(clientRenderEngineLayers),
6803 [](compositionengine::LayerFE::LayerSettings& settings)
6804 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006805
Alec Mouri6338c9d2019-02-07 16:57:51 -08006806 // Use an empty fence for the buffer fence, since we just created the buffer so
6807 // there is no need for synchronization with the GPU.
6808 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006809 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006810
Alec Mouria90a5702021-04-16 16:36:21 +00006811 const constexpr bool kUseFramebufferCache = false;
Sally Qi59a9f502021-10-12 18:53:23 +00006812 std::future<renderengine::RenderEngineResult> drawLayersResult =
6813 getRenderEngine().drawLayers(clientCompositionDisplay, clientRenderEngineLayers, buffer,
6814 kUseFramebufferCache, std::move(bufferFence));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006815
Sally Qi59a9f502021-10-12 18:53:23 +00006816 std::shared_future<renderengine::RenderEngineResult> drawLayersResultFuture =
6817 drawLayersResult.share(); // drawLayersResult will be moved to shared one
6818
6819 for (auto* layer : renderedLayers) {
6820 // make a copy of shared_future object for each layer
6821 layer->onLayerDisplayed(drawLayersResultFuture);
Yichi Chen40773d92020-04-01 10:10:18 +08006822 }
Ady Abraham99599942021-01-27 20:27:23 -08006823
Peiyong Lin05cc0112020-10-14 16:16:37 -07006824 // Always switch back to unprotected context.
6825 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006826
Sally Qi59a9f502021-10-12 18:53:23 +00006827 return drawLayersResultFuture;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006828}
6829
chaviwbf023a62021-06-07 16:00:06 -05006830void SurfaceFlinger::windowInfosReported() {
chaviw95ef3c42019-02-14 10:55:09 -08006831 Mutex::Autolock _l(mStateLock);
Arthur Hung2274a312021-04-28 15:13:06 +00006832 signalSynchronousTransactions(CountDownLatch::eSyncInputWindows);
chaviw95ef3c42019-02-14 10:55:09 -08006833}
chaviw5f21a5e2019-02-14 10:00:34 -08006834
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006835// ---------------------------------------------------------------------------
6836
Edgar Arriaga844fa672020-01-16 14:21:42 -08006837void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6838 layersSortedByZ.traverse(visitor);
6839}
6840
Dan Stoza412903f2017-04-27 13:42:17 -07006841void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6842 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006843}
6844
Dan Stoza412903f2017-04-27 13:42:17 -07006845void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6846 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006847}
6848
chaviw4b9d5e12020-08-04 18:30:35 -07006849void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006850 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006851 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006852 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006853 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006854 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006855 continue;
6856 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006857 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006858 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006859 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006860 return;
6861 }
chaviwa76b2712017-09-20 12:02:26 -07006862 if (!layer->isVisible()) {
6863 return;
6864 }
chaviw4b9d5e12020-08-04 18:30:35 -07006865 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6866 return;
6867 }
chaviwa76b2712017-09-20 12:02:26 -07006868 visitor(layer);
6869 });
6870 }
6871}
6872
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006873status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006874 const sp<DisplayDevice>& display,
6875 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006876 Mutex::Autolock lock(mStateLock);
6877
Ady Abrahamfb853662021-04-09 11:46:40 -07006878 if (mDebugDisplayModeSetByBackdoor) {
6879 // ignore this request as mode is overridden by backdoor
6880 return NO_ERROR;
6881 }
6882
Ady Abraham3efa3942021-06-24 19:01:25 -07006883 status_t setPolicyResult = overridePolicy
6884 ? display->refreshRateConfigs().setOverridePolicy(policy)
6885 : display->refreshRateConfigs().setDisplayManagerPolicy(*policy);
6886 if (setPolicyResult < 0) {
6887 return BAD_VALUE;
6888 }
6889 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6890 return NO_ERROR;
6891 }
6892
Ady Abraham3efa3942021-06-24 19:01:25 -07006893 scheduler::RefreshRateConfigs::Policy currentPolicy =
6894 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006895
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006896 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006897
Ana Krulecb9afd792020-06-11 13:16:15 -07006898 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6899 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006900 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006901 if (isDisplayActiveLocked(display)) {
6902 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6903 toggleKernelIdleTimer();
6904 } else {
6905 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6906 }
Ady Abraham838de062019-02-04 10:24:03 -08006907
Ady Abraham690f4612021-07-01 23:24:03 -07006908 const DisplayModePtr preferredDisplayMode = [&] {
6909 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6910 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6911 return schedulerMode;
6912 }
6913
6914 return display->getMode(currentPolicy.defaultMode);
6915 }();
6916
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006917 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006918 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006919
Ady Abraham690f4612021-07-01 23:24:03 -07006920 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006921 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006922 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006923 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006924 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006925 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006926 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006927 }
6928
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006929 return NO_ERROR;
6930}
6931
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006932status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6933 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6934 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6935 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006936 ATRACE_CALL();
6937
6938 if (!displayToken) {
6939 return BAD_VALUE;
6940 }
6941
Dominik Laskowski756b7892021-08-04 12:53:59 -07006942 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006943 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006944 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006945 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006946 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006947 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006948 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006949 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006950 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006951 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006952 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006953 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006954 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006955 {Fps::fromValue(primaryRefreshRateMin),
6956 Fps::fromValue(primaryRefreshRateMax)},
6957 {Fps::fromValue(appRequestRefreshRateMin),
6958 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006959 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006960
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006961 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006962 }
6963 });
6964
6965 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006966}
6967
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006968status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6969 ui::DisplayModeId* outDefaultMode,
6970 bool* outAllowGroupSwitching,
6971 float* outPrimaryRefreshRateMin,
6972 float* outPrimaryRefreshRateMax,
6973 float* outAppRequestRefreshRateMin,
6974 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006975 ATRACE_CALL();
6976
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006977 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006978 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006979 return BAD_VALUE;
6980 }
6981
6982 Mutex::Autolock lock(mStateLock);
6983 const auto display = getDisplayDeviceLocked(displayToken);
6984 if (!display) {
6985 return NAME_NOT_FOUND;
6986 }
6987
Ady Abraham3efa3942021-06-24 19:01:25 -07006988 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006989 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006990 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006991
6992 scheduler::RefreshRateConfigs::Policy policy =
6993 display->refreshRateConfigs().getDisplayManagerPolicy();
6994 *outDefaultMode = policy.defaultMode.value();
6995 *outAllowGroupSwitching = policy.allowGroupSwitching;
6996 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6997 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6998 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6999 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
7000 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07007001}
7002
Vishnu Nairf9096652021-07-20 18:49:42 -07007003wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
7004 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07007005}
7006
Dominik Laskowski75848362019-11-11 17:57:20 -08007007void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007008 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07007009 if (!layer->isRemovedFromCurrentState()) {
7010 mScheduler->registerLayer(layer);
7011 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007012}
7013
7014void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
7015 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07007016 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07007017 if (!layer->isRemovedFromCurrentState()) {
7018 mScheduler->deregisterLayer(layer);
7019 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08007020 if (mTransactionTracing) {
7021 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08007022 }
Valerie Hauc5686802019-11-22 14:18:09 -08007023}
7024
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007025void SurfaceFlinger::onLayerUpdate() {
7026 scheduleCommit(FrameHint::kActive);
7027}
7028
Valerie Hauc5686802019-11-22 14:18:09 -08007029// WARNING: ONLY CALL THIS FROM LAYER DTOR
7030// Here we add children in the current state to offscreen layers and remove the
7031// layer itself from the offscreen layer list. Since
7032// this is the dtor, it is safe to access the current state. This keeps us
7033// from dangling children layers such that they are not reachable from the
7034// Drawing state nor the offscreen layer list
7035// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07007036void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08007037 for (auto& child : layer->getCurrentChildren()) {
7038 mOffscreenLayers.emplace(child.get());
7039 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007040 mOffscreenLayers.erase(layer);
7041}
7042
Robert Carr867be372021-06-29 17:36:02 -07007043void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
7044 mOffscreenLayers.erase(layer);
7045}
7046
Vishnu Nair08f6eae2019-11-26 14:01:39 -08007047status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
7048 float lightPosY, float lightPosZ,
7049 float lightRadius) {
7050 Mutex::Autolock _l(mStateLock);
7051 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
7052 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
7053 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
7054 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
7055 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
7056
7057 // these values are overridden when calculating the shadow settings for a layer.
7058 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
7059 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08007060 return NO_ERROR;
7061}
7062
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007063const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
7064 const {
7065 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
7066 // on the work to remove the table in that bug rather than adding more to
7067 // it.
7068 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007069 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
7070 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007071 };
7072 return genericLayerMetadataKeyMap;
7073}
7074
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007075status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7076 PhysicalDisplayId displayId = [&]() {
7077 Mutex::Autolock lock(mStateLock);
7078 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7079 }();
7080
7081 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7082 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7083 return NO_ERROR;
7084}
7085
Dominik Laskowski20134642020-04-20 22:36:44 -07007086void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007087 for (const auto& [ignored, display] : mDisplays) {
7088 if (display->isInternal()) {
7089 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007090 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007091 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007092}
7093
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007094status_t SurfaceFlinger::addTransactionTraceListener(
7095 const sp<gui::ITransactionTraceListener>& listener) {
7096 if (!listener) {
7097 return BAD_VALUE;
7098 }
7099
7100 mInterceptor->addTransactionTraceListener(listener);
7101
7102 return NO_ERROR;
7103}
7104
Huihong Luo02186fb2022-02-23 14:21:54 -08007105int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007106 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007107}
7108
Ady Abraham899dcdb2021-06-15 16:56:21 -07007109int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7110 std::chrono::nanoseconds presentLatency) {
7111 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7112 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007113 pipelineDepth++;
7114 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007115 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007116}
7117
Ady Abraham899dcdb2021-06-15 16:56:21 -07007118status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007119 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007120
7121 if (!getHwComposer().isHeadless()) {
7122 if (const auto display = getDefaultDisplayDevice()) {
7123 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007124 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007125 }
7126
7127 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007128 return NO_ERROR;
7129}
7130
rnleeed20fa42021-08-10 18:00:03 -07007131uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007132 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007133
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007134 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7135 refreshRate = *frameRateOverride;
7136 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007137 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007138 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007139 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007140 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007141
Ady Abraham899dcdb2021-06-15 16:56:21 -07007142 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7143}
7144
7145int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7146 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7147 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7148 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7149}
7150
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007151void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state) {
7152 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007153 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007154 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7155 return;
arthurhungdba591c2021-02-08 17:28:49 +08007156 }
7157
7158 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007159 bool addToRoot = state.addToRoot;
7160 if (state.initialParent != nullptr) {
7161 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007162 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007163 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007164 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007165 }
arthurhungdba591c2021-02-08 17:28:49 +08007166 }
7167
Garfield Tand712ad32021-10-27 13:44:22 -07007168 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007169 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007170 mCurrentState.layersSortedByZ.add(layer);
7171 } else if (parent == nullptr) {
7172 layer->onRemovedFromCurrentState();
7173 } else if (parent->isRemovedFromCurrentState()) {
7174 parent->addChild(layer);
7175 layer->onRemovedFromCurrentState();
7176 } else {
7177 parent->addChild(layer);
7178 }
7179
Ady Abraham1273ac12021-08-26 17:31:53 -07007180 layer->updateTransformHint(mActiveDisplayTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +08007181
Arthur Hung23e07502021-10-15 11:58:19 +00007182 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007183}
Ady Abraham562c2712021-05-07 15:10:42 -07007184
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007185void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007186 if (!mLumaSampling || !mRegionSamplingThread) {
7187 return;
7188 }
7189
Dominik Laskowski756b7892021-08-04 12:53:59 -07007190 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007191}
7192
Ady Abrahamed3290f2021-05-17 15:12:14 -07007193void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7194 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7195 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7196}
7197
7198void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7199 ATRACE_CALL();
7200
Ady Abrahamdb036a82021-07-16 14:18:34 -07007201 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7202 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7203 }
7204
Ady Abrahamed3290f2021-05-17 15:12:14 -07007205 if (!activeDisplay) {
7206 ALOGE("%s: activeDisplay is null", __func__);
7207 return;
7208 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007209 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007210 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007211 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007212 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007213 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007214 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007215 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007216
7217 // Update the kernel timer for the current active display, since the policy
7218 // for this display might have changed when it was not the active display.
7219 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007220}
7221
chaviw60c9d3e2021-06-04 12:52:17 -05007222status_t SurfaceFlinger::addWindowInfosListener(
7223 const sp<IWindowInfosListener>& windowInfosListener) const {
7224 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7225 return NO_ERROR;
7226}
7227
7228status_t SurfaceFlinger::removeWindowInfosListener(
7229 const sp<IWindowInfosListener>& windowInfosListener) const {
7230 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7231 return NO_ERROR;
7232}
7233
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007234std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7235 const BufferData& bufferData, const char* layerName) const {
7236 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7237 bool bufferSizeExceedsLimit = false;
7238 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7239 if (cacheIdChanged && bufferData.buffer != nullptr) {
7240 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7241 bufferData.buffer->getHeight());
7242 if (!bufferSizeExceedsLimit) {
7243 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7244 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7245 }
7246 } else if (cacheIdChanged) {
7247 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7248 } else if (bufferData.buffer != nullptr) {
7249 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7250 bufferData.buffer->getHeight());
7251 if (!bufferSizeExceedsLimit) {
7252 buffer = std::make_shared<
7253 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7254 renderengine::impl::ExternalTexture::
7255 Usage::READABLE);
7256 }
7257 }
7258 ALOGE_IF(bufferSizeExceedsLimit,
7259 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7260 "limit.",
7261 layerName);
7262 return buffer;
7263}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007264
7265bool SurfaceFlinger::commitCreatedLayers() {
7266 std::vector<LayerCreatedState> createdLayers;
7267 {
7268 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7269 createdLayers = std::move(mCreatedLayers);
7270 mCreatedLayers.clear();
7271 if (createdLayers.size() == 0) {
7272 return false;
7273 }
7274 }
7275
7276 Mutex::Autolock _l(mStateLock);
7277 for (const auto& createdLayer : createdLayers) {
7278 handleLayerCreatedLocked(createdLayer);
7279 }
7280 createdLayers.clear();
7281 mLayersAdded = true;
7282 return true;
7283}
Huihong Luof5029222021-12-16 14:33:46 -08007284
7285// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007286
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007287binder::Status SurfaceComposerAIDL::bootFinished() {
7288 status_t status = checkAccessPermission();
7289 if (status != OK) {
7290 return binderStatusFromStatusT(status);
7291 }
7292 mFlinger->bootFinished();
7293 return binder::Status::ok();
7294}
7295
7296binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7297 VsyncSource vsyncSource, EventRegistration eventRegistration,
7298 sp<IDisplayEventConnection>* outConnection) {
7299 sp<IDisplayEventConnection> conn =
7300 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration);
7301 if (conn == nullptr) {
7302 *outConnection = nullptr;
7303 return binderStatusFromStatusT(BAD_VALUE);
7304 } else {
7305 *outConnection = conn;
7306 return binder::Status::ok();
7307 }
7308}
7309
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007310binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
7311 const sp<Client> client = new Client(mFlinger);
7312 if (client->initCheck() == NO_ERROR) {
7313 *outClient = client;
7314 return binder::Status::ok();
7315 } else {
7316 *outClient = nullptr;
7317 return binderStatusFromStatusT(BAD_VALUE);
7318 }
7319}
7320
Huihong Luo07e72362022-02-14 14:26:04 -08007321binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7322 sp<IBinder>* outDisplay) {
7323 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007324 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007325 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007326 }
Huihong Luo37396db2022-02-15 10:43:00 -08007327 String8 displayName8 = String8::format("%s", displayName.c_str());
7328 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7329 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007330}
7331
7332binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7333 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007334 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007335 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007336 }
Huihong Luo37396db2022-02-15 10:43:00 -08007337 mFlinger->destroyDisplay(display);
7338 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007339}
7340
7341binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7342 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7343 std::vector<int64_t> displayIds;
7344 displayIds.reserve(physicalDisplayIds.size());
7345 for (auto item : physicalDisplayIds) {
7346 displayIds.push_back(static_cast<int64_t>(item.value));
7347 }
7348 *outDisplayIds = displayIds;
7349 return binder::Status::ok();
7350}
7351
7352binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7353 status_t status = checkAccessPermission();
7354 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007355 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007356 }
7357
7358 PhysicalDisplayId id;
7359 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7360 if (status == NO_ERROR) {
7361 *outDisplayId = id.value;
7362 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007363 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007364}
7365
7366binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7367 sp<IBinder>* outDisplay) {
7368 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7369 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7370 return binder::Status::ok();
7371}
7372
Huihong Luo37396db2022-02-15 10:43:00 -08007373binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7374 status_t status = checkAccessPermission();
7375 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007376 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007377 }
7378 mFlinger->setPowerMode(display, mode);
7379 return binder::Status::ok();
7380}
7381
Huihong Luo0a81aa32022-02-22 16:02:36 -08007382binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7383 std::vector<FrameEvent>* outSupported) {
7384 status_t status;
7385 if (!outSupported) {
7386 status = UNEXPECTED_NULL;
7387 } else {
7388 outSupported->clear();
7389 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7390 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007391 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007392}
7393
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007394binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7395 gui::DisplayStatInfo* outStatInfo) {
7396 DisplayStatInfo statInfo;
7397 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7398 if (status == NO_ERROR) {
7399 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7400 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7401 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007402 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007403}
7404
7405binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7406 gui::DisplayState* outState) {
7407 ui::DisplayState state;
7408 status_t status = mFlinger->getDisplayState(display, &state);
7409 if (status == NO_ERROR) {
7410 outState->layerStack = state.layerStack.id;
7411 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7412 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7413 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7414 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007415 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007416}
7417
Huihong Luoa79ddf42022-02-17 00:01:38 -08007418binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7419 gui::StaticDisplayInfo* outInfo) {
7420 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7421 ui::StaticDisplayInfo info;
7422 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7423 if (status == NO_ERROR) {
7424 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7425 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7426 outInfo->density = info.density;
7427 outInfo->secure = info.secure;
7428 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7429
7430 gui::DeviceProductInfo dinfo;
7431 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7432 dinfo.name = std::move(dpi->name);
7433 dinfo.manufacturerPnpId =
7434 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7435 dinfo.productId = dpi->productId;
7436 if (const auto* model =
7437 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7438 gui::DeviceProductInfo::ModelYear modelYear;
7439 modelYear.year = model->year;
7440 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7441 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7442 &dpi->manufactureOrModelDate)) {
7443 gui::DeviceProductInfo::ManufactureYear date;
7444 date.modelYear.year = manufacture->year;
7445 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7446 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7447 &dpi->manufactureOrModelDate)) {
7448 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7449 date.manufactureYear.modelYear.year = manufacture->year;
7450 date.week = manufacture->week;
7451 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7452 }
7453
7454 outInfo->deviceProductInfo = dinfo;
7455 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007456 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007457}
7458
Huihong Luo38603fd2022-02-21 14:32:54 -08007459binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7460 gui::DynamicDisplayInfo* outInfo) {
7461 ui::DynamicDisplayInfo info;
7462 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7463 if (status == NO_ERROR) {
7464 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7465 outInfo->supportedDisplayModes.clear();
7466 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7467 for (const auto& mode : info.supportedDisplayModes) {
7468 gui::DisplayMode outMode;
7469 outMode.id = mode.id;
7470 outMode.resolution.width = mode.resolution.width;
7471 outMode.resolution.height = mode.resolution.height;
7472 outMode.xDpi = mode.xDpi;
7473 outMode.yDpi = mode.yDpi;
7474 outMode.refreshRate = mode.refreshRate;
7475 outMode.appVsyncOffset = mode.appVsyncOffset;
7476 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7477 outMode.presentationDeadline = mode.presentationDeadline;
7478 outMode.group = mode.group;
7479 outInfo->supportedDisplayModes.push_back(outMode);
7480 }
7481
7482 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7483
7484 outInfo->supportedColorModes.clear();
7485 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7486 for (const auto& cmode : info.supportedColorModes) {
7487 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7488 }
7489
7490 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7491
7492 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7493 hdrCapabilities.supportedHdrTypes.clear();
7494 hdrCapabilities.supportedHdrTypes.reserve(
7495 info.hdrCapabilities.getSupportedHdrTypes().size());
7496 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7497 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7498 }
7499 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7500 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7501 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7502
7503 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7504 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7505 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7506 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007507 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007508}
7509
Huihong Luoca3d9a42022-02-22 11:07:34 -08007510binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7511 gui::DisplayPrimaries* outPrimaries) {
7512 ui::DisplayPrimaries primaries;
7513 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7514 if (status == NO_ERROR) {
7515 outPrimaries->red.X = primaries.red.X;
7516 outPrimaries->red.Y = primaries.red.Y;
7517 outPrimaries->red.Z = primaries.red.Z;
7518
7519 outPrimaries->green.X = primaries.green.X;
7520 outPrimaries->green.Y = primaries.green.Y;
7521 outPrimaries->green.Z = primaries.green.Z;
7522
7523 outPrimaries->blue.X = primaries.blue.X;
7524 outPrimaries->blue.Y = primaries.blue.Y;
7525 outPrimaries->blue.Z = primaries.blue.Z;
7526
7527 outPrimaries->white.X = primaries.white.X;
7528 outPrimaries->white.Y = primaries.white.Y;
7529 outPrimaries->white.Z = primaries.white.Z;
7530 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007531 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007532}
7533
7534binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7535 status_t status = checkAccessPermission();
7536 if (status == OK) {
7537 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7538 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007539 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007540}
7541
7542binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7543 int displayModeId) {
7544 status_t status = checkAccessPermission();
7545 if (status == OK) {
7546 status = mFlinger->setBootDisplayMode(display,
7547 static_cast<ui::DisplayModeId>(displayModeId));
7548 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007549 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007550}
7551
Huihong Luo37396db2022-02-15 10:43:00 -08007552binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7553 status_t status = checkAccessPermission();
7554 if (status == OK) {
7555 status = mFlinger->clearBootDisplayMode(display);
7556 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007557 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007558}
7559
7560binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7561 status_t status = checkAccessPermission();
7562 if (status == OK) {
7563 status = mFlinger->getBootDisplayModeSupport(outMode);
7564 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007565 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007566}
7567
7568binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7569 status_t status = checkAccessPermission();
7570 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007571 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007572 }
7573 mFlinger->setAutoLowLatencyMode(display, on);
7574 return binder::Status::ok();
7575}
7576
7577binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7578 status_t status = checkAccessPermission();
7579 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007580 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007581 }
7582 mFlinger->setGameContentType(display, on);
7583 return binder::Status::ok();
7584}
7585
Huihong Luof5029222021-12-16 14:33:46 -08007586binder::Status SurfaceComposerAIDL::captureDisplay(
7587 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7588 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007589 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007590}
7591
7592binder::Status SurfaceComposerAIDL::captureDisplayById(
7593 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7594 status_t status;
7595 IPCThreadState* ipc = IPCThreadState::self();
7596 const int uid = ipc->getCallingUid();
7597 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7598 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7599 status = mFlinger->captureDisplay(*id, captureListener);
7600 } else {
7601 status = PERMISSION_DENIED;
7602 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007603 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007604}
7605
7606binder::Status SurfaceComposerAIDL::captureLayers(
7607 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7608 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007609 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007610}
7611
Huihong Luo4ed1c912022-02-22 14:30:01 -08007612binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7613 status_t status = checkAccessPermission();
7614 if (status == OK) {
7615 status = mFlinger->clearAnimationFrameStats();
7616 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007617 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007618}
7619
7620binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7621 status_t status = checkAccessPermission();
7622 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007623 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007624 }
7625
7626 FrameStats stats;
7627 status = mFlinger->getAnimationFrameStats(&stats);
7628 if (status == NO_ERROR) {
7629 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7630 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7631 for (const auto& t : stats.desiredPresentTimesNano) {
7632 outStats->desiredPresentTimesNano.push_back(t);
7633 }
7634 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7635 for (const auto& t : stats.actualPresentTimesNano) {
7636 outStats->actualPresentTimesNano.push_back(t);
7637 }
7638 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7639 for (const auto& t : stats.frameReadyTimesNano) {
7640 outStats->frameReadyTimesNano.push_back(t);
7641 }
7642 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007643 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007644}
7645
Huihong Luo05539a12022-02-23 10:29:40 -08007646binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7647 const std::vector<int32_t>& hdrTypes) {
7648 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7649 // permission dynamically. Don't use the permission cache for this check.
7650 status_t status = checkAccessPermission(false);
7651 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007652 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007653 }
7654
7655 std::vector<ui::Hdr> hdrTypesVector;
7656 for (int32_t i : hdrTypes) {
7657 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7658 }
7659 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007660 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007661}
7662
7663binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7664 status_t status;
7665 const int uid = IPCThreadState::self()->getCallingUid();
7666 if (uid != AID_SYSTEM) {
7667 status = PERMISSION_DENIED;
7668 } else {
7669 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7670 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007671 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007672}
7673
7674binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7675 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007676 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007677 }
7678
7679 status_t status = checkAccessPermission();
7680 if (status == OK) {
7681 status = mFlinger->enableVSyncInjections(enable);
7682 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007683 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007684}
7685
7686binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7687 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007688 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007689 }
7690
7691 status_t status = checkAccessPermission();
7692 if (status == OK) {
7693 status = mFlinger->injectVSync(when);
7694 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007695 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007696}
7697
7698binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7699 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007700 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007701 }
7702
7703 IPCThreadState* ipc = IPCThreadState::self();
7704 const int pid = ipc->getCallingPid();
7705 const int uid = ipc->getCallingUid();
7706 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7707 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007708 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007709 }
7710 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007711 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007712}
7713
7714binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7715 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007716 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007717}
7718
7719binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7720 ui::Dataspace dataspace;
7721 ui::PixelFormat pixelFormat;
7722 ui::Dataspace wideColorGamutDataspace;
7723 ui::PixelFormat wideColorGamutPixelFormat;
7724 status_t status =
7725 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7726 &wideColorGamutPixelFormat);
7727 if (status == NO_ERROR) {
7728 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7729 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7730 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7731 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7732 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007733 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007734}
7735
7736binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7737 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7738 status_t status = checkAccessPermission();
7739 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007740 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007741 }
7742
7743 ui::PixelFormat format;
7744 ui::Dataspace dataspace;
7745 uint8_t componentMask;
7746 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7747 &componentMask);
7748 if (status == NO_ERROR) {
7749 outAttrs->format = static_cast<int32_t>(format);
7750 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7751 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7752 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007753 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007754}
7755
7756binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7757 bool enable,
7758 int8_t componentMask,
7759 int64_t maxFrames) {
7760 status_t status = checkAccessPermission();
7761 if (status == OK) {
7762 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7763 static_cast<uint8_t>(componentMask),
7764 static_cast<uint64_t>(maxFrames));
7765 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007766 return binderStatusFromStatusT(status);
7767}
7768
7769binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7770 int64_t maxFrames, int64_t timestamp,
7771 gui::DisplayedFrameStats* outStats) {
7772 if (!outStats) {
7773 return binderStatusFromStatusT(BAD_VALUE);
7774 }
7775
7776 status_t status = checkAccessPermission();
7777 if (status != OK) {
7778 return binderStatusFromStatusT(status);
7779 }
7780
7781 DisplayedFrameStats stats;
7782 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7783 static_cast<uint64_t>(timestamp), &stats);
7784 if (status == NO_ERROR) {
7785 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7786 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7787 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7788 for (const auto& s : stats.component_0_sample) {
7789 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7790 }
7791 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7792 for (const auto& s : stats.component_1_sample) {
7793 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7794 }
7795 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7796 for (const auto& s : stats.component_2_sample) {
7797 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7798 }
7799 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7800 for (const auto& s : stats.component_3_sample) {
7801 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7802 }
7803 }
7804 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007805}
7806
7807binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7808 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007809 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007810}
7811
Huihong Luo37396db2022-02-15 10:43:00 -08007812binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7813 bool* outIsWideColorDisplay) {
7814 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007815 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007816}
7817
Huihong Luo02186fb2022-02-23 14:21:54 -08007818binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7819 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7820 const sp<gui::IRegionSamplingListener>& listener) {
7821 status_t status = checkReadFrameBufferPermission();
7822 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007823 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007824 }
7825 android::Rect rect;
7826 rect.left = samplingArea.left;
7827 rect.top = samplingArea.top;
7828 rect.right = samplingArea.right;
7829 rect.bottom = samplingArea.bottom;
7830 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007831 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007832}
7833
7834binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7835 const sp<gui::IRegionSamplingListener>& listener) {
7836 status_t status = checkReadFrameBufferPermission();
7837 if (status == OK) {
7838 status = mFlinger->removeRegionSamplingListener(listener);
7839 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007840 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007841}
7842
7843binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7844 const sp<gui::IFpsListener>& listener) {
7845 status_t status = checkReadFrameBufferPermission();
7846 if (status == OK) {
7847 status = mFlinger->addFpsListener(taskId, listener);
7848 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007849 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007850}
7851
7852binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7853 status_t status = checkReadFrameBufferPermission();
7854 if (status == OK) {
7855 status = mFlinger->removeFpsListener(listener);
7856 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007857 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007858}
7859
7860binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7861 const sp<gui::ITunnelModeEnabledListener>& listener) {
7862 status_t status = checkAccessPermission();
7863 if (status == OK) {
7864 status = mFlinger->addTunnelModeEnabledListener(listener);
7865 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007866 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007867}
7868
7869binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7870 const sp<gui::ITunnelModeEnabledListener>& listener) {
7871 status_t status = checkAccessPermission();
7872 if (status == OK) {
7873 status = mFlinger->removeTunnelModeEnabledListener(listener);
7874 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007875 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007876}
7877
7878binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7879 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7880 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7881 float appRequestRefreshRateMax) {
7882 status_t status = checkAccessPermission();
7883 if (status == OK) {
7884 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7885 static_cast<ui::DisplayModeId>(defaultMode),
7886 allowGroupSwitching, primaryRefreshRateMin,
7887 primaryRefreshRateMax,
7888 appRequestRefreshRateMin,
7889 appRequestRefreshRateMax);
7890 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007891 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007892}
7893
7894binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7895 gui::DisplayModeSpecs* outSpecs) {
7896 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007897 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007898 }
7899
7900 status_t status = checkAccessPermission();
7901 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007902 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007903 }
7904
7905 ui::DisplayModeId displayModeId;
7906 bool allowGroupSwitching;
7907 float primaryRefreshRateMin;
7908 float primaryRefreshRateMax;
7909 float appRequestRefreshRateMin;
7910 float appRequestRefreshRateMax;
7911 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7912 &allowGroupSwitching, &primaryRefreshRateMin,
7913 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7914 &appRequestRefreshRateMax);
7915 if (status == NO_ERROR) {
7916 outSpecs->defaultMode = displayModeId;
7917 outSpecs->allowGroupSwitching = allowGroupSwitching;
7918 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7919 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7920 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7921 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7922 }
7923
Huihong Luo3bdef862022-03-03 11:57:19 -08007924 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007925}
7926
Huihong Luo37396db2022-02-15 10:43:00 -08007927binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7928 bool* outSupport) {
7929 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007930 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007931}
7932
7933binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7934 const gui::DisplayBrightness& brightness) {
7935 status_t status = checkControlDisplayBrightnessPermission();
7936 if (status == OK) {
7937 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7938 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007939 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007940}
7941
7942binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7943 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7944 status_t status = checkControlDisplayBrightnessPermission();
7945 if (status == OK) {
7946 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7947 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007948 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007949}
7950
7951binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7952 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7953 status_t status = checkControlDisplayBrightnessPermission();
7954 if (status == OK) {
7955 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7956 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007957 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007958}
7959
7960binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7961 status_t status = checkAccessPermission();
7962 if (status == OK) {
7963 status = mFlinger->notifyPowerBoost(boostId);
7964 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007965 return binderStatusFromStatusT(status);
7966}
7967
7968binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7969 const gui::Color& spotColor,
7970 float lightPosY, float lightPosZ,
7971 float lightRadius) {
7972 status_t status = checkAccessPermission();
7973 if (status != OK) {
7974 return binderStatusFromStatusT(status);
7975 }
7976
7977 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7978 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7979 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7980 lightPosZ, lightRadius);
7981 return binderStatusFromStatusT(status);
7982}
7983
7984binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7985 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7986 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7987 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7988 if (status != NO_ERROR) {
7989 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7990 return binderStatusFromStatusT(status);
7991 }
7992
7993 if (!support || !support.has_value()) {
7994 outSupport->reset();
7995 } else {
7996 outSupport->emplace();
7997 outSupport->value().format = static_cast<int32_t>(support->format);
7998 outSupport->value().alphaInterpretation =
7999 static_cast<int32_t>(support->alphaInterpretation);
8000 }
8001
8002 return binder::Status::ok();
8003}
8004
8005binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
8006 status_t status;
8007 const int c_uid = IPCThreadState::self()->getCallingUid();
8008 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
8009 status = mFlinger->setOverrideFrameRate(uid, frameRate);
8010 } else {
8011 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
8012 status = PERMISSION_DENIED;
8013 }
8014 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008015}
8016
Huihong Luo02186fb2022-02-23 14:21:54 -08008017binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
8018 const sp<gui::ITransactionTraceListener>& listener) {
8019 status_t status;
8020 IPCThreadState* ipc = IPCThreadState::self();
8021 const int uid = ipc->getCallingUid();
8022 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
8023 status = mFlinger->addTransactionTraceListener(listener);
8024 } else {
8025 status = PERMISSION_DENIED;
8026 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008027 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008028}
8029
8030binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
8031 *outPriority = mFlinger->getGpuContextPriority();
8032 return binder::Status::ok();
8033}
8034
8035binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
8036 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08008037 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008038}
8039
8040binder::Status SurfaceComposerAIDL::addWindowInfosListener(
8041 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8042 status_t status;
8043 const int uid = IPCThreadState::self()->getCallingUid();
8044 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8045 status = mFlinger->addWindowInfosListener(windowInfosListener);
8046 } else {
8047 status = PERMISSION_DENIED;
8048 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008049 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008050}
8051
8052binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
8053 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8054 status_t status;
8055 const int uid = IPCThreadState::self()->getCallingUid();
8056 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8057 status = mFlinger->removeWindowInfosListener(windowInfosListener);
8058 } else {
8059 status = PERMISSION_DENIED;
8060 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008061 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008062}
8063
Huihong Luo07e72362022-02-14 14:26:04 -08008064status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
8065 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
8066 IPCThreadState* ipc = IPCThreadState::self();
8067 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
8068 ipc->getCallingUid());
8069 return PERMISSION_DENIED;
8070 }
8071 return OK;
8072}
8073
Huihong Luo37396db2022-02-15 10:43:00 -08008074status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
8075 IPCThreadState* ipc = IPCThreadState::self();
8076 const int pid = ipc->getCallingPid();
8077 const int uid = ipc->getCallingUid();
8078 if ((uid != AID_GRAPHICS) &&
8079 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
8080 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
8081 return PERMISSION_DENIED;
8082 }
8083 return OK;
8084}
8085
Huihong Luo02186fb2022-02-23 14:21:54 -08008086status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
8087 IPCThreadState* ipc = IPCThreadState::self();
8088 const int pid = ipc->getCallingPid();
8089 const int uid = ipc->getCallingUid();
8090 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
8091 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
8092 return PERMISSION_DENIED;
8093 }
8094 return OK;
8095}
8096
Dominik Laskowski9dab3432019-03-27 13:21:10 -07008097} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07008098
Mathias Agopian3f844832013-08-07 21:24:32 -07008099#if defined(__gl_h_)
8100#error "don't include gl/gl.h in this file"
8101#endif
8102
8103#if defined(__gl2_h_)
8104#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008105#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008106
8107// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008108#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"