blob: 3043809c8a7604f9c88541da0bd4f650747f418f [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020#pragma clang diagnostic ignored "-Wextra"
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080021
Alec Mourie7d1d4a2019-02-05 01:13:46 +000022//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080023#define ATRACE_TAG ATRACE_TAG_GRAPHICS
24
Alec Mouri5f487d42020-02-06 09:26:19 -080025#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080026
Dominik Laskowski298b08e2022-02-15 13:45:02 -080027#include <android-base/parseint.h>
Ana Krulecb9afd792020-06-11 13:16:15 -070028#include <android-base/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080029#include <android-base/stringprintf.h>
30#include <android-base/strings.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080031#include <android/configuration.h>
Huihong Luo6fac5232021-11-22 16:05:23 -080032#include <android/gui/IDisplayEventConnection.h>
Huihong Luoa79ddf42022-02-17 00:01:38 -080033#include <android/gui/StaticDisplayInfo.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080034#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
35#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
36#include <android/hardware/configstore/1.1/types.h>
Lais Andrade3a6e47d2020-04-02 11:20:16 +010037#include <android/hardware/power/Boost.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080038#include <android/native_window.h>
Chris Ye0783e992020-06-02 21:34:49 -070039#include <android/os/IInputFlinger.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070040#include <binder/IPCThreadState.h>
41#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070042#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070043#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080044#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070045#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070046#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070047#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080048#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080049#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070050#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070051#include <compositionengine/impl/OutputCompositionState.h>
John Reckdb1a16b2021-07-09 13:05:52 -040052#include <compositionengine/impl/OutputLayerCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080053#include <configstore/Utils.h>
54#include <cutils/compiler.h>
55#include <cutils/properties.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080056#include <ftl/fake_guard.h>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080057#include <ftl/future.h>
Dominik Laskowski9f410f02022-01-08 16:22:46 -080058#include <ftl/small_map.h>
Huihong Luo3bdef862022-03-03 11:57:19 -080059#include <gui/AidlStatusUtil.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070060#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070061#include <gui/DebugEGLImageTracker.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080062#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080063#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080064#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080065#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080066#include <gui/Surface.h>
rnlee60f46b52021-05-21 15:14:07 -070067#include <gui/TraceUtils.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000068#include <hidl/ServiceManagement.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080069#include <layerproto/LayerProtoParser.h>
70#include <log/log.h>
71#include <private/android_filesystem_config.h>
72#include <private/gui/SyncFeatures.h>
Wei Wang976a6452021-06-11 15:26:00 -070073#include <processgroup/processgroup.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070074#include <renderengine/RenderEngine.h>
Vishnu Nairdbbe3852022-01-12 20:22:11 -080075#include <renderengine/impl/ExternalTexture.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080076#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <ui/ColorSpace.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070078#include <ui/DataspaceUtils.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070079#include <ui/DebugUtils.h>
Marin Shalamanov045b7002021-01-07 16:56:24 +010080#include <ui/DisplayId.h>
Marin Shalamanova7fe3042021-01-29 21:02:08 +010081#include <ui/DisplayMode.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070082#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080083#include <ui/DisplayState.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010084#include <ui/DynamicDisplayInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070085#include <ui/GraphicBufferAllocator.h>
86#include <ui/PixelFormat.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010087#include <ui/StaticDisplayInfo.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070089#include <utils/String16.h>
90#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070091#include <utils/Timers.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070092#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093
Alec Mouri5f487d42020-02-06 09:26:19 -080094#include <algorithm>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080095#include <cerrno>
Alec Mouri5f487d42020-02-06 09:26:19 -080096#include <cinttypes>
97#include <cmath>
98#include <cstdint>
99#include <functional>
Xiang Wang839fe5b2022-04-04 17:39:38 +0000100#include <memory>
Alec Mouri5f487d42020-02-06 09:26:19 -0800101#include <mutex>
102#include <optional>
Michael Wright44753b12020-07-08 13:48:11 +0100103#include <type_traits>
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105
Alec Mouriff793872022-01-13 17:45:06 -0800106#include <ui/DisplayIdentification.h>
Vishnu Nair03ccbd62021-12-01 17:21:16 -0800107#include "BackgroundExecutor.h"
Robert Carr578038f2018-03-09 12:25:24 -0800108#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -0700109#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -0700110#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200111#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200112#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800113#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800114#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700115#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700116#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700117#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100118#include "DisplayHardware/Hal.h"
Xiang Wang839fe5b2022-04-04 17:39:38 +0000119#include "DisplayHardware/PowerAdvisor.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700120#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200121#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800122#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700123#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700124#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800125#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700126#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700127#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400128#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800129#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500130#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200131#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800132#include "LayerVector.h"
133#include "MonitoredProducer.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800134#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800135#include "NativeWindowSurface.h"
136#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700137#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700138#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700139#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700140#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700141#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700142#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700143#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800144#include "StartPropertySetThread.h"
145#include "SurfaceFlingerProperties.h"
146#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800147#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200148#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500149#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800150
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500151#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500152#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
Alec Mourifcedb9c2022-04-11 20:02:17 +0000153#include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500154
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700155#undef NO_THREAD_SAFETY_ANALYSIS
156#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800157 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500158
Tianhao Yao67dd7122022-02-22 17:48:33 +0000159// To enable layer borders in the system, change the below flag to true.
160#undef DOES_CONTAIN_BORDER
161#define DOES_CONTAIN_BORDER false
162
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700164
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700165using namespace std::string_literals;
166
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800167using namespace hardware::configstore;
168using namespace hardware::configstore::V1_0;
169using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800170
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800171using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
172using aidl::android::hardware::graphics::composer3::Capability;
173using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800174using CompositionStrategyPredictionState = android::compositionengine::impl::
175 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800176
Yiwei Zhang5434a782018-12-05 18:06:32 -0800177using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700178using gui::DisplayInfo;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800179using gui::GameMode;
Huihong Luo6fac5232021-11-22 16:05:23 -0800180using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500181using gui::IWindowInfosListener;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800182using gui::LayerMetadata;
chaviw98318de2021-05-19 16:45:23 -0500183using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800184using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700185using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700186using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800187using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700188using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900189
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800190using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
191
Peiyong Line9d809e2020-04-14 13:10:48 -0700192namespace hal = android::hardware::graphics::composer::hal;
193
Steven Thomasb02664d2017-07-26 18:48:28 -0700194namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700195
196#pragma clang diagnostic push
197#pragma clang diagnostic error "-Wswitch-enum"
198
199bool isWideColorMode(const ColorMode colorMode) {
200 switch (colorMode) {
201 case ColorMode::DISPLAY_P3:
202 case ColorMode::ADOBE_RGB:
203 case ColorMode::DCI_P3:
204 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700205 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700206 case ColorMode::BT2100_PQ:
207 case ColorMode::BT2100_HLG:
208 return true;
209 case ColorMode::NATIVE:
210 case ColorMode::STANDARD_BT601_625:
211 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
212 case ColorMode::STANDARD_BT601_525:
213 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
214 case ColorMode::STANDARD_BT709:
215 case ColorMode::SRGB:
216 return false;
217 }
218 return false;
219}
220
221#pragma clang diagnostic pop
222
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100223// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700224constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800225
226float getDensityFromProperty(const char* property, bool required) {
227 char value[PROPERTY_VALUE_MAX];
228 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
229 if (!density && required) {
230 ALOGE("%s must be defined as a build property", property);
231 return FALLBACK_DENSITY;
232 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700233 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800234}
235
Peiyong Lin9d846a52018-11-05 13:18:20 -0800236// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
237bool validateCompositionDataspace(Dataspace dataspace) {
238 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
239}
240
ramindani32cf0602022-03-02 02:30:29 +0000241std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700242 const auto displayIdleTimerMsKey = [displayId] {
243 std::stringstream ss;
244 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
245 return ss.str();
246 }();
247
ramindani32cf0602022-03-02 02:30:29 +0000248 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
249 if (displayIdleTimerMs > 0) {
250 return std::chrono::milliseconds(displayIdleTimerMs);
251 }
252
253 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
254 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
255 return std::chrono::milliseconds(millis);
256}
257
258bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700259 const auto displaySupportKernelIdleTimerKey = [displayId] {
260 std::stringstream ss;
261 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
262 return ss.str();
263 }();
264
Ady Abraham6d885932021-09-03 18:05:48 -0700265 const auto displaySupportKernelIdleTimer =
266 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000267 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700268}
269
Steven Thomasb02664d2017-07-26 18:48:28 -0700270} // namespace anonymous
271
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272// ---------------------------------------------------------------------------
273
Mathias Agopian99b49842011-06-27 16:05:52 -0700274const String16 sHardwareTest("android.permission.HARDWARE_TEST");
275const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800276const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700277const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400278const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700279const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500280const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000281const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500282
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800283const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700284
Vishnu Nair4fb00ed2022-06-03 10:25:09 -0700285static const int MAX_TRACING_MEMORY = 1024 * 1024 * 1024; // 1GB
286
Mathias Agopian99b49842011-06-27 16:05:52 -0700287// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700288int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700289bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800290bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800291int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100292uint32_t SurfaceFlinger::maxGraphicsWidth;
293uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600294bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700295bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700296Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
297ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
298Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
299ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000300LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700301
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800302std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
303 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800304 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700305 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800306 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700307 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800308 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700309 return std::string("Enhanced");
310 default:
311 return std::string("Unknown ") +
312 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800313 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800314}
315
Hongwei Wang46213ea2020-12-04 17:17:31 -0800316bool callingThreadHasRotateSurfaceFlingerAccess() {
317 IPCThreadState* ipc = IPCThreadState::self();
318 const int pid = ipc->getCallingPid();
319 const int uid = ipc->getCallingUid();
320 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
321 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
322}
323
Leon Scroggins9a20f722021-12-28 14:43:12 +0000324bool callingThreadHasInternalSystemWindowAccess() {
325 IPCThreadState* ipc = IPCThreadState::self();
326 const int pid = ipc->getCallingPid();
327 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500328 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
329 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000330}
331
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700332SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
333 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800334 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000335 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700336 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800337 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800338 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700339 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700340 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700341 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800342 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700343 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000344 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Dominik Laskowski91f635e2022-01-08 05:46:09 -0800345 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make(*this)) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700346 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700347}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800348
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700349SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800350 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800351
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900352 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900354 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700355
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900356 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700357
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900358 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800359
Brian Lindahla13f2d52020-03-05 11:54:17 +0100360 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
361 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
362
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900363 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900364 mDefaultCompositionDataspace =
365 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700366 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
367 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900368 defaultCompositionDataspace = mDefaultCompositionDataspace;
369 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
370 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
371 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
372 wideColorGamutCompositionPixelFormat =
373 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700374
Yichi Chenda901bf2019-06-28 14:58:27 +0800375 mColorSpaceAgnosticDataspace =
376 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
377
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700378 mLayerCachingEnabled = [] {
379 const bool enable =
380 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
381 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
382 }();
383
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900384 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800385
Sundong Ahn85131bd2019-02-18 15:51:53 +0900386 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800387
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388 // debugging stuff...
389 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700390
Mathias Agopianb4b17302013-03-20 18:36:41 -0700391 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700392 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700393
Alec Mouri5f487d42020-02-06 09:26:19 -0800394 property_get("ro.build.type", value, "user");
395 mIsUserBuild = strcmp(value, "user") == 0;
396
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700397 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000398
399 // DDMS debugging deprecated (b/120782499)
400 property_get("debug.sf.ddms", value, "0");
401 int debugDdms = atoi(value);
402 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700403
Ady Abrahamadb9a992019-09-19 21:21:55 +0000404 property_get("debug.sf.enable_gl_backpressure", value, "0");
405 mPropagateBackpressureClientComposition = atoi(value);
406 ALOGI_IF(mPropagateBackpressureClientComposition,
407 "Enabling backpressure propagation for Client Composition");
408
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800409 property_get("ro.surface_flinger.supports_background_blur", value, "0");
410 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700411 mSupportsBlur = supportsBlurs;
412 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800413 property_get("ro.sf.blurs_are_expensive", value, "0");
414 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800415
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700416 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700417 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
418 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800419 mGraphicBufferProducerListSizeLogThreshold =
420 std::max(static_cast<int>(0.95 *
421 static_cast<double>(mMaxGraphicBufferProducerListSize)),
422 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700423
Dan Stozaec460082018-12-17 15:35:09 -0800424 property_get("debug.sf.luma_sampling", value, "1");
425 mLumaSampling = atoi(value);
426
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800427 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800428 mDisableClientCompositionCache = atoi(value);
429
Vishnu Nair3539d812022-02-26 09:20:17 -0800430 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800431 mPredictCompositionStrategy = atoi(value);
432
Alec Mouridda07d92022-04-25 22:39:25 +0000433 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
434 mTreat170mAsSrgb = atoi(value);
435
Romain Guy11d63f42017-07-20 12:47:14 -0700436 // We should be reading 'persist.sys.sf.color_saturation' here
437 // but since /data may be encrypted, we need to wait until after vold
438 // comes online to attempt to read the property. The property is
439 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800440
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700441 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800442 // Without the override SurfaceFlinger cannot connect to HIDL
443 // services that are not listed in the manifests. Considered
444 // deriving the setting from the set service name, but it
445 // would be brittle if the name that's not 'default' is used
446 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700447 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000448 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800449 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800450
Ady Abraham29d0da32020-07-16 18:39:33 -0700451 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400452
Dominik Laskowski46471e62022-01-14 15:34:03 -0800453 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
454 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800455 }
John Reck49d9ad32022-02-23 19:03:31 -0500456
457 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
Matt Buckley50c44062022-01-17 20:48:10 +0000458
459 // Power hint session mode, representing which hint(s) to send: early, late, or both)
460 mPowerHintSessionMode =
461 {.late = base::GetBoolProperty("debug.sf.send_late_power_session_hint"s, true),
462 .early = base::GetBoolProperty("debug.sf.send_early_power_session_hint"s, true)};
ramindani4d48f902021-09-20 21:07:45 +0000463}
464
465LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
466 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
467 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000468 }
Ady Abraham9dada822022-02-03 10:26:59 -0800469
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000470 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800471 return LatchUnsignaledConfig::AutoSingleLayer;
472 }
473
474 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800475}
476
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700477SurfaceFlinger::~SurfaceFlinger() = default;
478
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700479void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800480 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700481 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800482
Dominik Laskowski756b7892021-08-04 12:53:59 -0700483 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000484 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800485
Andy McFadden13a082e2012-08-24 10:16:42 -0700486 // restore initial conditions (default device unblank, etc)
487 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800488
489 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700490 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800491}
492
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700493void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700494 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800495}
496
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700497sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700498 // onTransact already checks for some permissions, but adding an additional check here.
499 // This is to ensure that only system and graphics can request to create a secure
500 // display. Secure displays can show secure content so we add an additional restriction on it.
501 const int uid = IPCThreadState::self()->getCallingUid();
502 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
503 ALOGE("Only privileged processes can create a secure display");
504 return nullptr;
505 }
506
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507 class DisplayToken : public BBinder {
508 sp<SurfaceFlinger> flinger;
509 virtual ~DisplayToken() {
510 // no more references, this display must be terminated
511 Mutex::Autolock _l(flinger->mStateLock);
512 flinger->mCurrentState.displays.removeItem(this);
513 flinger->setTransactionFlags(eDisplayTransactionNeeded);
514 }
515 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700516 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700517 : flinger(flinger) {
518 }
519 };
520
521 sp<BBinder> token = new DisplayToken(this);
522
523 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700524 // Display ID is assigned when virtual display is allocated by HWC.
525 DisplayDeviceState state;
526 state.isSecure = secure;
527 state.displayName = displayName;
528 mCurrentState.displays.add(token, state);
529 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700530 return token;
531}
532
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700533void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700534 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700535
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700536 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700537 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800538 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700539 return;
540 }
541
Dominik Laskowski075d3172018-05-24 15:50:06 -0700542 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700543 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800544 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700545 return;
546 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700547 mInterceptor->saveDisplayDeletion(state.sequenceId);
548 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700549 setTransactionFlags(eDisplayTransactionNeeded);
550}
551
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800552void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
553 auto& generator = mVirtualDisplayIdGenerators.hal;
554 if (!generator && enable) {
555 ALOGI("Enabling HAL virtual displays");
556 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
557 } else if (generator && !enable) {
558 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
559 generator.reset();
560 }
561}
562
Dominik Laskowski263eec42021-07-21 23:13:24 -0700563VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
564 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800565 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
566 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700567 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800568 return *id;
569 }
570
571 generator->releaseId(*id);
572 } else {
573 ALOGW("%s: Exhausted HAL virtual displays", __func__);
574 }
575
576 ALOGW("%s: Falling back to GPU virtual display", __func__);
577 }
578
579 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
580 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
581 return *id;
582}
583
584void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
585 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
586 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
587 generator->releaseId(*id);
588 }
589 return;
590 }
591
592 const auto id = GpuVirtualDisplayId::tryCast(displayId);
593 LOG_ALWAYS_FATAL_IF(!id);
594 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
595}
596
Ady Abrahamed3290f2021-05-17 15:12:14 -0700597std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800598 std::vector<PhysicalDisplayId> displayIds;
599 displayIds.reserve(mPhysicalDisplayTokens.size());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700600
Dominik Laskowski3c363242022-04-07 10:44:12 -0700601 const auto defaultDisplayId = getDefaultDisplayDeviceLocked()->getPhysicalId();
Ady Abraham2a0066d2021-07-15 20:16:58 -0700602 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800603
604 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700605 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200606 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800607 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700608 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700609
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800610 return displayIds;
611}
612
Vishnu Nair8c8db542021-09-17 19:51:45 -0700613status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
614 Mutex::Autolock lock(mStateLock);
Dominik Laskowski3c363242022-04-07 10:44:12 -0700615 *id = getPrimaryDisplayIdLocked();
Vishnu Nair8c8db542021-09-17 19:51:45 -0700616 return NO_ERROR;
617}
618
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800619sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
620 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200621 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700622}
623
Ady Abraham37965d42018-11-01 13:43:32 -0700624status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
625 if (!outGetColorManagement) {
626 return BAD_VALUE;
627 }
628 *outGetColorManagement = useColorManagement;
629 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700630}
631
Lloyd Pique441d5042018-10-18 16:49:51 -0700632HWComposer& SurfaceFlinger::getHwComposer() const {
633 return mCompositionEngine->getHwComposer();
634}
635
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700636renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
637 return mCompositionEngine->getRenderEngine();
638}
639
Lloyd Pique70d91362018-10-18 16:02:55 -0700640compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
641 return *mCompositionEngine.get();
642}
643
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100644void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700645 if (mBootFinished == true) {
646 ALOGE("Extra call to bootFinished");
647 return;
648 }
649 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700650 if (mStartPropertySetThread->join() != NO_ERROR) {
651 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800652 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700653
654 if (mRenderEnginePrimeCacheFuture.valid()) {
655 mRenderEnginePrimeCacheFuture.get();
656 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800657 const nsecs_t now = systemTime();
658 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000659 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700660
Mikael Pessa90092f42019-08-26 17:22:04 -0700661 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700662 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700663 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700664
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700665 // wait patiently for the window manager death
666 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700667 mWindowManager = defaultServiceManager()->getService(name);
668 if (mWindowManager != 0) {
669 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700670 }
671
672 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700673 // formerly we would just kill the process, but we now ask it to exit so it
674 // can choose where to stop the animation.
675 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700676
677 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
678 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
679 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700680
Denis Hsue70cc6c2020-06-17 10:17:30 +0800681 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
682
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000683 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800684 if (input == nullptr) {
685 ALOGE("Failed to link to input service");
686 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700687 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800688 }
689
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800690 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000691 mPowerAdvisor->onBootFinished();
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000692 const bool powerHintEnabled = mFlagManager.use_adpf_cpu_hint();
693 mPowerAdvisor->enablePowerHint(powerHintEnabled);
694 const bool powerHintUsed = mPowerAdvisor->usePowerHintSession();
695 ALOGD("Power hint is %s",
696 powerHintUsed ? "supported" : (powerHintEnabled ? "unsupported" : "disabled"));
697 if (powerHintUsed) {
Xiang Wang76236e12022-03-22 17:25:30 +0000698 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
699 std::vector<int32_t> tidList;
700 tidList.emplace_back(gettid());
701 if (renderEngineTid.has_value()) {
702 tidList.emplace_back(*renderEngineTid);
703 }
Xiang Wang839fe5b2022-04-04 17:39:38 +0000704 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000705 ALOGW("Cannot start power hint session");
706 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000707 }
708
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800709 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800710
Ady Abraham8a82ba62020-01-17 12:43:17 -0800711 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800712 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800713 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800714 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800715}
716
Dan Stoza436ccf32018-06-21 12:10:12 -0700717uint32_t SurfaceFlinger::getNewTexture() {
718 {
719 std::lock_guard lock(mTexturePoolMutex);
720 if (!mTexturePool.empty()) {
721 uint32_t name = mTexturePool.back();
722 mTexturePool.pop_back();
723 ATRACE_INT("TexturePoolSize", mTexturePool.size());
724 return name;
725 }
726
727 // The pool was too small, so increase it for the future
728 ++mTexturePoolSize;
729 }
730
731 // The pool was empty, so we need to get a new texture name directly using a
732 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700733 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700734 uint32_t name = 0;
735 getRenderEngine().genTextures(1, &name);
736 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700737 };
738 if (std::this_thread::get_id() == mMainThreadId) {
739 return genTextures();
740 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700741 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700742 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700743}
744
Mathias Agopian3f844832013-08-07 21:24:32 -0700745void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700746 std::lock_guard lock(mTexturePoolMutex);
747 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
748 // to actually delete this or not based on mTexturePoolSize
749 mTexturePool.push_back(texture);
750 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700751}
752
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500753static std::optional<renderengine::RenderEngine::RenderEngineType>
754chooseRenderEngineTypeViaSysProp() {
755 char prop[PROPERTY_VALUE_MAX];
756 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
757
758 if (strcmp(prop, "gles") == 0) {
759 return renderengine::RenderEngine::RenderEngineType::GLES;
760 } else if (strcmp(prop, "threaded") == 0) {
761 return renderengine::RenderEngine::RenderEngineType::THREADED;
762 } else if (strcmp(prop, "skiagl") == 0) {
763 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
764 } else if (strcmp(prop, "skiaglthreaded") == 0) {
765 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
766 } else {
767 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
768 return {};
769 }
770}
771
Wei Wangf9b05ee2017-07-19 20:59:39 -0700772// Do not call property_set on main thread which will be blocked by init
773// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700774void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700775 ALOGI( "SurfaceFlinger's main thread ready to run. "
776 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700777 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800778
Steven Thomasb02664d2017-07-26 18:48:28 -0700779 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700780 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800781 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500782 auto builder = renderengine::RenderEngineCreationArgs::Builder()
783 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
784 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
785 .setUseColorManagerment(useColorManagement)
786 .setEnableProtectedContext(enable_protected_contents(false))
787 .setPrecacheToneMapperShaderOnly(false)
788 .setSupportsBackgroundBlur(mSupportsBlur)
789 .setContextPriority(
790 useContextPriority
791 ? renderengine::RenderEngine::ContextPriority::REALTIME
792 : renderengine::RenderEngine::ContextPriority::MEDIUM);
793 if (auto type = chooseRenderEngineTypeViaSysProp()) {
794 builder.setRenderEngineType(type.value());
795 }
796 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700797 mMaxRenderTargetSize =
798 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700799
800 // Set SF main policy after initializing RenderEngine which has its own policy.
801 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
802 ALOGW("Failed to set main task profile");
803 }
804
Alec Mourie4034bb2019-11-19 12:45:54 -0800805 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700806 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800807 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000808 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800809
Ady Abraham9dada822022-02-03 10:26:59 -0800810 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
811
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800812 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
813 enableHalVirtualDisplays(true);
814 }
815
Lloyd Piqueba04e622017-12-14 17:11:26 -0800816 // Process any initial hotplug and resulting display changes.
817 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700818 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700819 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200820 const auto displayId = display->getPhysicalId();
821 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700822 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800823
Mathias Agopian92a979a2012-08-02 18:32:23 -0700824 // initialize our drawing state
825 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700826
Andy McFadden13a082e2012-08-24 10:16:42 -0700827 // set initial conditions (e.g. unblank default device)
828 initializeDisplays();
829
Xiang Wang839fe5b2022-04-04 17:39:38 +0000830 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700831
Steven Thomas137d4bc2019-07-25 16:55:14 -0700832 char primeShaderCache[PROPERTY_VALUE_MAX];
833 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
834 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700835 if (setSchedFifo(false) != NO_ERROR) {
836 ALOGW("Can't set SCHED_OTHER for primeCache");
837 }
838
839 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
840
841 if (setSchedFifo(true) != NO_ERROR) {
842 ALOGW("Can't set SCHED_OTHER for primeCache");
843 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700844 }
Dan Stoza4e637772016-07-28 13:31:51 -0700845
Ady Abrahamed3290f2021-05-17 15:12:14 -0700846 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400847
Wei Wangf9b05ee2017-07-19 20:59:39 -0700848 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700849
850 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800851 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700852 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700853
854 if (mStartPropertySetThread->Start() != NO_ERROR) {
855 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800856 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800857
Dan Stoza9e56aa02015-11-02 13:00:03 -0800858 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700859}
860
Romain Guy11d63f42017-07-20 12:47:14 -0700861void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700862 Mutex::Autolock _l(mStateLock);
863
Romain Guy11d63f42017-07-20 12:47:14 -0700864 char value[PROPERTY_VALUE_MAX];
865
866 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800867 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700868 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800869 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100870
871 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700872 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800873
874 property_get("persist.sys.sf.color_mode", value, "0");
875 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700876}
877
Mathias Agopiana67e4182012-06-19 17:26:12 -0700878void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800879 // Start boot animation service by setting a property mailbox
880 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700881 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800882 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700883 if (mStartPropertySetThread->join() != NO_ERROR) {
884 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800885 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700886}
887
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800888// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800889
Brian Anderson6b376712017-04-04 10:51:39 -0700890status_t SurfaceFlinger::getSupportedFrameTimestamps(
891 std::vector<FrameEvent>* outSupported) const {
892 *outSupported = {
893 FrameEvent::REQUESTED_PRESENT,
894 FrameEvent::ACQUIRE,
895 FrameEvent::LATCH,
896 FrameEvent::FIRST_REFRESH_START,
897 FrameEvent::LAST_REFRESH_START,
898 FrameEvent::GPU_COMPOSITION_DONE,
899 FrameEvent::DEQUEUE_READY,
900 FrameEvent::RELEASE,
901 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800902
903 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
904
Ady Abrahamde549d42022-01-26 19:19:17 -0800905 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700906 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
907 }
908 return NO_ERROR;
909}
910
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800911status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
912 if (!displayToken || !state) {
913 return BAD_VALUE;
914 }
915
916 Mutex::Autolock lock(mStateLock);
917
918 const auto display = getDisplayDeviceLocked(displayToken);
919 if (!display) {
920 return NAME_NOT_FOUND;
921 }
922
923 state->layerStack = display->getLayerStack();
924 state->orientation = display->getOrientation();
925
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200926 const Rect layerStackRect = display->getLayerStackSpaceRect();
927 state->layerStackSpaceRect =
928 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800929
930 return NO_ERROR;
931}
932
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100933status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
934 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800935 if (!displayToken || !info) {
936 return BAD_VALUE;
937 }
938
939 Mutex::Autolock lock(mStateLock);
940
941 const auto display = getDisplayDeviceLocked(displayToken);
942 if (!display) {
943 return NAME_NOT_FOUND;
944 }
945
Dominik Laskowski55c85402020-01-21 16:25:47 -0800946 if (const auto connectionType = display->getConnectionType())
947 info->connectionType = *connectionType;
948 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800949 return INVALID_OPERATION;
950 }
951
952 if (mEmulatedDisplayDensity) {
953 info->density = mEmulatedDisplayDensity;
954 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100955 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800956 ? mInternalDisplayDensity
957 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800958 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700959 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800960
961 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200962 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000963 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800964
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800965 return NO_ERROR;
966}
967
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100968status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
969 ui::DynamicDisplayInfo* info) {
970 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700971 return BAD_VALUE;
972 }
973
Dominik Laskowski22488f62019-03-28 09:53:04 -0700974 Mutex::Autolock lock(mStateLock);
975
Marin Shalamanov5801c942020-12-17 17:00:13 +0100976 const auto display = getDisplayDeviceLocked(displayToken);
977 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700978 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700979 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700980
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700981 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
982 if (!displayId) {
983 return INVALID_OPERATION;
984 }
985
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800986 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700987
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100988 const auto& supportedModes = display->getSupportedModes();
989 info->supportedDisplayModes.clear();
990 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800991
992 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100993 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800994 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700995
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800996 auto [width, height] = mode->getResolution();
997 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700998
ramindani06e518e2022-03-14 18:47:53 +0000999 if (const auto physicalOrientation = display->getPhysicalOrientation();
1000 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001001 std::swap(width, height);
1002 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -07001003 }
1004
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001005 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -08001006
Huan Songf7eeb102022-03-28 11:02:38 -07001007 outMode.xDpi = xDpi;
1008 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001009
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001010 const nsecs_t period = mode->getVsyncPeriod();
1011 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001012
Ady Abraham8287e852020-08-12 14:44:58 -07001013 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001014 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001015 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1016 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1017 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001018
Andy McFadden91b2ca82014-06-13 14:04:23 -07001019 // This is how far in advance a buffer must be queued for
1020 // presentation at a given time. If you want a buffer to appear
1021 // on the screen at time N, you must submit the buffer before
1022 // (N - presentationDeadline).
1023 //
1024 // Normally it's one full refresh period (to give SF a chance to
1025 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001026 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001027 // composer or panel must be accounted for here.
1028 //
1029 // We add an additional 1ms to allow for processing time and
1030 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001031 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001032
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001033 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001034 }
1035
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001036 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001037 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001038 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001039
Marin Shalamanovb173f752021-02-16 19:38:36 +01001040 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001041 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001042 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001043 info->gameContentTypeSupported =
1044 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001045
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001046 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001047
1048 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001049 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1050 if (const auto modeId = display->translateModeId(*hwcId)) {
1051 info->preferredBootDisplayMode = modeId->value();
1052 }
1053 }
1054 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001055
Dan Stoza7f7da322014-05-02 15:26:25 -07001056 return NO_ERROR;
1057}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001059status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
1060 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001061 return BAD_VALUE;
1062 }
1063
Ady Abrahame90dd522020-12-29 12:08:45 -08001064 *stats = mScheduler->getDisplayStatInfo(systemTime());
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001065 return NO_ERROR;
1066}
1067
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001068void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001069 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001070
1071 if (!info.mode) {
1072 ALOGW("requested display mode is null");
1073 return;
1074 }
1075 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001076 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001077 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001078 return;
1079 }
1080
Ady Abraham690f4612021-07-01 23:24:03 -07001081 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001082 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001083
Alec Mouri754c98a2019-03-18 18:53:42 -07001084 // Start receiving vsync samples now, so that we can detect a period
1085 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001086 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001087 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001088 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001089 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001090
Ady Abraham690f4612021-07-01 23:24:03 -07001091 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001092 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001093 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001094}
1095
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001096status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001097 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001098
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001099 if (!displayToken) {
1100 return BAD_VALUE;
1101 }
Ady Abraham838de062019-02-04 10:24:03 -08001102
Dominik Laskowski756b7892021-08-04 12:53:59 -07001103 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001104 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001105 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001106 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001107 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001108 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001109 }
1110
1111 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001112 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001113 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001114 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001115
1116 const auto mode = display->getMode(DisplayModeId{modeId});
1117 if (!mode) {
1118 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1119 return BAD_VALUE;
1120 }
1121
1122 const auto fps = mode->getFps();
1123 // Keep the old switching type.
1124 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001125 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001126 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1127 allowGroupSwitching,
1128 {fps, fps}};
1129 constexpr bool kOverridePolicy = false;
1130
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001131 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001132 });
1133
1134 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001135}
1136
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001137void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001138 ATRACE_CALL();
1139
Dominik Laskowski22488f62019-03-28 09:53:04 -07001140 const auto display = getDefaultDisplayDeviceLocked();
1141 if (!display) {
1142 return;
1143 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001144
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001145 const auto upcomingModeInfo =
1146 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1147
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001148 if (!upcomingModeInfo.mode) {
1149 // There is no pending mode change. This can happen if the active
1150 // display changed and the mode change happened on a different display.
1151 return;
1152 }
1153
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001154 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001155 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1156 // We need to generate new sequenceId in order to recreate the display (and this
1157 // way the framebuffer).
1158 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001159 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001160 processDisplayChangesLocked();
1161
1162 // processDisplayChangesLocked will update all necessary components so we're done here.
1163 return;
1164 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001165
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001166 // We just created this display so we can call even if we are not on the main thread.
1167 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001168 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001169
Ady Abraham690f4612021-07-01 23:24:03 -07001170 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001171 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001172 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001173
Dominik Laskowski068173d2021-08-11 17:22:59 -07001174 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001175 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001176 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001177}
1178
Ady Abraham690f4612021-07-01 23:24:03 -07001179void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1180 display->clearDesiredActiveModeState();
1181 if (isDisplayActiveLocked(display)) {
1182 mScheduler->setModeChangePending(false);
1183 }
Ady Abraham53852a52019-05-28 18:07:44 -07001184}
1185
Ady Abraham690f4612021-07-01 23:24:03 -07001186void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1187 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1188 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001189 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001190 updatePhaseConfiguration(refreshRate);
1191}
1192
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001193void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001194 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001195
Marin Shalamanovdd594312021-11-09 16:37:37 +01001196 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1197
Ady Abraham690f4612021-07-01 23:24:03 -07001198 for (const auto& iter : mDisplays) {
1199 const auto& display = iter.second;
1200 if (!display || !display->isInternal()) {
1201 continue;
1202 }
1203
1204 // Store the local variable to release the lock.
1205 const auto desiredActiveMode = display->getDesiredActiveMode();
1206 if (!desiredActiveMode) {
1207 // No desired active mode pending to be applied
1208 continue;
1209 }
1210
1211 if (!isDisplayActiveLocked(display)) {
1212 // display is no longer the active display, so abort the mode change
1213 clearDesiredActiveModeState(display);
1214 continue;
1215 }
1216
1217 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1218 if (!desiredMode) {
1219 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1220 desiredActiveMode->mode->getId().value());
1221 clearDesiredActiveModeState(display);
1222 continue;
1223 }
1224
1225 const auto refreshRate = desiredMode->getFps();
1226 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1227 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1228 to_string(display->getId()).c_str());
1229
1230 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001231 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001232 desiredActiveModeChangeDone(display);
1233 continue;
1234 }
1235
1236 // Desired active mode was set, it is different than the mode currently in use, however
1237 // allowed modes might have changed by the time we process the refresh.
1238 // Make sure the desired mode is still allowed
1239 const auto displayModeAllowed =
1240 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1241 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001242 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001243 continue;
1244 }
1245
1246 // TODO(b/142753666) use constrains
1247 hal::VsyncPeriodChangeConstraints constraints;
1248 constraints.desiredTimeNanos = systemTime();
1249 constraints.seamlessRequired = false;
1250 hal::VsyncPeriodChangeTimeline outTimeline;
1251
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001252 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1253 display->initiateModeChange(*desiredActiveMode,
1254 constraints, &outTimeline));
1255
Ady Abraham690f4612021-07-01 23:24:03 -07001256 if (status != NO_ERROR) {
1257 // initiateModeChange may fail if a hotplug event is just about
1258 // to be sent. We just log the error in this case.
1259 ALOGW("initiateModeChange failed: %d", status);
1260 continue;
1261 }
1262 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1263
Marin Shalamanovdd594312021-11-09 16:37:37 +01001264 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001265 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001266 mSetActiveModePending = true;
1267 } else {
1268 // Updating the internal state should be done outside the loop,
1269 // because it can recreate a DisplayDevice and modify mDisplays
1270 // which will invalidate the iterator.
1271 displayToUpdateImmediately = display->getPhysicalId();
1272 }
1273 }
1274
1275 if (displayToUpdateImmediately) {
1276 updateInternalStateWithChangedMode();
1277
1278 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1279 const auto desiredActiveMode = display->getDesiredActiveMode();
1280 if (desiredActiveMode &&
1281 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1282 desiredActiveModeChangeDone(display);
1283 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001284 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001285}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001286
Alec Mouridea1ac52021-06-23 18:12:18 -07001287void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001288 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001289 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001290 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001291 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001292 for (const auto& [_, display] : mDisplays) {
1293 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001294 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001295 }
1296 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001297 });
1298
1299 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001300}
1301
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001302std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1303 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001304
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001305 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001306 // filter out all wide color modes. The typical reason why this happens is that the
1307 // hardware is not good enough to support GPU composition of wide color, and thus the
1308 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001309 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1310 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001311 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1312 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001313 }
Michael Wright28f24d02016-07-12 13:30:53 -07001314
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001315 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001316}
1317
Daniel Solomon42d04562019-01-20 21:03:19 -08001318status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
Dominik Laskowski3c363242022-04-07 10:44:12 -07001319 ui::DisplayPrimaries& primaries) {
Daniel Solomon42d04562019-01-20 21:03:19 -08001320 if (!displayToken) {
1321 return BAD_VALUE;
1322 }
1323
Dominik Laskowski3c363242022-04-07 10:44:12 -07001324 Mutex::Autolock lock(mStateLock);
1325
1326 const auto display = getDisplayDeviceLocked(displayToken);
1327 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001328 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001329 }
1330
Dominik Laskowski3c363242022-04-07 10:44:12 -07001331 const auto connectionType = display->getConnectionType();
1332 if (connectionType != ui::DisplayConnectionType::Internal) {
1333 return INVALID_OPERATION;
1334 }
1335
1336 // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1337 primaries = mInternalDisplayPrimaries;
Daniel Solomon42d04562019-01-20 21:03:19 -08001338 return NO_ERROR;
1339}
1340
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001341status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001342 if (!displayToken) {
1343 return BAD_VALUE;
1344 }
1345
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001346 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001347 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001348 if (!display) {
1349 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1350 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001351 return NAME_NOT_FOUND;
1352 }
1353
1354 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001355 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1356 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001357 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001358 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001359
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001360 const auto modes = getDisplayColorModes(*display);
1361 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1362
1363 if (mode < ColorMode::NATIVE || !exists) {
1364 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1365 decodeColorMode(mode).c_str(), mode, displayToken.get());
1366 return BAD_VALUE;
1367 }
1368
1369 display->getCompositionDisplay()->setColorProfile(
1370 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1371
1372 return NO_ERROR;
1373 });
1374
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001375 // TODO(b/195698395): Propagate error.
1376 future.wait();
1377 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001378}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001379
Kriti Dang7defaf32021-11-15 11:55:43 +01001380status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001381 auto future = mScheduler->schedule(
1382 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1383
1384 *outSupport = future.get();
1385 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001386}
1387
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001388status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1389 ui::DisplayModeId modeId) {
1390 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001391 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001392 const auto display = getDisplayDeviceLocked(displayToken);
1393 if (!display) {
1394 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1395 return NAME_NOT_FOUND;
1396 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001397
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001398 if (display->isVirtual()) {
1399 ALOGE("%s: Invalid operation on virtual display", whence);
1400 return INVALID_OPERATION;
1401 }
1402
1403 const auto displayId = display->getPhysicalId();
1404 const auto mode = display->getMode(DisplayModeId{modeId});
1405 if (!mode) {
1406 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1407 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001408 return BAD_VALUE;
1409 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001410
1411 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001412 });
1413 return future.get();
1414}
1415
1416status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001417 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001418 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001419 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1420 return getHwComposer().clearBootDisplayMode(*displayId);
1421 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001422 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001423 return BAD_VALUE;
1424 }
1425 });
1426 return future.get();
1427}
1428
Galia Peycheva5492cb52019-10-30 14:13:16 +01001429void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001430 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001431 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001432 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1433 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1434 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001435 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001436 }
1437 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001438}
1439
Galia Peycheva5492cb52019-10-30 14:13:16 +01001440void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001441 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001442 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001443 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001444 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001445 getHwComposer().setContentType(*displayId, type);
1446 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001447 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001448 }
1449 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001450}
1451
Svetoslavd85084b2014-03-20 10:28:31 -07001452status_t SurfaceFlinger::clearAnimationFrameStats() {
1453 Mutex::Autolock _l(mStateLock);
1454 mAnimFrameTracker.clearStats();
1455 return NO_ERROR;
1456}
1457
1458status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1459 Mutex::Autolock _l(mStateLock);
1460 mAnimFrameTracker.getStats(outStats);
1461 return NO_ERROR;
1462}
1463
Kriti Dang49ad4132021-01-08 11:49:56 +01001464status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1465 const std::vector<ui::Hdr>& hdrTypes) {
1466 Mutex::Autolock lock(mStateLock);
1467
1468 auto display = getDisplayDeviceLocked(displayToken);
1469 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001470 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001471 return NAME_NOT_FOUND;
1472 }
1473
1474 display->overrideHdrTypes(hdrTypes);
1475 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1476 return NO_ERROR;
1477}
1478
Tej Singhe2751772021-04-06 22:05:29 -07001479status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1480 *success = mTimeStats->onPullAtom(atomId, pulledData);
1481 return NO_ERROR;
1482}
1483
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001484status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1485 ui::PixelFormat* outFormat,
1486 ui::Dataspace* outDataspace,
1487 uint8_t* outComponentMask) const {
1488 if (!outFormat || !outDataspace || !outComponentMask) {
1489 return BAD_VALUE;
1490 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001491
1492 Mutex::Autolock lock(mStateLock);
1493
1494 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1495 if (!displayId) {
1496 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001497 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001498
1499 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001500 outDataspace, outComponentMask);
1501}
1502
Kevin DuBois74e53772018-11-19 10:52:38 -08001503status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1504 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001505 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001506 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001507 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001508 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1509 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1510 componentMask, maxFrames);
1511 } else {
1512 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1513 return NAME_NOT_FOUND;
1514 }
1515 });
1516
1517 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001518}
1519
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001520status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1521 uint64_t maxFrames, uint64_t timestamp,
1522 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001523 Mutex::Autolock lock(mStateLock);
1524
1525 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1526 if (!displayId) {
1527 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001528 }
1529
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001530 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001531}
1532
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001533status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1534 if (!outSupported) {
1535 return BAD_VALUE;
1536 }
1537 *outSupported = getRenderEngine().supportsProtectedContent();
1538 return NO_ERROR;
1539}
1540
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001541status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1542 bool* outIsWideColorDisplay) const {
1543 if (!displayToken || !outIsWideColorDisplay) {
1544 return BAD_VALUE;
1545 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001546
1547 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001548 const auto display = getDisplayDeviceLocked(displayToken);
1549 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001550 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001551 }
Peiyong Linff84a152019-05-17 18:36:19 -07001552
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001553 *outIsWideColorDisplay =
1554 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001555 return NO_ERROR;
1556}
1557
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001558status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001559 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001560 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001561
Dominik Laskowski6505f792019-09-18 11:10:05 -07001562 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001563 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001564 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001565 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001566
Dominik Laskowski756b7892021-08-04 12:53:59 -07001567 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001568 return NO_ERROR;
1569}
1570
1571status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001572 Mutex::Autolock lock(mStateLock);
Ady Abrahame90dd522020-12-29 12:08:45 -08001573 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(when);
Ady Abraham56b42a42020-12-28 16:48:48 -08001574 const auto expectedPresent = calculateExpectedPresentTime(stats);
Ady Abraham9c53ee72020-07-22 21:16:18 -07001575 return mScheduler->injectVSync(when, /*expectedVSyncTime=*/expectedPresent,
1576 /*deadlineTimestamp=*/expectedPresent)
1577 ? NO_ERROR
1578 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001579}
1580
Huihong Luo05539a12022-02-23 10:29:40 -08001581status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001582 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001583 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001584 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001585 mDrawingState.traverseInZOrder([&](Layer* layer) {
1586 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1587 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001588 });
1589
1590 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001591 return NO_ERROR;
1592}
1593
Peiyong Linc6780972018-10-28 15:24:08 -07001594status_t SurfaceFlinger::getCompositionPreference(
1595 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1596 Dataspace* outWideColorGamutDataspace,
1597 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001598 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001599 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001600 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001601 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001602 return NO_ERROR;
1603}
1604
Dan Stozaec460082018-12-17 15:35:09 -08001605status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1606 const sp<IBinder>& stopLayerHandle,
1607 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001608 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001609 return BAD_VALUE;
1610 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001611
1612 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1613 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001614 return NO_ERROR;
1615}
1616
Dan Stozaec460082018-12-17 15:35:09 -08001617status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001618 if (!listener) {
1619 return BAD_VALUE;
1620 }
Dan Stozaec460082018-12-17 15:35:09 -08001621 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001622 return NO_ERROR;
1623}
Dan Gittik57e63c52019-01-18 16:37:54 +00001624
Alec Mouria9a68a62021-03-04 19:14:50 -08001625status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001626 if (!listener) {
1627 return BAD_VALUE;
1628 }
1629
Alec Mouria9a68a62021-03-04 19:14:50 -08001630 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001631 return NO_ERROR;
1632}
1633
1634status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1635 if (!listener) {
1636 return BAD_VALUE;
1637 }
1638 mFpsReporter->removeListener(listener);
1639 return NO_ERROR;
1640}
1641
Galia Peycheva8f04b302021-04-27 13:25:38 +02001642status_t SurfaceFlinger::addTunnelModeEnabledListener(
1643 const sp<gui::ITunnelModeEnabledListener>& listener) {
1644 if (!listener) {
1645 return BAD_VALUE;
1646 }
1647
1648 mTunnelModeEnabledReporter->addListener(listener);
1649 return NO_ERROR;
1650}
1651
1652status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1653 const sp<gui::ITunnelModeEnabledListener>& listener) {
1654 if (!listener) {
1655 return BAD_VALUE;
1656 }
1657
1658 mTunnelModeEnabledReporter->removeListener(listener);
1659 return NO_ERROR;
1660}
1661
Dan Gittik57e63c52019-01-18 16:37:54 +00001662status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1663 bool* outSupport) const {
1664 if (!displayToken || !outSupport) {
1665 return BAD_VALUE;
1666 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001667
1668 Mutex::Autolock lock(mStateLock);
1669
Dan Gittik57e63c52019-01-18 16:37:54 +00001670 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1671 if (!displayId) {
1672 return NAME_NOT_FOUND;
1673 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001674 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001675 return NO_ERROR;
1676}
1677
Alec Mouricdf16792021-12-10 13:16:06 -08001678bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1679 bool hasHdrLayers = false;
1680 mDrawingState.traverse([&,
1681 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1682 hasHdrLayers |= (layer->isVisible() &&
1683 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1684 isHdrDataspace(layer->getDataSpace()));
1685 });
1686 return hasHdrLayers;
1687}
1688
John Reck22be6962021-03-10 12:59:54 -05001689status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1690 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001691 if (!displayToken) {
1692 return BAD_VALUE;
1693 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001694
Dominik Laskowski756b7892021-08-04 12:53:59 -07001695 const char* const whence = __func__;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001696 return ftl::Future(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001697 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001698 const bool supportsDisplayBrightnessCommand =
1699 getHwComposer().getComposer()->isSupported(
1700 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1701 // If we support applying display brightness as a command, then we also support
1702 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001703 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001704 auto compositionDisplay = display->getCompositionDisplay();
1705 float currentDimmingRatio =
1706 compositionDisplay->editState().sdrWhitePointNits /
1707 compositionDisplay->editState().displayBrightnessNits;
1708 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1709 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001710 FTL_FAKE_GUARD(kMainThreadContext,
1711 display->stageBrightness(brightness.displayBrightness));
1712
Alec Mouri6da0e272022-02-07 12:45:57 -08001713 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1714 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001715 scheduleComposite(FrameHint::kNone);
1716 } else {
1717 scheduleCommit(FrameHint::kNone);
1718 }
1719 return ftl::yield<status_t>(OK);
1720 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001721 return getHwComposer()
1722 .setDisplayBrightness(display->getPhysicalId(),
1723 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001724 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001725 Hwc2::Composer::DisplayBrightnessOptions{
1726 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001727 }
Alec Mouricdf16792021-12-10 13:16:06 -08001728
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001729 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001730 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001731 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001732 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001733 }))
Dominik Laskowskib17c6212022-05-09 09:36:19 -07001734 .then([](ftl::Future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001735 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001736}
1737
John Reck88270902021-03-18 11:27:35 -04001738status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1739 const sp<gui::IHdrLayerInfoListener>& listener) {
1740 if (!displayToken) {
1741 return BAD_VALUE;
1742 }
1743
1744 Mutex::Autolock lock(mStateLock);
1745
1746 const auto display = getDisplayDeviceLocked(displayToken);
1747 if (!display) {
1748 return NAME_NOT_FOUND;
1749 }
1750 const auto displayId = display->getId();
1751 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1752 if (!hdrInfoReporter) {
1753 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1754 }
1755 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001756
1757
1758 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001759 return OK;
1760}
1761
1762status_t SurfaceFlinger::removeHdrLayerInfoListener(
1763 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1764 if (!displayToken) {
1765 return BAD_VALUE;
1766 }
1767
1768 Mutex::Autolock lock(mStateLock);
1769
1770 const auto display = getDisplayDeviceLocked(displayToken);
1771 if (!display) {
1772 return NAME_NOT_FOUND;
1773 }
1774 const auto displayId = display->getId();
1775 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1776 if (hdrInfoReporter) {
1777 hdrInfoReporter->removeListener(listener);
1778 }
1779 return OK;
1780}
1781
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001782status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001783 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001784 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001785
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001786 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001787 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001788 }
1789
1790 return NO_ERROR;
1791}
1792
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001793status_t SurfaceFlinger::getDisplayDecorationSupport(
1794 const sp<IBinder>& displayToken,
1795 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001796 if (!displayToken || !outSupport) {
1797 return BAD_VALUE;
1798 }
1799
1800 Mutex::Autolock lock(mStateLock);
1801
1802 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1803 if (!displayId) {
1804 return NAME_NOT_FOUND;
1805 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001806 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001807 return NO_ERROR;
1808}
1809
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001810// ----------------------------------------------------------------------------
1811
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001812sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001813 gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001814 const auto& handle =
Huihong Luo1b0c49f2022-03-15 19:18:21 -07001815 vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
1816 ? mSfConnectionHandle
1817 : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001818
Ady Abraham62f216c2020-10-13 19:07:23 -07001819 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001820}
1821
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001822void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001823 if (hint == FrameHint::kActive) {
1824 mScheduler->resetIdleTimer();
1825 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001826 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001827 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001828}
1829
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001830void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1831 mMustComposite = true;
1832 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001833}
1834
1835void SurfaceFlinger::scheduleRepaint() {
1836 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001837 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001838}
1839
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001840void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001841 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001842}
1843
Ady Abraham2492a022020-07-24 11:09:55 -07001844nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001845 if (const auto display = getDefaultDisplayDeviceLocked()) {
1846 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001847 }
1848
Marin Shalamanov045b7002021-01-07 16:56:24 +01001849 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001850}
1851
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001852void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1853 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001854 const std::string tracePeriod = [vsyncPeriod]() {
1855 if (ATRACE_ENABLED() && vsyncPeriod) {
1856 std::stringstream ss;
1857 ss << "(" << *vsyncPeriod << ")";
1858 return ss.str();
1859 }
1860 return std::string();
1861 }();
1862 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001863
Steven Thomas3cfac282017-02-06 12:29:30 -08001864 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001865 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1866 if (displayId) {
1867 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1868 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001869 display->onVsync(timestamp);
1870 }
1871
Dominik Laskowski075d3172018-05-24 15:50:06 -07001872 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001873 return;
1874 }
1875
Ady Abrahame1166472021-07-15 10:56:06 -07001876 const bool isActiveDisplay =
1877 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1878 if (!isActiveDisplay) {
1879 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001880 return;
1881 }
1882
Alec Mourif8e689c2019-05-20 18:32:22 -07001883 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001884 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001885 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001886 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001887 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001888}
1889
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001890void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001891 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1892 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001893}
1894
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001895void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1896 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001897 const bool connected = connection == hal::Connection::CONNECTED;
1898 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001899
Steven Thomasb02664d2017-07-26 18:48:28 -07001900 // Only lock if we're not on the main thread. This function is normally
1901 // called on a hwbinder thread, but for the primary display it's called on
1902 // the main thread with the state lock already held, so don't attempt to
1903 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001904 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001905
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001906 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001907
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001908 if (std::this_thread::get_id() == mMainThreadId) {
1909 // Process all pending hot plug events immediately if we are on the main thread.
1910 processDisplayHotplugEventsLocked();
1911 }
1912
Lloyd Piqueba04e622017-12-14 17:11:26 -08001913 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001914}
1915
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001916void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1917 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001918 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001919 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001920
1921 if (timeline.refreshRequired) {
1922 scheduleComposite(FrameHint::kNone);
1923 }
Ady Abraham7159f572019-10-11 11:10:18 -07001924}
1925
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001926void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001927 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001928 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1929}
1930
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001931void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001932 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001933 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001934}
1935
Yichi Chen3401b562022-01-17 15:42:35 +08001936void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001937 ATRACE_CALL();
1938 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001939}
1940
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001941void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001942 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001943
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001944 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001945 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001946 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001947
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001948 if (const auto display = getDefaultDisplayDeviceLocked();
1949 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001950 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001951 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001952 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001953}
1954
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001955SurfaceFlinger::FenceWithFenceTime SurfaceFlinger::previousFrameFence() {
Ady Abrahamccf4b472021-05-11 19:53:01 -07001956 const auto now = systemTime();
1957 const auto vsyncPeriod = mScheduler->getDisplayStatInfo(now).vsyncPeriod;
1958 const bool expectedPresentTimeIsTheNextVsync = mExpectedPresentTime - now <= vsyncPeriod;
1959 return expectedPresentTimeIsTheNextVsync ? mPreviousPresentFences[0]
1960 : mPreviousPresentFences[1];
Alec Mouri6d414b52020-03-17 11:18:05 -07001961}
1962
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001963bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001964 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001965 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001966
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001967 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001968 return false;
1969 }
1970
Dan Stoza59083052020-04-28 10:13:20 -07001971 const status_t status = fence->wait(graceTimeMs);
1972 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1973 // which calls wait(0) again internally
1974 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001975}
1976
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001977nsecs_t SurfaceFlinger::previousFramePresentTime() {
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001978 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001979
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001980 if (fence == FenceTime::NO_FENCE) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001981 return Fence::SIGNAL_TIME_INVALID;
1982 }
1983
1984 return fence->getSignalTime();
1985}
1986
Ady Abraham56b42a42020-12-28 16:48:48 -08001987nsecs_t SurfaceFlinger::calculateExpectedPresentTime(DisplayStatInfo stats) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001988 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham8cb21882020-08-26 18:22:05 -07001989 return mVsyncModulator->getVsyncConfig().sfOffset > 0 ? stats.vsyncTime
1990 : stats.vsyncTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001991}
1992
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001993bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1994 FTL_FAKE_GUARD(kMainThreadContext) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001995 // calculate the expected present time once and use the cached
1996 // value throughout this frame to make sure all layers are
1997 // seeing this same value.
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001998 if (expectedVsyncTime >= frameTime) {
1999 mExpectedPresentTime = expectedVsyncTime;
Snild Dolkow819636c2021-01-22 14:42:08 +01002000 } else {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002001 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(frameTime);
Snild Dolkow819636c2021-01-22 14:42:08 +01002002 mExpectedPresentTime = calculateExpectedPresentTime(stats);
2003 }
2004
2005 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002006 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07002007
Ady Abraham893c99d2021-04-30 16:00:23 -07002008 const auto vsyncIn = [&] {
2009 if (!ATRACE_ENABLED()) return 0.f;
2010 return (mExpectedPresentTime - systemTime()) / 1e6f;
2011 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002012 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
2013 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002014
Dan Stoza28d46a52020-04-28 09:54:54 -07002015 // When Backpressure propagation is enabled we want to give a small grace period
2016 // for the present fence to fire instead of just giving up on this frame to handle cases
2017 // where present fence is just about to get signaled.
2018 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002019 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002020
2021 // Pending frames may trigger backpressure propagation.
2022 const TracedOrdinal<bool> framePending = {"PrevFramePending",
2023 previousFramePending(graceTimeForPresentFenceMs)};
2024
2025 // Frame missed counts for metrics tracking.
2026 // A frame is missed if the prior frame is still pending. If no longer pending,
2027 // then we still count the frame as missed if the predicted present time
2028 // was further in the past than when the fence actually fired.
2029
2030 // Add some slop to correct for drift. This should generally be
2031 // smaller than a typical frame duration, but should not be so small
2032 // that it reports reasonable drift as a missed frame.
Ady Abrahame90dd522020-12-29 12:08:45 -08002033 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(systemTime());
Dan Stoza28d46a52020-04-28 09:54:54 -07002034 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
2035 const nsecs_t previousPresentTime = previousFramePresentTime();
2036 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2037 framePending ||
2038 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002039 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002040 previousPresentTime - frameMissedSlop))};
2041 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2042 mHadDeviceComposition && frameMissed};
2043 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2044 mHadClientComposition && frameMissed};
2045
2046 if (frameMissed) {
2047 mFrameMissedCount++;
2048 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002049 }
2050
2051 if (hwcFrameMissed) {
2052 mHwcFrameMissedCount++;
2053 }
2054
2055 if (gpuFrameMissed) {
2056 mGpuFrameMissedCount++;
2057 }
2058
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002059 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002060 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002061 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002062 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002063 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002064 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002065 }
2066
2067 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002068 // the mode, hence we update SF.
2069 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002070 {
2071 Mutex::Autolock lock(mStateLock);
2072 updateInternalStateWithChangedMode();
2073 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002074 }
2075
John Reck2ec53912020-07-07 16:53:55 -07002076 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002077 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002078 scheduleCommit(FrameHint::kNone);
2079 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002080 }
2081 }
2082
Matt Buckley50c44062022-01-17 20:48:10 +00002083 // Save this once per commit + composite to ensure consistency
2084 mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession();
2085 if (mPowerHintSessionEnabled) {
2086 nsecs_t vsyncPeriod;
2087 {
2088 Mutex::Autolock lock(mStateLock);
2089 vsyncPeriod = getVsyncPeriodFromHWC();
2090 }
2091 mPowerAdvisor->setCommitStart(frameTime);
2092 mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime);
2093 const nsecs_t idealSfWorkDuration =
2094 mVsyncModulator->getVsyncConfig().sfWorkDuration.count();
2095 // Frame delay is how long we should have minus how long we actually have
2096 mPowerAdvisor->setFrameDelay(idealSfWorkDuration - (mExpectedPresentTime - frameTime));
2097 mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration);
2098 mPowerAdvisor->setTargetWorkDuration(vsyncPeriod);
2099
2100 // Send early hint here to make sure there's not another frame pending
2101 if (mPowerHintSessionMode.early) {
2102 // Send a rough prediction for this frame based on last frame's timing info
2103 mPowerAdvisor->sendPredictedWorkDuration();
2104 }
2105 }
2106
Dan Stoza28d46a52020-04-28 09:54:54 -07002107 if (mTracingEnabledChanged) {
Vishnu Nair7891e962021-11-11 12:07:21 -08002108 mLayerTracingEnabled = mLayerTracing.isEnabled();
Dan Stoza28d46a52020-04-28 09:54:54 -07002109 mTracingEnabledChanged = false;
2110 }
2111
Ady Abraham29d0da32020-07-16 18:39:33 -07002112 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002113 Mutex::Autolock lock(mStateLock);
2114 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002115 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002116 }
2117 }
2118
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002119 // Composite if transactions were committed, or if requested by HWC.
2120 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002121 {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002122 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(stats.vsyncPeriod));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002123
chaviw6b9ffea2021-11-08 09:25:48 -06002124 bool needsTraversal = false;
2125 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002126 needsTraversal |= commitCreatedLayers();
2127 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002128 }
2129
2130 const bool shouldCommit =
2131 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2132 if (shouldCommit) {
2133 commitTransactions();
2134 }
2135
2136 if (transactionFlushNeeded()) {
2137 setTransactionFlags(eTransactionFlushNeeded);
2138 }
2139
2140 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002141 mustComposite |= latchBuffers();
2142
chaviw6b9ffea2021-11-08 09:25:48 -06002143 // This has to be called after latchBuffers because we want to include the layers that have
2144 // been latched in the commit callback
2145 if (!needsTraversal) {
2146 // Invoke empty transaction callbacks early.
2147 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2148 } else {
2149 // Invoke OnCommit callbacks.
2150 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2151 }
2152
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002153 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002154 }
2155
2156 // Layers need to get updated (in the previous line) before we can use them for
2157 // choosing the refresh rate.
2158 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2159 // and may eventually call to ~Layer() if it holds the last reference
2160 {
2161 Mutex::Autolock _l(mStateLock);
2162 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002163 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002164 }
2165
Dan Stoza28d46a52020-04-28 09:54:54 -07002166 updateCursorAsync();
2167 updateInputFlinger();
2168
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002169 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2170 // This will block and tracing should only be enabled for debugging.
2171 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
2172 }
2173
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002174 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002175
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002176 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002177}
2178
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002179void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2180 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002181 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002182
Lloyd Piqueab039b52019-02-13 14:22:42 -08002183 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002184 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002185 refreshArgs.outputs.reserve(displays.size());
Matt Buckley50c44062022-01-17 20:48:10 +00002186 std::vector<DisplayId> displayIds;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002187 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002188 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Matt Buckley50c44062022-01-17 20:48:10 +00002189 displayIds.push_back(display->getId());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002190 }
Matt Buckley50c44062022-01-17 20:48:10 +00002191 mPowerAdvisor->setDisplays(displayIds);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002192 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002193 if (auto layerFE = layer->getCompositionEngineLayerFE())
2194 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002195 });
Tianhao Yao67dd7122022-02-22 17:48:33 +00002196
2197 if (DOES_CONTAIN_BORDER) {
2198 refreshArgs.borderInfoList.clear();
2199 mDrawingState.traverse([&refreshArgs](Layer* layer) {
2200 if (layer->isBorderEnabled()) {
2201 compositionengine::BorderRenderInfo info;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00002202 info.width = layer->getBorderWidth();
2203 info.color = layer->getBorderColor();
Tianhao Yao67dd7122022-02-22 17:48:33 +00002204 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2205 info.layerIds.push_back(ilayer->getSequence());
2206 });
2207 refreshArgs.borderInfoList.emplace_back(std::move(info));
2208 }
2209 });
2210 }
2211
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002212 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002213 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002214 if (auto layerFE = layer->getCompositionEngineLayerFE())
2215 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002216 }
2217
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002218 refreshArgs.outputColorSetting = useColorManagement
2219 ? mDisplayColorSetting
2220 : compositionengine::OutputColorSetting::kUnmanaged;
2221 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2222 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002223
2224 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002225 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002226 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002227 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002228
2229 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2230 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2231 mDrawingState.colorMatrixChanged = false;
2232 }
2233
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002234 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002235
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002236 if (mDebugFlashDelay != 0) {
2237 refreshArgs.devOptForceClientComposition = true;
2238 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002239 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002240
Ady Abraham43065bd2021-12-10 17:22:15 -08002241 const auto expectedPresentTime = mExpectedPresentTime.load();
2242 const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
Ady Abrahamcaba2982021-06-16 16:45:04 -07002243 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2244 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002245 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002246 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002247 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002248
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002249 // Store the present time just before calling to the composition engine so we could notify
2250 // the scheduler.
2251 const auto presentTime = systemTime();
2252
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002253 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002254
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002255 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002256
Matt Buckley50c44062022-01-17 20:48:10 +00002257 // Send a power hint hint after presentation is finished
2258 if (mPowerHintSessionEnabled) {
2259 if (mPowerHintSessionMode.late) {
2260 mPowerAdvisor->sendActualWorkDuration();
2261 }
2262 }
2263
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002264 if (mScheduler->onPostComposition(presentTime)) {
2265 scheduleComposite(FrameHint::kNone);
2266 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002267
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002268 postFrame();
2269 postComposition();
2270
Midas Chien50f52e22020-09-26 17:57:42 +08002271 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002272
Vishnu Nair9cf89262022-02-26 09:17:49 -08002273 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2274 TimeStats::ClientCompositionRecord clientCompositionRecord;
2275 for (const auto& [_, display] : displays) {
2276 const auto& state = display->getCompositionDisplay()->getState();
2277 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2278 mHadDeviceComposition |= state.usesDeviceComposition;
2279 mReusedClientComposition |= state.reusedClientComposition;
2280 clientCompositionRecord.predicted |=
2281 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2282 clientCompositionRecord.predictionSucceeded |=
2283 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002284 }
2285
Vishnu Nair9cf89262022-02-26 09:17:49 -08002286 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2287 clientCompositionRecord.reused = mReusedClientComposition;
2288 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2289 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2290
Yichi Chen28dee2c2020-07-06 21:24:14 +08002291 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002292 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2293 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002294
David Sodman7e4ae112018-02-09 15:02:28 -08002295 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002296 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002297 // This will block and should only be used for debugging.
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002298 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
Vishnu Nairdf529052019-06-07 14:53:14 -07002299 }
Robert Carr167bdde2021-07-28 11:26:51 -07002300
2301 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002302 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002303
2304 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002305 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002306 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002307
Matt Buckley50c44062022-01-17 20:48:10 +00002308 if (mPowerHintSessionEnabled) {
2309 mPowerAdvisor->setCompositeEnd(systemTime());
Matt Buckleyef51fba2021-10-12 19:30:12 +00002310 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002311}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002312
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002313void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002314 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002315
Vishnu Nair4351ad52019-02-11 14:13:02 -08002316 if (mVisibleRegionsDirty) {
2317 computeLayerBounds();
2318 }
2319
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002320 for (auto& layer : mLayersPendingRefresh) {
2321 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002322 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002323 invalidateLayerStack(layer, visibleReg);
2324 }
2325 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002326}
2327
Ana Krulece588e312018-09-18 12:32:24 -07002328void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2329 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002330 // Update queue of past composite+present times and determine the
2331 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002332 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002333 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002334 while (!getBE().mCompositePresentTimes.empty()) {
2335 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002336 // Cached values should have been updated before calling this method,
2337 // which helps avoid duplicate syscalls.
2338 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2339 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2340 break;
2341 }
2342 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002343 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002344 }
2345
2346 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002347 while (getBE().mCompositePresentTimes.size() > 16) {
2348 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002349 }
2350
Ana Krulece588e312018-09-18 12:32:24 -07002351 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002352}
2353
Ana Krulece588e312018-09-18 12:32:24 -07002354void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2355 nsecs_t compositeToPresentLatency) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002356 // Avoid division by 0 by defaulting to 60Hz
2357 const auto vsyncPeriod = stats.vsyncPeriod ?: (60_Hz).getPeriodNsecs();
2358
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002359 // Integer division and modulo round toward 0 not -inf, so we need to
2360 // treat negative and positive offsets differently.
Ady Abraham8287e852020-08-12 14:44:58 -07002361 nsecs_t idealLatency = (mVsyncConfiguration->getCurrentConfigs().late.sfOffset > 0)
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002362 ? (vsyncPeriod -
2363 (mVsyncConfiguration->getCurrentConfigs().late.sfOffset % vsyncPeriod))
2364 : ((-mVsyncConfiguration->getCurrentConfigs().late.sfOffset) % vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002365
Ady Abraham8287e852020-08-12 14:44:58 -07002366 // Just in case mVsyncConfiguration->getCurrentConfigs().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002367 if (idealLatency <= 0) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002368 idealLatency = vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002369 }
2370
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002371 // Snap the latency to a value that removes scheduling jitter from the
2372 // composition and present times, which often have >1ms of jitter.
2373 // Reducing jitter is important if an app attempts to extrapolate
2374 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002375 // Snapping also allows an app to precisely calculate
Ady Abraham8287e852020-08-12 14:44:58 -07002376 // mVsyncConfiguration->getCurrentConfigs().late.sf with (presentLatency % interval).
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002377 const nsecs_t bias = vsyncPeriod / 2;
2378 const int64_t extraVsyncs = ((compositeToPresentLatency - idealLatency + bias) / vsyncPeriod);
Ady Abraham8d7e7842022-02-03 01:42:45 +00002379 const nsecs_t snappedCompositeToPresentLatency =
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002380 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002381
David Sodman99974d22017-11-28 12:04:33 -08002382 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002383 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002384 getBE().mCompositorTiming.interval = vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002385 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002386}
2387
John Reck49d9ad32022-02-23 19:03:31 -05002388bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
Alec Mouri2c0ea352022-04-12 16:30:24 +00002389 // Treat all layers as non-HDR if:
2390 // 1. They do not have a valid HDR dataspace. Currently we treat those as PQ or HLG. and
2391 // 2. The layer is allowed to be dimmed. WindowManager may disable dimming in order to
2392 // keep animations invoking SDR screenshots of HDR layers seamless. Treat such tagged
2393 // layers as HDR so that DisplayManagerService does not try to change the screen brightness
2394 if (!isHdrDataspace(layer->getDataSpace()) && layer->isDimmingEnabled()) {
John Reck49d9ad32022-02-23 19:03:31 -05002395 return false;
2396 }
2397 if (mIgnoreHdrCameraLayers) {
2398 auto buffer = layer->getBuffer();
2399 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2400 return false;
2401 }
2402 }
2403 return true;
2404}
2405
ramindani06e518e2022-03-14 18:47:53 +00002406ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2407 bool isPrimary) const {
2408 const auto id = PhysicalDisplayId::tryCast(displayId);
2409 if (!id) {
2410 return ui::ROTATION_0;
2411 }
2412 if (getHwComposer().getComposer()->isSupported(
2413 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2414 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2415 case Hwc2::AidlTransform::ROT_90:
2416 return ui::ROTATION_90;
2417 case Hwc2::AidlTransform::ROT_180:
2418 return ui::ROTATION_180;
2419 case Hwc2::AidlTransform::ROT_270:
2420 return ui::ROTATION_270;
2421 default:
2422 return ui::ROTATION_0;
2423 }
2424 }
2425
2426 if (isPrimary) {
2427 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2428 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2429 case Values::ORIENTATION_90:
2430 return ui::ROTATION_90;
2431 case Values::ORIENTATION_180:
2432 return ui::ROTATION_180;
2433 case Values::ORIENTATION_270:
2434 return ui::ROTATION_270;
2435 default:
2436 break;
2437 }
2438 }
2439 return ui::ROTATION_0;
2440}
2441
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002442void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 ATRACE_CALL();
2444 ALOGV("postComposition");
2445
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002446 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002447
2448 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002449 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002450 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002451 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002452 ->getRenderSurface()
2453 ->getClientTargetAcquireFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002454 } else {
2455 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2456 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002457
Ady Abrahambe0f9482019-04-24 15:41:53 -07002458 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002459 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002460 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002461 mPreviousPresentFences[0].fenceTime =
2462 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2463
Vishnu Nair9a69a042021-06-18 13:19:49 -07002464 nsecs_t now = systemTime();
2465
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002466 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2467 // information from previous' frame classification is already available when sending jank info
2468 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002469 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002470 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002471
Vishnu Nair9a69a042021-06-18 13:19:49 -07002472 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002473
Lloyd Piqueab039b52019-02-13 14:22:42 -08002474 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2475 // be sampled a little later than when we started doing work for this frame,
2476 // but that should be okay since updateCompositorTiming has snapping logic.
2477 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002478 mPreviousPresentFences[0].fenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002479 CompositorTiming compositorTiming;
2480 {
David Sodman99974d22017-11-28 12:04:33 -08002481 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2482 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002483 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002484
Robert Carrc747ad02021-06-11 14:01:24 -07002485 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002486 layer->onPostComposition(display, glCompositionDoneFenceTime,
2487 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002488 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002489 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002490
John Reck88270902021-03-18 11:27:35 -04002491 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2492 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002493 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002494 {
2495 Mutex::Autolock lock(mStateLock);
2496 if (mFpsReporter) {
2497 mFpsReporter->dispatchLayerFps();
2498 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002499
2500 if (mTunnelModeEnabledReporter) {
2501 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2502 }
John Reck88270902021-03-18 11:27:35 -04002503 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002504 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2505 if (reporter && reporter->hasListeners()) {
2506 if (const auto display = getDisplayDeviceLocked(displayId)) {
2507 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002508 }
2509 }
2510 }
Robert Carr167bdde2021-07-28 11:26:51 -07002511 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2512 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002513 }
2514
Robert Carr167bdde2021-07-28 11:26:51 -07002515 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2516 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2517 HdrLayerInfoReporter::HdrLayerInfo info;
2518 int32_t maxArea = 0;
2519 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2520 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002521 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002522 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002523 const auto* outputLayer =
2524 compositionDisplay->getOutputLayerForLayer(layerFe);
2525 if (outputLayer) {
2526 info.numberOfHdrLayers++;
2527 const auto displayFrame = outputLayer->getState().displayFrame;
2528 const int32_t area = displayFrame.width() * displayFrame.height();
2529 if (area > maxArea) {
2530 maxArea = area;
2531 info.maxW = displayFrame.width();
2532 info.maxH = displayFrame.height();
2533 }
John Reckdb1a16b2021-07-09 13:05:52 -04002534 }
John Reck88270902021-03-18 11:27:35 -04002535 }
2536 }
Robert Carr167bdde2021-07-28 11:26:51 -07002537 });
2538 listener->dispatchHdrLayerInfo(info);
2539 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002540 }
2541
Robert Carr167bdde2021-07-28 11:26:51 -07002542 mSomeDataspaceChanged = false;
2543 mVisibleRegionsWereDirtyThisFrame = false;
2544
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002545 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002546 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002547 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002548
Ady Abrahamed3290f2021-05-17 15:12:14 -07002549 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002550 mPreviousPresentFences[0].fenceTime->isValid()) {
2551 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002552 }
2553
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002554 const bool isDisplayConnected =
2555 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002556
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002557 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002558 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002559 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002560 }
2561 }
2562
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002563 if (mAnimCompositionPending) {
2564 mAnimCompositionPending = false;
2565
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002566 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2567 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002568 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002569 // The HWC doesn't support present fences, so use the refresh
2570 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002571 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002572 mAnimFrameTracker.setActualPresentTime(presentTime);
2573 }
2574 mAnimFrameTracker.advanceFrame();
2575 }
Dan Stozab90cf072015-03-05 11:05:59 -08002576
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002577 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002578
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002579 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002580
Alec Mouri717bcb62020-02-10 17:07:19 -08002581 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2582 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2583 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2584
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002585 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002586 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002587 return;
2588 }
2589
2590 nsecs_t currentTime = systemTime();
2591 if (mHasPoweredOff) {
2592 mHasPoweredOff = false;
2593 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002594 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002595 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002596 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2597 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002598 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002599 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002600 }
David Sodman4a36e932017-11-07 14:29:47 -08002601 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002602 }
David Sodman4a36e932017-11-07 14:29:47 -08002603 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002604
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002605 // Cleanup any outstanding resources due to rendering a prior frame.
2606 getRenderEngine().cleanupPostRender();
2607
Dan Stoza436ccf32018-06-21 12:10:12 -07002608 {
2609 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002610 if (mTexturePool.size() < mTexturePoolSize) {
2611 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002612 const size_t offset = mTexturePool.size();
2613 mTexturePool.resize(mTexturePoolSize);
2614 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2615 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002616 } else if (mTexturePool.size() > mTexturePoolSize) {
2617 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2618 const size_t offset = mTexturePoolSize;
2619 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2620 mTexturePool.resize(mTexturePoolSize);
2621 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002622 }
2623 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002624
Dan Stoza45de5ba2019-04-25 14:12:09 -07002625 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2626 // side-effect of getTotalSize(), so we check that again here
2627 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002628 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002629 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2630 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002631}
2632
chaviw79468ab2021-10-27 11:11:24 -05002633FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002634 const ui::Size maxSize = [this] {
2635 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002636
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002637 // The LayerTraceGenerator tool runs without displays.
2638 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002639
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002640 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2641 [](ui::Size size, const auto& pair) -> ui::Size {
2642 const auto& display = pair.second;
2643 return {std::max(size.getWidth(), display->getWidth()),
2644 std::max(size.getHeight(), display->getHeight())};
2645 });
2646 }();
chaviwb09c6552021-08-12 17:20:43 -05002647
2648 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2649 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002650 const float xMax = maxSize.getWidth() * 10.f;
2651 const float yMax = maxSize.getHeight() * 10.f;
2652
2653 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002654}
2655
2656void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002657 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002658 for (const auto& layer : mDrawingState.layersSortedByZ) {
2659 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002660 }
2661}
2662
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002663void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002664 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002665 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002666 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002667 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2668 logFrameStats();
2669 }
2670 }
2671}
2672
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002673void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002674 ATRACE_CALL();
2675
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002676 // Keep a copy of the drawing state (that is going to be overwritten
2677 // by commitTransactionsLocked) outside of mStateLock so that the side
2678 // effects of the State assignment don't happen with mStateLock held,
2679 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002680 State drawingState(mDrawingState);
2681
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002682 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002683 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002684
Mathias Agopianca4d3602011-05-19 15:38:14 -07002685 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002686 // so we can call commitTransactionsLocked unconditionally.
2687 // We clear the flags with mStateLock held to guarantee that
2688 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002689 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002690 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002691
Mathias Agopianca4d3602011-05-19 15:38:14 -07002692 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002693}
2694
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002695std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2696 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002697 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2698 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002699
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002700 int attempt = 0;
2701 constexpr int kMaxAttempts = 3;
2702 do {
2703 hwcModes = getHwComposer().getModes(displayId);
2704 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2705 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2706
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002707 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2708 return mode.hwcId == *activeModeHwcId;
2709 };
2710
2711 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2712 break;
2713 }
2714 } while (++attempt < kMaxAttempts);
2715
2716 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002717 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002718 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002719 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002720
2721 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002722 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2723 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002724 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002725
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002726 ui::DisplayModeId nextModeId = 1 +
2727 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2728 [](ui::DisplayModeId max, const auto& pair) {
2729 return std::max(max, pair.first.value());
2730 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002731
2732 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002733 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002734 const DisplayModeId id{nextModeId++};
2735 newModes.try_emplace(id,
2736 DisplayMode::Builder(hwcMode.hwcId)
2737 .setId(id)
2738 .setPhysicalDisplayId(displayId)
2739 .setResolution({hwcMode.width, hwcMode.height})
2740 .setVsyncPeriod(hwcMode.vsyncPeriod)
2741 .setDpiX(hwcMode.dpiX)
2742 .setDpiY(hwcMode.dpiY)
2743 .setGroup(hwcMode.configGroup)
2744 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002745 }
2746
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002747 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002748 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002749 [](const auto& lhs, const auto& rhs) {
2750 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002751 });
2752
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002753 // Keep IDs if modes have not changed.
2754 const auto& modes = sameModes ? oldModes : newModes;
2755 const DisplayModePtr activeMode =
2756 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2757 return pair.second->getHwcId() == activeModeHwcId;
2758 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002759
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002760 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002761}
2762
Lloyd Piqueba04e622017-12-14 17:11:26 -08002763void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2764 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002765 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002766 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002767
Dominik Laskowski075d3172018-05-24 15:50:06 -07002768 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002769 continue;
2770 }
2771
Marin Shalamanova524a092020-07-27 21:39:55 +02002772 const auto displayId = info->id;
Dominik Laskowskieb627312022-04-07 09:13:16 -07002773 const auto token = mPhysicalDisplayTokens.get(displayId);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002774
Peiyong Line9d809e2020-04-14 13:10:48 -07002775 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002776 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002777
Dominik Laskowskieb627312022-04-07 09:13:16 -07002778 if (!token) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002779 ALOGV("Creating display %s", to_string(displayId).c_str());
2780
Dominik Laskowski075d3172018-05-24 15:50:06 -07002781 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002782 state.physical = {.id = displayId,
2783 .type = getHwComposer().getDisplayConnectionType(displayId),
2784 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002785 .deviceProductInfo = std::move(info->deviceProductInfo),
2786 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002787 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002788 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002789 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002790
2791 sp<IBinder> token = new BBinder();
2792 mCurrentState.displays.add(token, state);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002793 mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002794 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002795 } else {
2796 ALOGV("Recreating display %s", to_string(displayId).c_str());
2797
Dominik Laskowskieb627312022-04-07 09:13:16 -07002798 auto& state = mCurrentState.displays.editValueFor(token->get());
2799 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
Marin Shalamanova903d032020-12-29 20:35:13 +01002800 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002801 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002802 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2803 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2804 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002805 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002806 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002807 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002808
Dominik Laskowskieb627312022-04-07 09:13:16 -07002809 if (const ssize_t index = mCurrentState.displays.indexOfKey(token->get()); index >= 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002810 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2811 mInterceptor->saveDisplayDeletion(state.sequenceId);
2812 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002813 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07002814
2815 mPhysicalDisplayTokens.erase(displayId);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002816 }
2817
2818 processDisplayChangesLocked();
2819 }
2820
2821 mPendingHotplugEvents.clear();
2822}
2823
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002824void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002825 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2826 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002827 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2828 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002829}
2830
Lloyd Pique99d3da52018-01-22 17:48:03 -08002831sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002832 const wp<IBinder>& displayToken,
2833 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002834 const DisplayDeviceState& state,
2835 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002836 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002837 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002838 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002839 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002840 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002841 creationArgs.hasWideColorGamut = false;
2842 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002843
Dominik Laskowski55c85402020-01-21 16:25:47 -08002844 if (const auto& physical = state.physical) {
2845 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002846 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002847 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002848 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2849 getKernelIdleTimerProperties(compositionDisplay->getId());
2850
Ady Abraham3efa3942021-06-24 19:01:25 -07002851 scheduler::RefreshRateConfigs::Config config =
2852 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2853 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002854 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002855 .idleTimerTimeout = idleTimerTimeoutMs,
2856 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002857 creationArgs.refreshRateConfigs =
2858 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2859 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002860 }
2861
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002862 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
Dominik Laskowski3c363242022-04-07 10:44:12 -07002863 creationArgs.isPrimary = id == getPrimaryDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002864
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002865 if (useColorManagement) {
2866 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2867 for (ColorMode colorMode : modes) {
2868 if (isWideColorMode(colorMode)) {
2869 creationArgs.hasWideColorGamut = true;
2870 }
2871
2872 std::vector<RenderIntent> renderIntents =
2873 getHwComposer().getRenderIntents(*id, colorMode);
2874 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002875 }
2876 }
tangrobin6753a022018-08-10 10:58:54 +08002877 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002878
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002879 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2880 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2881 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002882 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002883
Lloyd Pique90c115d2018-09-18 21:39:42 -07002884 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002885 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002886 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002887
Lloyd Pique99d3da52018-01-22 17:48:03 -08002888 // Make sure that composition can never be stalled by a virtual display
2889 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002890 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002891 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002892 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2893 }
2894
Dominik Laskowski718f9602019-11-09 20:01:35 -08002895 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002896 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2897 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002898
Lloyd Pique99d3da52018-01-22 17:48:03 -08002899 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002900 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002901
Lloyd Pique9370a482019-10-03 17:58:30 -07002902 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002903
Ady Abraham8565ad22021-06-22 17:45:44 -07002904 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002905
2906 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002907 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002908 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002909 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002910 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002911 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002912 display->getCompositionDisplay()->setColorProfile(
2913 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2914 RenderIntent::COLORIMETRIC,
2915 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002916 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002917 FTL_FAKE_GUARD(kMainThreadContext,
2918 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002919 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002920 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002921
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002922 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002923 display->setProjection(state.orientation, state.layerStackSpaceRect,
2924 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002925 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002926 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002927
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002928 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002929}
2930
Marin Shalamanovae685592020-02-12 17:12:22 +01002931void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2932 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002933 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002934 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2935 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002936 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002937 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2938 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002939 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002940 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002941 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002942 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002943 int format;
2944 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002945 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002946 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002947 } else {
2948 // Virtual displays without a surface are dormant:
2949 // they have external state (layer stack, projection,
2950 // etc.) but no internal state (i.e. a DisplayDevice).
2951 return;
2952 }
2953
2954 compositionengine::DisplayCreationArgsBuilder builder;
2955 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002956 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002957 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002958 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002959 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002960
Marin Shalamanov045b7002021-01-07 16:56:24 +01002961 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002962 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002963 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002964 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002965 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002966 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002967
2968 sp<compositionengine::DisplaySurface> displaySurface;
2969 sp<IGraphicBufferProducer> producer;
2970 sp<IGraphicBufferProducer> bqProducer;
2971 sp<IGraphicBufferConsumer> bqConsumer;
2972 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2973
Marin Shalamanovae685592020-02-12 17:12:22 +01002974 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002975 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2976 LOG_FATAL_IF(!displayId);
2977 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2978 bqProducer, bqConsumer, state.displayName);
2979 displaySurface = surface;
2980 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002981 } else {
2982 ALOGE_IF(state.surface != nullptr,
2983 "adding a supported display, but rendering "
2984 "surface is provided (%p), ignoring it",
2985 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002986 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2987 LOG_FATAL_IF(!displayId);
2988 displaySurface =
2989 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002990 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002991 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002992 producer = bqProducer;
2993 }
2994
Marin Shalamanov700e6392020-02-12 20:22:26 +01002995 LOG_FATAL_IF(!displaySurface);
Dominik Laskowskieb627312022-04-07 09:13:16 -07002996 auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
2997 displaySurface, producer);
Ady Abraham3efa3942021-06-24 19:01:25 -07002998 if (display->isPrimary()) {
2999 initScheduler(display);
3000 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003001 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003002 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01003003 }
Dominik Laskowskieb627312022-04-07 09:13:16 -07003004
3005 mDisplays.try_emplace(displayToken, std::move(display));
Marin Shalamanovae685592020-02-12 17:12:22 +01003006}
3007
3008void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08003009 auto display = getDisplayDeviceLocked(displayToken);
3010 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01003011 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003012
3013 if (display->isVirtual()) {
3014 releaseVirtualDisplay(display->getVirtualId());
3015 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003016 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01003017 }
3018 }
3019
3020 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08003021
3022 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07003023 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08003024 // Destroy the display without holding the mStateLock.
3025 // This is a temporary solution until we can manage transaction queues without
3026 // holding the mStateLock.
3027 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
3028 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
3029 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
3030 // ends up running on the main thread causing a deadlock since setTransactionstate
3031 // will try to acquire the mStateLock. Instead we extend the lifetime of
3032 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
3033 // The display will be disconnected and removed from the mDisplays list so it will
3034 // not be accessible.
3035 }));
3036 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003037}
3038
3039void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
3040 const DisplayDeviceState& currentState,
3041 const DisplayDeviceState& drawingState) {
3042 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3043 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003044
3045 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01003046 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02003047 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003048
Marin Shalamanovae685592020-02-12 17:12:22 +01003049 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3050 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003051 if (display->isVirtual()) {
3052 releaseVirtualDisplay(display->getVirtualId());
3053 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003054 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003055
Marin Shalamanovae685592020-02-12 17:12:22 +01003056 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003057
Marin Shalamanov700e6392020-02-12 20:22:26 +01003058 if (const auto& physical = currentState.physical) {
3059 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3060 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003061
Marin Shalamanovae685592020-02-12 17:12:22 +01003062 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003063
Marin Shalamanov700e6392020-02-12 20:22:26 +01003064 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003065 const auto display = getDisplayDeviceLocked(displayToken);
3066 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003067
3068 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003069 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003070 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003071 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003072 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003073 return;
3074 }
3075
3076 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3077 if (currentState.layerStack != drawingState.layerStack) {
3078 display->setLayerStack(currentState.layerStack);
3079 }
Evan Rosky2239b372021-05-20 13:43:47 -07003080 if (currentState.flags != drawingState.flags) {
3081 display->setFlags(currentState.flags);
3082 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003083 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003084 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3085 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3086 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3087 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003088 if (isDisplayActiveLocked(display)) {
3089 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003090 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003091 }
3092 if (currentState.width != drawingState.width ||
3093 currentState.height != drawingState.height) {
3094 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003095
Ady Abrahamed3290f2021-05-17 15:12:14 -07003096 if (isDisplayActiveLocked(display)) {
3097 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003098 }
3099 }
3100 }
3101}
Ady Abraham3efa3942021-06-24 19:01:25 -07003102void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003103 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003104 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003105 updatePhaseConfiguration(refreshRate);
3106 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003107}
Marin Shalamanovae685592020-02-12 17:12:22 +01003108
Lloyd Pique347200f2017-12-14 17:00:15 -08003109void SurfaceFlinger::processDisplayChangesLocked() {
3110 // here we take advantage of Vector's copy-on-write semantics to
3111 // improve performance by skipping the transaction entirely when
3112 // know that the lists are identical
3113 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3114 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3115 if (!curr.isIdenticalTo(draw)) {
3116 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003117
3118 // find the displays that were removed
3119 // (ie: in drawing state but not in current state)
3120 // also handle displays that changed
3121 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003122 for (size_t i = 0; i < draw.size(); i++) {
3123 const wp<IBinder>& displayToken = draw.keyAt(i);
3124 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003125 if (j < 0) {
3126 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003127 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003128 } else {
3129 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003130 const DisplayDeviceState& currentState = curr[j];
3131 const DisplayDeviceState& drawingState = draw[i];
3132 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003133 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003134 }
3135
3136 // find displays that were added
3137 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003138 for (size_t i = 0; i < curr.size(); i++) {
3139 const wp<IBinder>& displayToken = curr.keyAt(i);
3140 if (draw.indexOfKey(displayToken) < 0) {
3141 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003142 }
3143 }
3144 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003145
3146 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003147}
3148
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003149void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3150 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003151 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3152 if (displayTransactionNeeded) {
3153 processDisplayChangesLocked();
3154 processDisplayHotplugEventsLocked();
3155 }
Robert Carrb552ff52021-06-11 13:35:54 -07003156 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157
Robert Carre450fb52021-06-11 13:21:09 -07003158 if (mSomeChildrenChanged) {
3159 mVisibleRegionsDirty = true;
3160 mSomeChildrenChanged = false;
3161 }
3162
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003163 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003164 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003165 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003166 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003167 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003168 // the hint is set before we acquire a buffer from the surface texture.
3169 //
3170 // NOTE: layer transactions have taken place already, so we use their
3171 // drawing state. However, SurfaceFlinger's own transaction has not
3172 // happened yet, so we must use the current state layer list
3173 // (soon to become the drawing state list).
3174 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003175 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003176 ui::LayerStack layerStack;
3177
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003178 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003179 // NOTE: we rely on the fact that layers are sorted by
3180 // layerStack first (so we don't have to traverse the list
3181 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003182 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3183 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003184 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003185
3186 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003187 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003188 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3189 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003190 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003191
3192 // Pick the primary display if another display mirrors the layer.
3193 if (hintDisplay) {
3194 hintDisplay = nullptr;
3195 break;
3196 }
3197
3198 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003199 }
3200 }
Chet Haase91d25932013-04-11 15:24:55 -07003201
Vishnu Naire3066de2022-06-08 12:16:25 -07003202 if (!hintDisplay && mDisplays.size() > 0) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003203 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3204 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003205
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003206 // could be null when this layer is using a layerStack
3207 // that is not visible on any display. Also can occur at
3208 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003209 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003210 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003211
Vishnu Naire3066de2022-06-08 12:16:25 -07003212 if (hintDisplay) {
3213 layer->updateTransformHint(hintDisplay->getTransformHint());
3214 } else {
3215 ALOGW("Ignoring transform hint update for %s", layer->getDebugName());
3216 }
Robert Carr2047fae2016-11-28 14:09:09 -08003217 });
Mathias Agopian84300952012-11-21 16:02:13 -08003218 }
3219
Robert Carr1f0a16a2016-10-24 16:27:39 -07003220 if (mLayersAdded) {
3221 mLayersAdded = false;
3222 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003223 mVisibleRegionsDirty = true;
3224 }
3225
3226 // some layers might have been removed, so
3227 // we need to update the regions they're exposing.
3228 if (mLayersRemoved) {
3229 mLayersRemoved = false;
3230 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003231 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003232 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003233 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003234 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003235 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003236 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003237 }
Robert Carr2047fae2016-11-28 14:09:09 -08003238 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239 }
3240
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003241 doCommitTransactions();
3242 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3243 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003244}
3245
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003246void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003247 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003248 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003249 return;
3250 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003251
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003252 std::vector<WindowInfo> windowInfos;
3253 std::vector<DisplayInfo> displayInfos;
3254 bool updateWindowInfo = false;
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003255 if (mVisibleRegionsDirty || mInputInfoChanged) {
3256 mInputInfoChanged = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003257 updateWindowInfo = true;
3258 buildWindowInfos(windowInfos, displayInfos);
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003259 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003260 if (!updateWindowInfo && mInputWindowCommands.empty()) {
3261 return;
3262 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003263 BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
3264 windowInfos = std::move(windowInfos),
3265 displayInfos = std::move(displayInfos),
3266 inputWindowCommands =
3267 std::move(mInputWindowCommands),
3268 inputFlinger = mInputFlinger, this]() {
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003269 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3270 if (updateWindowInfo) {
3271 mWindowInfosListenerInvoker->windowInfosChanged(windowInfos, displayInfos,
3272 inputWindowCommands.syncInputWindows);
3273 } else if (inputWindowCommands.syncInputWindows) {
3274 // If the caller requested to sync input windows, but there are no
3275 // changes to input windows, notify immediately.
3276 windowInfosReported();
3277 }
3278 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3279 inputFlinger->setFocusedWindow(focusRequest);
3280 }
Alec Mouri8d7d0f42022-05-10 23:33:40 +00003281 }});
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003282
Arthur Hung6cbb9752019-09-05 16:38:18 +08003283 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003284}
3285
Alec Mouricdf16792021-12-10 13:16:06 -08003286void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3287 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3288 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3289 if (!supportsDisplayBrightnessCommand) {
3290 return;
3291 }
3292
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003293 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003294 if (const auto brightness = display->getStagedBrightness(); brightness) {
3295 if (!needsComposite) {
3296 const status_t error =
3297 getHwComposer()
3298 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003299 display->getCompositionDisplay()
3300 ->getState()
3301 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003302 Hwc2::Composer::DisplayBrightnessOptions{
3303 .applyImmediately = true})
3304 .get();
3305
3306 ALOGE_IF(error != NO_ERROR,
3307 "Error setting display brightness for display %s: %d (%s)",
3308 display->getDebugName().c_str(), error, strerror(error));
3309 }
3310 display->persistBrightness(needsComposite);
3311 }
3312 }
3313}
3314
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003315void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3316 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003317 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3318
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003319 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003320 const auto layerStack = display->getLayerStack();
3321 const auto info = display->getInputInfo();
3322
3323 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003324 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003325 continue;
3326 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003327
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003328 // If the layer stack is mirrored on multiple displays, the first display that is configured
3329 // to receive input takes precedence.
3330 auto& otherInfo = it->second;
3331 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003332 ALOGW_IF(display->receivesInput(),
3333 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003334 layerStack.id);
3335 } else {
3336 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003337 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003338 }
Robert Carr720e5062018-07-30 17:45:14 -07003339
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003340 static size_t sNumWindowInfos = 0;
3341 outWindowInfos.reserve(sNumWindowInfos);
3342 sNumWindowInfos = 0;
3343
Robert Carr720e5062018-07-30 17:45:14 -07003344 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003345 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003346
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003347 // Do not create WindowInfos for windows on displays that cannot receive input.
3348 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3349 const auto& info = opt->get();
3350 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003351 }
Robert Carr720e5062018-07-30 17:45:14 -07003352 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003353
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003354 sNumWindowInfos = outWindowInfos.size();
3355
3356 outDisplayInfos.reserve(displayInputInfos.size());
3357 for (const auto& [_, info] : displayInputInfos) {
3358 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003359 }
Robert Carr720e5062018-07-30 17:45:14 -07003360}
3361
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003362void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003363 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003364 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003365 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003366 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003367 }
3368 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003369
3370 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003371}
3372
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003373void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003374 // If this is called from the main thread mStateLock must be locked before
3375 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003376 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003377
3378 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003379
3380 const auto display = getDefaultDisplayDeviceLocked();
3381 if (!display || mBootStage != BootStage::FINISHED) {
3382 return;
3383 }
3384 ATRACE_CALL();
3385
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003386 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3387 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003388 return;
3389 }
3390
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003391 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003392}
3393
Ady Abraham62a0be22020-12-08 16:54:10 -08003394void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3395 PhysicalDisplayId displayId = [&]() {
3396 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3397 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3398 }();
3399
3400 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3401}
3402
Ady Abraham3efa3942021-06-24 19:01:25 -07003403void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003404 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003405 // If the scheduler is already initialized, this means that we received
3406 // a hotplug(connected) on the primary display. In that case we should
3407 // update the scheduler with the most recent display information.
3408 ALOGW("Scheduler already initialized, updating instead");
3409 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003410 return;
3411 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003412 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003413 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3414 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003415
Marin Shalamanova903d032020-12-29 20:35:13 +01003416 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003417 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003418
Dominik Laskowski068173d2021-08-11 17:22:59 -07003419 using Feature = scheduler::Feature;
3420 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003421
Dominik Laskowski068173d2021-08-11 17:22:59 -07003422 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3423 features |= Feature::kContentDetection;
3424 }
3425 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3426 features |= Feature::kTracePredictedVsync;
3427 }
3428 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003429 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003430 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003431 }
3432
Dominik Laskowski068173d2021-08-11 17:22:59 -07003433 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3434 static_cast<ISchedulerCallback&>(*this),
3435 features);
3436 {
3437 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003438 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003439 features |= Feature::kKernelIdleTimer;
3440 }
3441
3442 mScheduler->createVsyncSchedule(features);
3443 mScheduler->setRefreshRateConfigs(std::move(configs));
3444 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003445 setVsyncEnabled(false);
3446 mScheduler->startTimers();
3447
Ady Abraham9c53ee72020-07-22 21:16:18 -07003448 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003449 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003450 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003451 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003452 /*workDuration=*/configs.late.appWorkDuration,
3453 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003454 impl::EventThread::InterceptVSyncsCallback());
3455 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003456 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3457 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3458 /*readyDuration=*/configs.late.sfWorkDuration,
3459 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003460 mInterceptor->saveVSyncEvent(timestamp);
3461 });
3462
Dominik Laskowski756b7892021-08-04 12:53:59 -07003463 mScheduler->initVsync(mScheduler->getVsyncDispatch(), *mFrameTimeline->getTokenManager(),
3464 configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003465
3466 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003467 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003468 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003469 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003470 // initialization, so that the EventThreads always contain a reference to a
3471 // prior configuration.
3472 //
3473 // This is a bit hacky, but this avoids a back-pointer into the main SF
3474 // classes from EventThread, and there should be no run-time binder cost
3475 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003476 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003477}
3478
Marin Shalamanov5801c942020-12-17 17:00:13 +01003479void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3480 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003481 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003482 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003483}
3484
Ady Abraham55fa7272020-09-30 19:19:27 -07003485void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3486 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003487 mScheduler->setDuration(mAppConnectionHandle,
3488 /*workDuration=*/config.appWorkDuration,
3489 /*readyDuration=*/config.sfWorkDuration);
3490 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003491 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3492 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003493 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003494}
3495
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003496void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003497 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003498
Lloyd Pique58e24a32019-08-01 15:50:14 -07003499 if (!mLayersPendingRemoval.isEmpty()) {
3500 // Notify removed layers now that they can't be drawn from
3501 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003502 // Ensure any buffers set to display on any children are released.
3503 if (l->isRemovedFromCurrentState()) {
3504 l->latchAndReleaseBuffer();
3505 }
3506
chaviw6852bff2022-04-19 17:35:11 -05003507 // If a layer has a parent, we allow it to out-live it's handle
3508 // with the idea that the parent holds a reference and will eventually
3509 // be cleaned up. However no one cleans up the top-level so we do so
3510 // here.
3511 if (l->isAtRoot()) {
3512 l->setIsAtRoot(false);
3513 mCurrentState.layersSortedByZ.remove(l);
3514 }
3515
Lloyd Pique58e24a32019-08-01 15:50:14 -07003516 // If the layer has been removed and has no parent, then it will not be reachable
3517 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3518 // ensure we can copy its current to drawing state.
3519 if (!l->getParent()) {
3520 mOffscreenLayers.emplace(l.get());
3521 }
3522 }
3523 mLayersPendingRemoval.clear();
3524 }
3525
3526 // If this transaction is part of a window animation then the next frame
3527 // we composite should be considered an animation as well.
3528 mAnimCompositionPending = mAnimTransactionPending;
3529
3530 mDrawingState = mCurrentState;
3531 // clear the "changed" flags in current state
3532 mCurrentState.colorMatrixChanged = false;
3533
Robert Carra70e91c2021-06-11 13:59:52 -07003534 if (mVisibleRegionsDirty) {
3535 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3536 rootLayer->commitChildList();
3537 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003538 }
Robert Carra70e91c2021-06-11 13:59:52 -07003539
Lloyd Pique58e24a32019-08-01 15:50:14 -07003540 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003541 if (mNumClones > 0) {
3542 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3543 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003544}
3545
chaviw74d90ad2019-04-26 14:45:26 -07003546void SurfaceFlinger::commitOffscreenLayers() {
3547 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003548 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003549 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3550 layer->doTransaction(0);
3551 layer->commitChildList();
3552 }
chaviw74d90ad2019-04-26 14:45:26 -07003553 });
3554 }
3555}
3556
Chia-I Wuab0c3192017-08-01 11:29:00 -07003557void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003558 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003559 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003560 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003561 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003562 }
3563 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003564}
3565
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003566bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003567 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003568
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003569 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570
Mathias Agopian4fec8732012-06-29 14:12:52 -07003571 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003572 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003573 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003574
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003575 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3576
Eric Penner51c59cd2014-07-28 19:51:58 -07003577 // Store the set of layers that need updates. This set must not change as
3578 // buffers are being latched, as this could result in a deadlock.
3579 // Example: Two producers share the same command stream and:
3580 // 1.) Layer 0 is latched
3581 // 2.) Layer 0 gets a new frame
3582 // 2.) Layer 1 gets a new frame
3583 // 3.) Layer 1 is latched.
3584 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3585 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003586 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003587 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3588 const uint32_t flags = layer->doTransaction(0);
3589 if (flags & Layer::eVisibleRegion) {
3590 mVisibleRegionsDirty = true;
3591 }
3592 }
Robert Carrb552ff52021-06-11 13:35:54 -07003593
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003594 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003595 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003596 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003597 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003598 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003599 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003600 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003601 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003602 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003603 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003604 }
Robert Carr2047fae2016-11-28 14:09:09 -08003605 });
Robert Carrb552ff52021-06-11 13:35:54 -07003606 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003607
chaviw49a108c2019-08-12 11:23:06 -07003608 // The client can continue submitting buffers for offscreen layers, but they will not
3609 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3610 // layers to ensure dequeueBuffer doesn't block indefinitely.
3611 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003612 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003613 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3614 }
3615
Lloyd Piquef2c79392018-12-20 16:23:33 -08003616 if (!mLayersWithQueuedFrames.empty()) {
3617 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3618 // writes to Layer current state. See also b/119481871
3619 Mutex::Autolock lock(mStateLock);
3620
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003621 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003622 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003623 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003624 newDataLatched = true;
3625 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003626 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003627 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003628 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003629
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003630 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003631
3632 // If we will need to wake up at some time in the future to deal with a
3633 // queued frame that shouldn't be displayed during this vsync period, wake
3634 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003635 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003636 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003637 }
3638
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003639 // enter boot animation on first buffer latch
3640 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3641 ALOGI("Enter boot animation");
3642 mBootStage = BootStage::BOOTANIMATION;
3643 }
3644
Robert Carr6a0382d2021-07-01 15:57:17 -07003645 if (mNumClones > 0) {
3646 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3647 }
chaviw74b03172019-08-19 11:09:03 -07003648
Dan Stoza6b9454d2014-11-07 16:00:59 -08003649 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003650 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003651}
3652
Robert Carrc0df3122019-04-11 13:18:21 -07003653status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003654 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003655 bool addToRoot, uint32_t* outTransformHint) {
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003656 if (mNumLayers >= MAX_LAYERS) {
arthurhungdba591c2021-02-08 17:28:49 +08003657 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Huihong Luo1b0c49f2022-03-15 19:18:21 -07003658 MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003659 static_cast<void>(mScheduler->schedule([=] {
3660 ALOGE("Dumping random sampling of on-screen layers: ");
3661 mDrawingState.traverse([&](Layer *layer) {
3662 // Aim to dump about 200 layers to avoid totally trashing
3663 // logcat. On the other hand, if there really are 4096 layers
3664 // something has gone totally wrong its probably the most
3665 // useful information in logcat.
3666 if (rand() % 20 == 13) {
3667 ALOGE("Layer: %s", layer->getName().c_str());
3668 }
3669 });
3670 for (Layer* offscreenLayer : mOffscreenLayers) {
3671 if (rand() % 20 == 13) {
3672 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3673 }
3674 }
3675 }));
arthurhungdba591c2021-02-08 17:28:49 +08003676 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003677 }
3678
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003679 {
3680 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3681 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3682 }
arthurhungdba591c2021-02-08 17:28:49 +08003683
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003684 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003685 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003686 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003687 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003688 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003689 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003690 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003691 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003692
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003693 setTransactionFlags(eTransactionNeeded);
3694 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003695}
3696
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003697uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003698 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003699}
3700
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003701uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3702 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003703}
3704
Dominik Laskowski94000c42022-03-17 12:55:14 -07003705void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003706 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003707 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003708
3709 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003710 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003711 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003712}
3713
Ady Abraham9dada822022-02-03 10:26:59 -08003714bool SurfaceFlinger::stopTransactionProcessing(
3715 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3716 applyTokensWithUnsignaledTransactions) const {
3717 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3718 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3719 // then we should have only one applyToken for processing.
3720 // so we can stop further transactions on this applyToken.
3721 return !applyTokensWithUnsignaledTransactions.empty();
3722 }
3723
3724 return false;
3725}
3726
ramindani9eff2492022-03-23 00:28:26 +00003727int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3728 std::vector<TransactionState>& transactions,
3729 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3730 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3731 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3732 applyTokensWithUnsignaledTransactions,
3733 /*tryApplyUnsignaled*/ true);
3734}
3735
Robert Carr79dc06a2022-02-22 15:28:59 -08003736int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003737 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003738 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003739 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3740 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003741 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003742 auto it = mPendingTransactionQueues.begin();
3743 while (it != mPendingTransactionQueues.end()) {
3744 auto& [applyToken, transactionQueue] = *it;
3745 while (!transactionQueue.empty()) {
3746 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3747 ATRACE_NAME("stopTransactionProcessing");
3748 break;
3749 }
3750
3751 auto& transaction = transactionQueue.front();
3752 const auto ready =
Robert Carr4c1b6462021-12-21 10:30:50 -08003753 transactionIsReadyToBeApplied(transaction,
3754 transaction.frameTimelineInfo,
3755 transaction.isAutoTimestamp,
3756 transaction.desiredPresentTime,
3757 transaction.originUid, transaction.states,
3758 bufferLayersReadyToPresent, transactions.size(),
3759 tryApplyUnsignaled);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003760 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3761 if (ready == TransactionReadiness::NotReady) {
3762 setTransactionFlags(eTransactionFlushNeeded);
3763 break;
3764 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003765 if (ready == TransactionReadiness::NotReadyBarrier) {
3766 transactionsPendingBarrier++;
3767 setTransactionFlags(eTransactionFlushNeeded);
3768 break;
3769 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003770 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003771 const bool frameNumberChanged = state.bufferData->flags.test(
3772 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003773 if (frameNumberChanged) {
3774 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3775 } else {
3776 // Barrier function only used for BBQ which always includes a frame number
3777 bufferLayersReadyToPresent[state.surface] =
3778 std::numeric_limits<uint64_t>::max();
3779 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003780 });
3781 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3782 if (appliedUnsignaled) {
3783 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3784 }
3785
3786 transactions.emplace_back(std::move(transaction));
3787 transactionQueue.pop();
3788 }
3789
3790 if (transactionQueue.empty()) {
3791 it = mPendingTransactionQueues.erase(it);
3792 mTransactionQueueCV.broadcast();
3793 } else {
3794 it = std::next(it, 1);
3795 }
3796 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003797 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003798}
3799
Vishnu Nair7891e962021-11-11 12:07:21 -08003800bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003801 // to prevent onHandleDestroyed from being called while the lock is held,
3802 // we must keep a copy of the transactions (specifically the composer
3803 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003804 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003805 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003806 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003807 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003808 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003809 Mutex::Autolock _l(mStateLock);
3810 {
3811 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003812
Robert Carr79dc06a2022-02-22 15:28:59 -08003813 int lastTransactionsPendingBarrier = 0;
3814 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003815 // First collect transactions from the pending transaction queues.
3816 // We are not allowing unsignaled buffers here as we want to
3817 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003818 transactionsPendingBarrier =
3819 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3820 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003821
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003822 // Second, collect transactions from the transaction queue.
3823 // Here as well we are not allowing unsignaled buffers for the same
3824 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003825 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003826 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003827 const bool pendingTransactions =
3828 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003829 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003830 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003831 if (pendingTransactions) {
3832 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003833 return TransactionReadiness::NotReady;
3834 }
3835
Robert Carr4c1b6462021-12-21 10:30:50 -08003836 return transactionIsReadyToBeApplied(transaction, transaction.frameTimelineInfo,
Ady Abraham9dada822022-02-03 10:26:59 -08003837 transaction.isAutoTimestamp,
3838 transaction.desiredPresentTime,
3839 transaction.originUid, transaction.states,
3840 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003841 transactions.size(),
3842 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003843 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003844 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003845 if (ready != TransactionReadiness::Ready) {
3846 if (ready == TransactionReadiness::NotReadyBarrier) {
3847 transactionsPendingBarrier++;
3848 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003849 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003850 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003851 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003852 const bool frameNumberChanged = state.bufferData->flags.test(
3853 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003854 if (frameNumberChanged) {
3855 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3856 } else {
3857 // Barrier function only used for BBQ which always includes a frame number.
3858 // This value only used for barrier logic.
3859 bufferLayersReadyToPresent[state.surface] =
3860 std::numeric_limits<uint64_t>::max();
3861 }
Xiang Wang76236e12022-03-22 17:25:30 +00003862 });
Ady Abraham9dada822022-02-03 10:26:59 -08003863 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003864 }
ramindani4d48f902021-09-20 21:07:45 +00003865 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003866 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003867 }
Arthur Hung58144272021-01-16 03:43:53 +00003868
Robert Carr79dc06a2022-02-22 15:28:59 -08003869 // Transactions with a buffer pending on a barrier may be on a different applyToken
3870 // than the transaction which satisfies our barrier. In fact this is the exact use case
3871 // that the primitive is designed for. This means we may first process
3872 // the barrier dependent transaction, determine it ineligible to complete
3873 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3874 // The barrier dependent transaction was eligible to be presented in this frame
3875 // but we would have prevented it without case. To fix this we continually
3876 // loop through flushPendingTransactionQueues until we perform an iteration
3877 // where the number of transactionsPendingBarrier doesn't change. This way
3878 // we can continue to resolve dependency chains of barriers as far as possible.
3879 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3880 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3881 transactionsPendingBarrier =
3882 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3883 applyTokensWithUnsignaledTransactions,
3884 /*tryApplyUnsignaled*/ false);
3885 }
3886
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003887 // We collected all transactions that could apply without latching unsignaled buffers.
3888 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3889 // transactions that were not applied and try to apply them unsignaled.
3890 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003891 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3892 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003893 }
3894
Vishnu Nair7891e962021-11-11 12:07:21 -08003895 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003896 }
ramindani4d48f902021-09-20 21:07:45 +00003897 }
3898}
3899
Vishnu Nair7891e962021-11-11 12:07:21 -08003900bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3901 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003902 bool needsTraversal = false;
3903 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003904 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003905 needsTraversal |=
3906 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3907 transaction.displays, transaction.flags,
3908 transaction.inputWindowCommands,
3909 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3910 transaction.buffer, transaction.postTime,
3911 transaction.permissions, transaction.hasListenerCallbacks,
3912 transaction.listenerCallbacks, transaction.originPid,
3913 transaction.originUid, transaction.id);
3914 if (transaction.transactionCommittedSignal) {
3915 mTransactionCommittedSignals.emplace_back(
3916 std::move(transaction.transactionCommittedSignal));
3917 }
3918 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003919
Dominik Laskowski46471e62022-01-14 15:34:03 -08003920 if (mTransactionTracing) {
3921 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003922 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003923 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003924}
3925
3926bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003927 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003928 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003929}
3930
Ady Abraham8db10102021-03-15 17:19:23 -07003931bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3932 // The amount of time SF can delay a frame if it is considered early based
3933 // on the VsyncModulator::VsyncConfig::appWorkDuration
3934 constexpr static std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3935
3936 const auto currentVsyncPeriod = mScheduler->getDisplayStatInfo(systemTime()).vsyncPeriod;
3937 const auto earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
3938
3939 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3940 if (!prediction.has_value()) {
3941 return false;
3942 }
3943
3944 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3945 kEarlyLatchMaxThreshold.count()) {
3946 return false;
3947 }
3948
3949 return prediction->presentTime >= expectedPresentTime &&
3950 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3951}
Ady Abraham9dada822022-02-03 10:26:59 -08003952bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003953 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003954 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3955 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3956 return false;
3957 }
Ady Abraham8db10102021-03-15 17:19:23 -07003958
Ady Abraham9dada822022-02-03 10:26:59 -08003959 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3960 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3961 return true;
3962 }
3963
3964 // We only want to latch unsignaled when a single layer is updated in this
3965 // transaction (i.e. not a blast sync transaction).
3966 if (numStates != 1) {
3967 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3968 return false;
3969 }
3970
Ady Abraham2739e832022-02-14 17:42:00 -08003971 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3972 if (totalTXapplied > 0) {
3973 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3974 __func__, totalTXapplied);
3975 return false;
3976 }
3977
3978 // We don't want to latch unsignaled if are in early / client composition
3979 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3980 // or window animations being slow.
3981 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3982 if (!isDefaultVsyncConfig) {
3983 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3984 __func__);
3985 return false;
3986 }
Ady Abraham9dada822022-02-03 10:26:59 -08003987 }
3988
3989 if (!layer->simpleBufferUpdate(state)) {
3990 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3991 return false;
3992 }
3993
3994 ALOGV("%s: true", __func__);
3995 return true;
3996}
3997
Robert Carr4c1b6462021-12-21 10:30:50 -08003998auto SurfaceFlinger::transactionIsReadyToBeApplied(TransactionState& transaction,
Ady Abraham43752eb2021-03-04 16:24:25 -08003999 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08004000 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08004001 const std::unordered_map<
4002 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004003 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00004004 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07004005 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08004006 // Do not present if the desiredPresentTime has not passed unless it is more than one second
4007 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08004008 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08004009 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004010 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08004011 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08004012 }
4013
Ady Abraham5690bda2021-03-12 15:01:18 -08004014 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
4015 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08004016 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08004017 }
4018
Ady Abraham8db10102021-03-15 17:19:23 -07004019 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
4020 // present time of this transaction.
4021 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
4022 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08004023 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07004024 }
4025
Ady Abraham9dada822022-02-03 10:26:59 -08004026 bool fenceUnsignaled = false;
Robert Carr4c1b6462021-12-21 10:30:50 -08004027 auto queueProcessTime = systemTime();
Marissa Wall713b63f2018-10-17 15:42:43 -07004028 for (const ComposerState& state : states) {
4029 const layer_state_t& s = state.state;
Robert Carr4c1b6462021-12-21 10:30:50 -08004030
Ady Abrahamf20c1922020-12-21 18:39:01 -08004031 sp<Layer> layer = nullptr;
4032 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07004033 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004034 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08004035 ALOGW("Transaction with buffer, but no Layer?");
4036 continue;
4037 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08004038 if (!layer) {
4039 continue;
4040 }
Ady Abraham43752eb2021-03-04 16:24:25 -08004041
Robert Carr79dc06a2022-02-22 15:28:59 -08004042 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
4043 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
4044 const bool willApplyBarrierFrame =
4045 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
4046 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
4047 if (!willApplyBarrierFrame) {
4048 ATRACE_NAME("NotReadyBarrier");
4049 return TransactionReadiness::NotReadyBarrier;
4050 }
4051 }
4052
Ady Abrahame1bfaac2022-02-22 21:32:08 -08004053 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08004054 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08004055 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
4056 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08004057
4058 const bool acquireFenceChanged = s.bufferData &&
4059 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
4060 s.bufferData->acquireFence;
4061 fenceUnsignaled = fenceUnsignaled ||
4062 (acquireFenceChanged &&
4063 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
4064
4065 if (fenceUnsignaled && !allowLatchUnsignaled) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004066 if (!transaction.sentFenceTimeoutWarning &&
4067 queueProcessTime - transaction.queueTime > std::chrono::nanoseconds(4s).count()) {
4068 transaction.sentFenceTimeoutWarning = true;
4069 auto listener = s.bufferData->releaseBufferListener;
4070 if (listener) {
4071 listener->onTransactionQueueStalled();
4072 }
4073 }
4074
Ady Abraham9dada822022-02-03 10:26:59 -08004075 ATRACE_NAME("fence unsignaled");
4076 return TransactionReadiness::NotReady;
4077 }
4078
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004079 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08004080 // If backpressure is enabled and we already have a buffer to commit, keep the
4081 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004082 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4083 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004084 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004085 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004086 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004087 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004088 }
4089 }
Ady Abraham9dada822022-02-03 10:26:59 -08004090 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004091}
4092
arthurhungf1b7c7b2021-03-03 17:42:23 +08004093void SurfaceFlinger::queueTransaction(TransactionState& state) {
Robert Carr4c1b6462021-12-21 10:30:50 -08004094 state.queueTime = systemTime();
4095
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004096 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004097
arthurhungf1b7c7b2021-03-03 17:42:23 +08004098 // Generate a CountDownLatch pending state if this is a synchronous transaction.
4099 if ((state.flags & eSynchronous) || state.inputWindowCommands.syncInputWindows) {
4100 state.transactionCommittedSignal = std::make_shared<CountDownLatch>(
Arthur Hung2274a312021-04-28 15:13:06 +00004101 (state.inputWindowCommands.syncInputWindows
4102 ? (CountDownLatch::eSyncInputWindows | CountDownLatch::eSyncTransaction)
4103 : CountDownLatch::eSyncTransaction));
arthurhungf1b7c7b2021-03-03 17:42:23 +08004104 }
4105
ramindani4d48f902021-09-20 21:07:45 +00004106 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004107 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4108
Ady Abrahame46243a2021-02-23 19:33:49 -08004109 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004110 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4111 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004112 return TransactionSchedule::Late;
4113 }(state.flags);
4114
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004115 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4116
4117 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004118}
4119
arthurhungf1b7c7b2021-03-03 17:42:23 +08004120void SurfaceFlinger::waitForSynchronousTransaction(
4121 const CountDownLatch& transactionCommittedSignal) {
4122 // applyTransactionState is called on the main SF thread. While a given process may wish
4123 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4124 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004125 if (!transactionCommittedSignal.wait_until(
4126 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004127 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004128 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004129}
Ady Abrahame46243a2021-02-23 19:33:49 -08004130
Arthur Hung2274a312021-04-28 15:13:06 +00004131void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004132 for (auto it = mTransactionCommittedSignals.begin();
4133 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004134 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004135 it = mTransactionCommittedSignals.erase(it);
4136 } else {
4137 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004138 }
4139 }
4140}
4141
chaviw308ddba2020-08-11 16:23:51 -07004142status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004143 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004144 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4145 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004146 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004147 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004148 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004149
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004150 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004151 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4152 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004153 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4154 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004155 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004156 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004157 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004158 }
4159
Leon Scroggins9a20f722021-12-28 14:43:12 +00004160 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004161 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004162 }
4163
Robert Carrde6d7b42022-01-07 18:23:06 -08004164 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004165 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4166 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4167 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004168 }
4169
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004170 const int64_t postTime = systemTime();
4171
4172 IPCThreadState* ipc = IPCThreadState::self();
4173 const int originPid = ipc->getCallingPid();
4174 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004175 TransactionState state{frameTimelineInfo, states,
4176 displays, flags,
4177 applyToken, inputWindowCommands,
4178 desiredPresentTime, isAutoTimestamp,
4179 uncacheBuffer, postTime,
4180 permissions, hasListenerCallbacks,
4181 listenerCallbacks, originPid,
4182 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004183
4184 // Check for incoming buffer updates and increment the pending buffer count.
4185 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4186 mBufferCountTracker.increment(state.surface->localBinder());
4187 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004188
Dominik Laskowski46471e62022-01-14 15:34:03 -08004189 if (mTransactionTracing) {
4190 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004191 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004192 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004193
arthurhungf1b7c7b2021-03-03 17:42:23 +08004194 // Check the pending state to make sure the transaction is synchronous.
4195 if (state.transactionCommittedSignal) {
4196 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004197 }
4198
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004199 return NO_ERROR;
4200}
Marissa Wall713b63f2018-10-17 15:42:43 -07004201
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004202bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004203 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004204 const Vector<DisplayState>& displays, uint32_t flags,
4205 const InputWindowCommands& inputWindowCommands,
4206 const int64_t desiredPresentTime, bool isAutoTimestamp,
4207 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004208 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004209 bool hasListenerCallbacks,
4210 const std::vector<ListenerCallbacks>& listenerCallbacks,
4211 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004212 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004213 for (const DisplayState& display : displays) {
4214 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004215 }
4216
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004217 // start and end registration for listeners w/ no surface so they can get their callback. Note
4218 // that listeners with SurfaceControls will start registration during setClientStateLocked
4219 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004220 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004221 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004222 }
4223
Marissa Walle2ffb422018-10-12 11:33:52 -07004224 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004225 for (int i = 0; i < states.size(); i++) {
4226 ComposerState& state = states.editItemAt(i);
4227 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004228 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004229 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004230 if (const auto layer = fromHandle(state.state.surface).promote()) {
4231 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004232 mScheduler->recordLayerHistory(layer.get(),
4233 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004234 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004235 }
4236 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004237 }
4238
Marissa Walle2ffb422018-10-12 11:33:52 -07004239 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004240
Robert Carrde6d7b42022-01-07 18:23:06 -08004241 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004242 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4243 } else if (!inputWindowCommands.empty()) {
4244 ALOGE("Only privileged callers are allowed to send input commands.");
4245 }
chaviw273171b2018-12-26 11:46:30 -08004246
Marissa Wall947d34e2019-03-29 14:03:53 -07004247 if (uncacheBuffer.isValid()) {
4248 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004249 }
4250
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004251 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4252 // anyway. This can be used as a flush mechanism for previous async transactions.
4253 // Empty animation transaction can be used to simulate back-pressure, so also force a
4254 // transaction for empty animation transactions.
4255 if (transactionFlags == 0 &&
4256 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004257 transactionFlags = eTransactionNeeded;
4258 }
4259
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004260 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004261 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004262 if (mInterceptor->isEnabled()) {
4263 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004264 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004265 }
4266
Arthur Hung58144272021-01-16 03:43:53 +00004267 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4268 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4269 if (transactionFlags & eTraversalNeeded) {
4270 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004271 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004272 }
Arthur Hung58144272021-01-16 03:43:53 +00004273 if (transactionFlags) {
4274 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004275 }
4276
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004277 if (flags & eAnimation) {
4278 mAnimTransactionPending = true;
4279 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004280 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004281
4282 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004283}
4284
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004285uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4286 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4287 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004288
Mathias Agopiane57f2922012-08-09 16:29:12 -07004289 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004290 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4291
4292 const uint32_t what = s.what;
4293 if (what & DisplayState::eSurfaceChanged) {
4294 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4295 state.surface = s.surface;
4296 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004297 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004298 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004299 if (what & DisplayState::eLayerStackChanged) {
4300 if (state.layerStack != s.layerStack) {
4301 state.layerStack = s.layerStack;
4302 flags |= eDisplayTransactionNeeded;
4303 }
4304 }
Evan Rosky2239b372021-05-20 13:43:47 -07004305 if (what & DisplayState::eFlagsChanged) {
4306 if (state.flags != s.flags) {
4307 state.flags = s.flags;
4308 flags |= eDisplayTransactionNeeded;
4309 }
4310 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004311 if (what & DisplayState::eDisplayProjectionChanged) {
4312 if (state.orientation != s.orientation) {
4313 state.orientation = s.orientation;
4314 flags |= eDisplayTransactionNeeded;
4315 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004316 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4317 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004318 flags |= eDisplayTransactionNeeded;
4319 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004320 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4321 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004322 flags |= eDisplayTransactionNeeded;
4323 }
4324 }
4325 if (what & DisplayState::eDisplaySizeChanged) {
4326 if (state.width != s.width) {
4327 state.width = s.width;
4328 flags |= eDisplayTransactionNeeded;
4329 }
4330 if (state.height != s.height) {
4331 state.height = s.height;
4332 flags |= eDisplayTransactionNeeded;
4333 }
4334 }
4335
Mathias Agopiane57f2922012-08-09 16:29:12 -07004336 return flags;
4337}
4338
Steven Thomasd4071902020-03-24 16:02:53 -07004339bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004340 IPCThreadState* ipc = IPCThreadState::self();
4341 const int pid = ipc->getCallingPid();
4342 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004343 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004344 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4345 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004346 return false;
4347 }
4348 return true;
4349}
4350
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004351uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004352 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004353 int64_t desiredPresentTime, bool isAutoTimestamp,
4354 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004355 layer_state_t& s = composerState.state;
4356 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004357
4358 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004359 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004360 // Starts a registration but separates the callback ids according to callback type. This
4361 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004362 // note that startRegistration will not re-register if the listener has
4363 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004364
4365 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4366 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004367 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004368 }
4369
4370 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4371 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004372 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004373 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004374 }
4375
arthurhungdba591c2021-02-08 17:28:49 +08004376 const uint64_t what = s.what;
4377 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004378 sp<Layer> layer = nullptr;
4379 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004380 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004381 } else {
4382 // The client may provide us a null handle. Treat it as if the layer was removed.
4383 ALOGW("Attempt to set client state with a null layer handle");
4384 }
chaviw8b3871a2017-11-01 17:41:01 -07004385 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004386 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004387 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004388 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004389 }
chaviw8b3871a2017-11-01 17:41:01 -07004390 return 0;
4391 }
4392
Valerie Hau871d6352020-01-29 08:44:02 -08004393 // Only set by BLAST adapter layers
4394 if (what & layer_state_t::eProducerDisconnect) {
4395 layer->onDisconnect();
4396 }
4397
chaviw8b3871a2017-11-01 17:41:01 -07004398 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004399 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004400 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004401 }
chaviw8b3871a2017-11-01 17:41:01 -07004402 }
4403 if (what & layer_state_t::eLayerChanged) {
4404 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004405 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004406 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004407 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004408 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004409 mCurrentState.layersSortedByZ.removeAt(idx);
4410 mCurrentState.layersSortedByZ.add(layer);
4411 // we need traversal (state changed)
4412 // AND transaction (list changed)
4413 flags |= eTransactionNeeded|eTraversalNeeded;
4414 }
chaviw8b3871a2017-11-01 17:41:01 -07004415 } else {
4416 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004417 flags |= eTransactionNeeded|eTraversalNeeded;
4418 }
4419 }
chaviw8b3871a2017-11-01 17:41:01 -07004420 }
4421 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004422 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004423 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004424 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4425 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004426 if (p == nullptr) {
4427 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004428 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004429 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004430 mCurrentState.layersSortedByZ.removeAt(idx);
4431 mCurrentState.layersSortedByZ.add(layer);
4432 // we need traversal (state changed)
4433 // AND transaction (list changed)
4434 flags |= eTransactionNeeded|eTraversalNeeded;
4435 }
4436 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004437 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004438 flags |= eTransactionNeeded|eTraversalNeeded;
4439 }
chaviw8b3871a2017-11-01 17:41:01 -07004440 }
4441 }
4442 if (what & layer_state_t::eSizeChanged) {
4443 if (layer->setSize(s.w, s.h)) {
4444 flags |= eTraversalNeeded;
4445 }
4446 }
4447 if (what & layer_state_t::eAlphaChanged) {
4448 if (layer->setAlpha(s.alpha))
4449 flags |= eTraversalNeeded;
4450 }
4451 if (what & layer_state_t::eColorChanged) {
4452 if (layer->setColor(s.color))
4453 flags |= eTraversalNeeded;
4454 }
Peiyong Lind3788632018-09-18 16:01:31 -07004455 if (what & layer_state_t::eColorTransformChanged) {
4456 if (layer->setColorTransform(s.colorTransform)) {
4457 flags |= eTraversalNeeded;
4458 }
4459 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004460 if (what & layer_state_t::eBackgroundColorChanged) {
4461 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4462 flags |= eTraversalNeeded;
4463 }
4464 }
chaviw8b3871a2017-11-01 17:41:01 -07004465 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004466 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004467 }
4468 if (what & layer_state_t::eTransparentRegionChanged) {
4469 if (layer->setTransparentRegionHint(s.transparentRegion))
4470 flags |= eTraversalNeeded;
4471 }
4472 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004473 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004474 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004475 if (what & layer_state_t::eCornerRadiusChanged) {
4476 if (layer->setCornerRadius(s.cornerRadius))
4477 flags |= eTraversalNeeded;
4478 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004479 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004480 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4481 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004482 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004483 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4484 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00004485 if (what & layer_state_t::eRenderBorderChanged) {
Tianhao Yao10cea3c2022-03-30 01:37:22 +00004486 if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00004487 flags |= eTraversalNeeded;
4488 }
4489 }
chaviw8b3871a2017-11-01 17:41:01 -07004490 if (what & layer_state_t::eLayerStackChanged) {
4491 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4492 // We only allow setting layer stacks for top level layers,
4493 // everything else inherits layer stack from its parent.
4494 if (layer->hasParent()) {
4495 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004496 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004497 } else if (idx < 0) {
4498 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004499 "that also does not appear in the top level layer list. Something"
4500 " has gone wrong.",
4501 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004502 } else if (layer->setLayerStack(s.layerStack)) {
4503 mCurrentState.layersSortedByZ.removeAt(idx);
4504 mCurrentState.layersSortedByZ.add(layer);
4505 // we need traversal (state changed)
4506 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004507 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004508 }
4509 }
Marissa Wall61c58622018-07-18 10:12:20 -07004510 if (what & layer_state_t::eTransformChanged) {
4511 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4512 }
4513 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4514 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4515 flags |= eTraversalNeeded;
4516 }
4517 if (what & layer_state_t::eCropChanged) {
4518 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4519 }
Marissa Wall61c58622018-07-18 10:12:20 -07004520 if (what & layer_state_t::eDataspaceChanged) {
4521 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4522 }
4523 if (what & layer_state_t::eHdrMetadataChanged) {
4524 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4525 }
4526 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4527 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4528 }
4529 if (what & layer_state_t::eApiChanged) {
4530 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4531 }
4532 if (what & layer_state_t::eSidebandStreamChanged) {
4533 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4534 }
Robert Carr720e5062018-07-30 17:45:14 -07004535 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004536 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4537 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004538 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004539 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004540 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004541 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004542
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004543 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4544 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004545 // The transaction will be received on the Task layer and needs to be applied to all
4546 // child layers. Child layers that are added at a later point will obtain the game mode
4547 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004548 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004549 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004550
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004551 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4552 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004553 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4554 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4555 flags |= eTraversalNeeded;
4556 }
4557 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004558 if (what & layer_state_t::eShadowRadiusChanged) {
4559 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4560 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004561 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004562 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004563 flags |= eTraversalNeeded;
4564 }
4565 }
Steven Thomas3172e202020-01-06 19:25:30 -08004566 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004567 const auto compatibility =
4568 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4569 const auto strategy =
4570 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004571
Robert Carrde6d7b42022-01-07 18:23:06 -08004572 if (layer->setFrameRate(
4573 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4574 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004575 }
Steven Thomas3172e202020-01-06 19:25:30 -08004576 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004577 if (what & layer_state_t::eFixedTransformHintChanged) {
4578 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4579 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4580 }
4581 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004582 if (what & layer_state_t::eAutoRefreshChanged) {
4583 layer->setAutoRefresh(s.autoRefresh);
4584 }
Sally Qi421ffb02022-03-21 19:41:33 -07004585 if (what & layer_state_t::eDimmingEnabledChanged) {
4586 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4587 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004588 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004589 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4590 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004591 }
4592 }
John Reckcdb4ed72021-02-04 13:39:33 -05004593 if (what & layer_state_t::eStretchChanged) {
4594 if (layer->setStretchEffect(s.stretchEffect)) {
4595 flags |= eTraversalNeeded;
4596 }
4597 }
chaviwf3f40fe2021-04-27 15:54:02 -05004598 if (what & layer_state_t::eBufferCropChanged) {
4599 if (layer->setBufferCrop(s.bufferCrop)) {
4600 flags |= eTraversalNeeded;
4601 }
4602 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004603 if (what & layer_state_t::eDestinationFrameChanged) {
4604 if (layer->setDestinationFrame(s.destinationFrame)) {
4605 flags |= eTraversalNeeded;
4606 }
4607 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004608 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004609 if (layer->setDropInputMode(s.dropInputMode)) {
4610 flags |= eTraversalNeeded;
4611 mInputInfoChanged = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004612 }
4613 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004614 // This has to happen after we reparent children because when we reparent to null we remove
4615 // child layers from current state and remove its relative z. If the children are reparented in
4616 // the same transaction, then we have to make sure we reparent the children first so we do not
4617 // lose its relative z order.
4618 if (what & layer_state_t::eReparent) {
4619 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004620 auto parentHandle = (s.parentSurfaceControlForChild)
4621 ? s.parentSurfaceControlForChild->getHandle()
4622 : nullptr;
4623 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004624 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004625 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004626 mCurrentState.layersSortedByZ.remove(layer);
4627 }
4628 flags |= eTransactionNeeded | eTraversalNeeded;
4629 }
4630 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004631 std::vector<sp<CallbackHandle>> callbackHandles;
4632 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4633 for (auto& [listener, callbackIds] : filteredListeners) {
4634 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4635 }
4636 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004637
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004638 if (what & layer_state_t::eBufferChanged) {
4639 std::shared_ptr<renderengine::ExternalTexture> buffer =
4640 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4641 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4642 dequeueBufferTimestamp, frameTimelineInfo)) {
4643 flags |= eTraversalNeeded;
4644 }
Ady Abraham8db10102021-03-15 17:19:23 -07004645 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4646 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004647 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004648
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004649 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004650 // Do not put anything that updates layer state or modifies flags after
4651 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004652 return flags;
4653}
4654
chaviw273171b2018-12-26 11:46:30 -08004655uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004656 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004657 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004658}
4659
Vishnu Nair84125ac2021-12-02 08:47:48 -08004660status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4661 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4662 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004663 if (!mirrorFromHandle) {
4664 return NAME_NOT_FOUND;
4665 }
4666
4667 sp<Layer> mirrorLayer;
4668 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004669 {
4670 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004671 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004672 if (!mirrorFrom) {
4673 return NAME_NOT_FOUND;
4674 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004675 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004676 if (result != NO_ERROR) {
4677 return result;
4678 }
4679
Robert Carr6a0382d2021-07-01 15:57:17 -07004680 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004681 }
4682
Ady Abraham9f0a4002020-10-05 15:47:26 -07004683 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004684 if (mTransactionTracing) {
4685 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4686 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004687 }
4688 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004689 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004690}
4691
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004692status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004693 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4694 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004695 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4696 "Expected only one of parentLayer or parentHandle to be non-null. "
4697 "Programmer error?");
4698
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004699 status_t result = NO_ERROR;
4700
4701 sp<Layer> layer;
4702
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004703 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004704 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004705 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004706 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004707 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4708 if (pendingBufferCounter) {
4709 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004710 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004711 pendingBufferCounter);
4712 }
4713 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004714 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004715 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004716 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004717 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004718 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004719 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004720 default:
4721 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004722 break;
4723 }
4724
Dan Stoza7d89d062015-04-30 13:29:25 -07004725 if (result != NO_ERROR) {
4726 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004727 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004728
Vishnu Nair858a3b42022-01-12 20:42:28 -08004729 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004730 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4731 if (parentHandle != nullptr && parent == nullptr) {
4732 ALOGE("Invalid parent handle %p.", parentHandle.get());
4733 addToRoot = false;
4734 }
4735 if (parentLayer != nullptr) {
4736 addToRoot = false;
4737 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004738
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004739 int parentId = -1;
4740 // We can safely promote the layer in binder thread because we have a strong reference
4741 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4742 sp<Layer> parentSp = parent.promote();
4743 if (parentSp != nullptr) {
4744 parentId = parentSp->getSequence();
4745 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004746 if (mTransactionTracing) {
4747 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4748 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004749 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004750
Vishnu Nair047fb332021-12-09 09:54:36 -08004751 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4752 if (result != NO_ERROR) {
4753 return result;
4754 }
4755
Ady Abraham9f0a4002020-10-05 15:47:26 -07004756 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004757 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004758}
4759
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004760status_t SurfaceFlinger::createBufferQueueLayer(LayerCreationArgs& args, PixelFormat& format,
Evan Roskya1f1e152019-01-24 16:17:46 -08004761 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004762 sp<IGraphicBufferProducer>* gbp,
4763 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004764 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004765 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004766 case PIXEL_FORMAT_TRANSPARENT:
4767 case PIXEL_FORMAT_TRANSLUCENT:
4768 format = PIXEL_FORMAT_RGBA_8888;
4769 break;
4770 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004771 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004772 break;
4773 }
4774
chaviwb4c6e582019-08-16 14:35:07 -07004775 sp<BufferQueueLayer> layer;
chaviwb4c6e582019-08-16 14:35:07 -07004776 args.textureName = getNewTexture();
4777 {
4778 // Grab the SF state lock during this since it's the only safe way to access
4779 // RenderEngine when creating a BufferLayerConsumer
4780 // TODO: Check if this lock is still needed here
4781 Mutex::Autolock lock(mStateLock);
4782 layer = getFactory().createBufferQueueLayer(args);
4783 }
4784
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004785 status_t err = layer->setDefaultBufferProperties(0, 0, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004786 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004787 *handle = layer->getHandle();
4788 *gbp = layer->getProducer();
4789 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004790 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004791
Marissa Wallfd668622018-05-10 10:21:13 -07004792 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004793 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004794}
4795
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004796status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004797 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004798 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004799 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004800 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004801 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004802}
4803
Vishnu Nair84125ac2021-12-02 08:47:48 -08004804status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004805 sp<Layer>* outLayer) {
4806 *outLayer = getFactory().createEffectLayer(args);
4807 *handle = (*outLayer)->getHandle();
4808 return NO_ERROR;
4809}
4810
Vishnu Nair84125ac2021-12-02 08:47:48 -08004811status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004812 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004813 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004814 *handle = (*outLayer)->getHandle();
4815 return NO_ERROR;
4816}
4817
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004818void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004819 mLayersPendingRemoval.add(layer);
4820 mLayersRemoved = true;
4821 setTransactionFlags(eTransactionNeeded);
4822}
4823
Vishnu Nairf9096652021-07-20 18:49:42 -07004824void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004825 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004826 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004827 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004828 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004829 if (mTransactionTracing) {
4830 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004831 }
Rob Carr4bba3702018-10-08 21:53:30 +00004832}
4833
Mathias Agopianb60314a2012-04-10 22:09:54 -07004834// ---------------------------------------------------------------------------
4835
Andy McFadden13a082e2012-08-24 10:16:42 -07004836void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004837 const auto display = getDefaultDisplayDeviceLocked();
4838 if (!display) return;
4839
4840 const sp<IBinder> token = display->getDisplayToken().promote();
4841 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004842
Jesse Hall01e29052013-02-19 16:13:35 -08004843 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004844 Vector<ComposerState> state;
4845 Vector<DisplayState> displays;
4846 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004847 d.what = DisplayState::eDisplayProjectionChanged |
4848 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004849 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004850 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004851 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004852 d.orientedDisplaySpaceRect.makeInvalid();
4853 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004854 d.width = 0;
4855 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004856 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004857
Vishnu Nair9a69a042021-06-18 13:19:49 -07004858 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004859
4860 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004861 // It should be on the main thread, apply it directly.
4862 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004863 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004864 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004865
Peiyong Lin65248e02020-04-18 21:15:07 -07004866 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004867 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004868 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004869 mActiveDisplayTransformHint = display->getTransformHint();
Brian Andersond0010582017-03-07 13:20:31 -08004870 // Use phase of 0 since phase is not known.
4871 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004872 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004873 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004874}
4875
4876void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004877 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004878 static_cast<void>(
4879 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004880}
4881
Peiyong Lin65248e02020-04-18 21:15:07 -07004882void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004883 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004884 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004885 return;
4886 }
4887
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004888 const auto displayId = display->getPhysicalId();
4889 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004890
Peiyong Lin65248e02020-04-18 21:15:07 -07004891 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004892 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004893 return;
4894 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004895
Ady Abraham4f960d12021-10-13 16:59:49 -07004896 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4897 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4898 activeDisplay->isPoweredOn()) {
4899 ALOGW("Trying to change power mode on non active display while the active display is ON");
4900 }
4901
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004902 display->setPowerMode(mode);
4903
Lloyd Pique4dccc412018-01-22 17:21:36 -08004904 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004905 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004906 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004907 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004908 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004909 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004910 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004911 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004912 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004913 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4914 // We can merge the syscall later.
4915 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4916 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4917 }
Martin Liu4a322352020-03-24 21:30:38 +08004918 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4919 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4920 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004921 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004922 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004923 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004924 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004925 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004926 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004927
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004928 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004929 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004930 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004931 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004932 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004933 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4934 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004935 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004936 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4937 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4938 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004939 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004940 mScheduler->disableHardwareVsync(true);
4941 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004942 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004943
Ady Abraham27c70212019-06-11 10:52:26 -07004944 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004945 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004946
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004947 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004948 mVisibleRegionsDirty = true;
4949 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004950 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004951 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004952 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004953 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004954 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004955 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004956 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004957 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004958 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004959 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004960 mScheduler->disableHardwareVsync(true);
4961 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004962 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004963 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004964 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004965 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004966 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004967 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004968
Ady Abrahamadc914c2021-10-13 17:04:27 -07004969 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004970 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004971 mRefreshRateStats->setPowerMode(mode);
Rachel Lee6a9731d2022-06-06 17:08:14 -07004972 mScheduler->setDisplayPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004973 }
4974
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004975 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004976}
4977
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004978void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004979 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004980 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004981 if (!display) {
4982 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4983 displayToken.get());
4984 } else if (display->isVirtual()) {
4985 ALOGW("Attempt to set power mode %d for virtual display", mode);
4986 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004987 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004988 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004989 });
4990
4991 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004992}
4993
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004994status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004995 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004996
Mathias Agopianbd115332013-04-18 16:41:04 -07004997 IPCThreadState* ipc = IPCThreadState::self();
4998 const int pid = ipc->getCallingPid();
4999 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07005000
Mathias Agopianbd115332013-04-18 16:41:04 -07005001 if ((uid != AID_SHELL) &&
5002 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005003 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
5004 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005005 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08005006 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005007 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005008 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005009 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
Ady Abraham8cb21882020-08-26 18:22:05 -07005010 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005011 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005012 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
5013 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
5014 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08005015 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005016 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
5017 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005018 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005019 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005020 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08005021 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005022
Dominik Laskowskic2867142019-01-21 11:33:38 -08005023 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005024
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005025 bool dumpLayers = true;
5026 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005027 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005028 if (!lock.locked()) {
5029 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
5030 strerror(-lock.status), lock.status);
5031 }
5032
5033 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
5034 (it->second)(args, asProto, result);
5035 dumpLayers = false;
5036 } else if (!asProto) {
5037 dumpAllLocked(args, result);
5038 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08005039 }
5040
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005041 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005042 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05005043 LayersTraceProto* layersTrace = traceFileProto.add_entry();
5044 LayersProto layersProto = dumpProtoFromMainThread();
5045 layersTrace->mutable_layers()->Swap(&layersProto);
5046 dumpDisplayProto(*layersTrace);
5047
Dominik Laskowski46470112019-08-02 13:13:11 -07005048 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05005049 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07005050 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07005051 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05005052 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07005053 result.append(LayerProtoParser::layerTreeToString(layerTree));
5054 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07005055 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07005056 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07005057 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005058 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005059 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005060 return NO_ERROR;
5061}
5062
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005063status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08005064 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07005065 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08005066 if (mTransactionTracing) {
5067 mTransactionTracing->writeToFile();
5068 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08005069 }
5070
5071 return doDump(fd, DumpArgs(), asProto);
5072}
5073
Dominik Laskowskic2867142019-01-21 11:33:38 -08005074void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005075 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005076 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005077}
5078
Dominik Laskowskic2867142019-01-21 11:33:38 -08005079void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07005080 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005081
Dominik Laskowskic2867142019-01-21 11:33:38 -08005082 if (args.size() > 1) {
5083 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08005084 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005085 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005086 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005087 }
Robert Carr2047fae2016-11-28 14:09:09 -08005088 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005089 } else {
5090 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005091 }
5092}
5093
Dominik Laskowskic2867142019-01-21 11:33:38 -08005094void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005095 const bool clearAll = args.size() < 2;
5096 const auto name = clearAll ? String8() : String8(args[1]);
5097
Edgar Arriaga844fa672020-01-16 14:21:42 -08005098 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005099 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005100 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005101 }
Robert Carr2047fae2016-11-28 14:09:09 -08005102 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005103
Svetoslavd85084b2014-03-20 10:28:31 -07005104 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005105}
5106
Dominik Laskowskic2867142019-01-21 11:33:38 -08005107void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5108 mTimeStats->parseArgs(asProto, args, result);
5109}
5110
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005111void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5112 mFrameTimeline->parseArgs(args, result);
5113}
5114
Jamie Gennis6547ff42013-07-16 20:12:42 -07005115void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005116 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005117 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005118 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005119
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005120 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005121}
5122
Yiwei Zhang5434a782018-12-05 18:06:32 -08005123void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005124 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005125
Yiwei Zhang5434a782018-12-05 18:06:32 -08005126 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5127 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005128 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5129 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005130 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5131 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5132 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005133 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005134}
5135
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005136void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005137 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005138
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005139 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005140 result.append("\n");
5141
Ady Abraham8287e852020-08-12 14:44:58 -07005142 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005143 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005144 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005145 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005146
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005147 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5148 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005149
Ana Krulecc2870422019-01-29 19:00:58 -08005150 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005151 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005152 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5153 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005154}
5155
Dan Stoza269dc4d2021-01-15 15:07:43 -08005156void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5157 for (const auto& [token, display] : mDisplays) {
5158 const auto compositionDisplay = display->getCompositionDisplay();
5159 compositionDisplay->dumpPlannerInfo(args, result);
5160 }
5161}
5162
Yiwei Zhang5434a782018-12-05 18:06:32 -08005163void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5164 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005165 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5166 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005167 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005168 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005169 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005170 }
David Sodman4a36e932017-11-07 14:29:47 -08005171 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005172 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005173 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005174 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5175 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005176}
5177
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005178void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5179 for (const auto& [token, display] : mDisplays) {
5180 display->getCompositionDisplay()->dump(result);
5181 result += '\n';
5182 }
5183}
5184
5185void SurfaceFlinger::dumpDisplays(std::string& result) const {
5186 for (const auto& [token, display] : mDisplays) {
5187 display->dump(result);
5188 result += '\n';
5189 }
5190}
5191
Yiwei Zhang5434a782018-12-05 18:06:32 -08005192void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005193 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005194 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005195 if (!displayId) {
5196 continue;
5197 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005198 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005199 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005200 continue;
5201 }
5202
Yiwei Zhang5434a782018-12-05 18:06:32 -08005203 StringAppendF(&result,
5204 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5205 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005206 uint8_t port;
5207 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005208 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005209 result.append("no identification data\n");
5210 continue;
5211 }
5212
5213 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005214 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005215 continue;
5216 }
5217
5218 const auto edid = parseEdid(data);
5219 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005220 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005221 continue;
5222 }
5223
Yiwei Zhang5434a782018-12-05 18:06:32 -08005224 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005225 result.append(edid->displayName.data(), edid->displayName.length());
5226 result.append("\"\n");
5227 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005228}
5229
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005230void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5231 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005232 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005233 uint8_t port;
5234 DisplayIdentificationData data;
5235
5236 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5237 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5238 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5239 }
5240}
5241
Yiwei Zhang5434a782018-12-05 18:06:32 -08005242void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005243 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005244 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5245 StringAppendF(&result, "DisplayColorSetting: %s\n",
5246 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005247
5248 // TODO: print out if wide-color mode is active or not
5249
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005250 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005251 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005252 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005253 continue;
5254 }
5255
Yiwei Zhang5434a782018-12-05 18:06:32 -08005256 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005257 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005258 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005259 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005260 }
5261
Lloyd Pique32cbe282018-10-19 13:09:22 -07005262 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005263 StringAppendF(&result, " Current color mode: %s (%d)\n",
5264 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005265 }
5266 result.append("\n");
5267}
5268
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005269LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005270 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005271 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005272 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005273 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005274
chaviw1d044282017-09-27 12:19:28 -07005275 return layersProto;
5276}
5277
chaviw0a398992021-08-13 10:13:01 -05005278void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005279 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005280 DisplayProto* displayProto = layersTraceProto.add_displays();
5281 displayProto->set_id(display->getId().value);
5282 displayProto->set_name(display->getDisplayName());
5283 displayProto->set_layer_stack(display->getLayerStack().id);
5284 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5285 [&]() { return displayProto->mutable_size(); });
5286 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5287 return displayProto->mutable_layer_stack_space_rect();
5288 });
5289 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5290 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005291 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005292 }
5293}
5294
Alec Mouri6b9e9912020-01-21 10:50:24 -08005295void SurfaceFlinger::dumpHwc(std::string& result) const {
5296 getHwComposer().dump(result);
5297}
5298
Vishnu Nair0f085c62019-08-30 08:49:12 -07005299void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5300 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5301 // it.
5302 LayerProto* rootProto = layersProto.add_layers();
5303 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5304 rootProto->set_id(offscreenRootLayerId);
5305 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005306 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005307
5308 for (Layer* offscreenLayer : mOffscreenLayers) {
5309 // Add layer as child of the fake root
5310 rootProto->add_children(offscreenLayer->sequence);
5311
5312 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005313 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005314 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005315 }
5316}
5317
Vishnu Nair8406fd72019-07-30 11:29:31 -07005318LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005319 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005320}
5321
Vishnu Nair0f085c62019-08-30 08:49:12 -07005322void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005323 auto future = mScheduler->schedule([this] {
5324 std::string result;
5325 for (Layer* offscreenLayer : mOffscreenLayers) {
5326 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5327 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5328 }
5329 return result;
5330 });
5331
Vishnu Nair0f085c62019-08-30 08:49:12 -07005332 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005333 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005334}
5335
Dominik Laskowskic2867142019-01-21 11:33:38 -08005336void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5337 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005338 Colorizer colorizer(colorize);
5339
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005340 // figure out if we're stuck somewhere
5341 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005342 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005343 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5344
5345 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005346 * Dump library configuration.
5347 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005348
5349 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005350 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005351 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005352 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005353 result.append("\n");
5354
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005355 result.append("\nDisplay identification data:\n");
5356 dumpDisplayIdentificationData(result);
5357
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005358 result.append("\nWide-Color information:\n");
5359 dumpWideColorInfo(result);
5360
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005361 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005362 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005363 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005364 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005365 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005366
Andy McFadden41d67d72014-04-25 16:58:34 -07005367 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005368 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005369 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005370 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005371 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005372
Dan Stozab90cf072015-03-05 11:05:59 -08005373 dumpStaticScreenStats(result);
5374 result.append("\n");
5375
Alec Mouri40189b02019-03-05 15:07:54 -08005376 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5377 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5378 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005379
Andy McFadden4803b742012-09-24 19:07:20 -07005380 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005381 * Dump the visible layer list
5382 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005383 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005384 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005385 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005386
Chia-I Wu2f884132018-09-13 15:17:58 -07005387 {
Lloyd Pique207def92019-02-28 16:09:52 -08005388 StringAppendF(&result, "Composition layers\n");
5389 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005390 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005391 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005392
5393 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5394 layer->getDebugName() ? layer->getDebugName()
5395 : "<unknown>");
5396 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005397 });
5398 }
5399
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005400 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005401 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005402 colorizer.reset(result);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07005403 dumpDisplays(result);
5404 dumpCompositionDisplays(result);
5405 result.push_back('\n');
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005406
5407 mCompositionEngine->dump(result);
5408
5409 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005410 * Dump SurfaceFlinger global state
5411 */
5412
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005413 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005414 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005415 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005416
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005417 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005418
Robert Carrbeba6f02021-02-10 21:06:27 -08005419 result.append("ClientCache state:\n");
5420 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005421 DebugEGLImageTracker::getInstance()->dump(result);
5422
Dominik Laskowski075d3172018-05-24 15:50:06 -07005423 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005424 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5425 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005426 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5427 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005428 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005429 StringAppendF(&result,
5430 " transaction-flags : %08x\n"
5431 " gpu_to_cpu_unsupported : %d\n",
5432 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005433
Marin Shalamanov045b7002021-01-07 16:56:24 +01005434 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005435 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005436 if (const auto activeMode = display->getActiveMode()) {
5437 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005438
5439 const auto dpi = activeMode->getDpi();
5440 xDpi = base::StringPrintf("%.2f", dpi.x);
5441 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005442 } else {
5443 fps = "unknown";
5444 xDpi = "unknown";
5445 yDpi = "unknown";
5446 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005447 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005448 " refresh-rate : %s\n"
5449 " x-dpi : %s\n"
5450 " y-dpi : %s\n",
5451 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005452 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005453
Yiwei Zhang5434a782018-12-05 18:06:32 -08005454 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005455
Dan Stozae22aec72016-08-01 13:20:59 -07005456 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005457 * Tracing state
5458 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005459 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005460
5461 result.append("\nTransaction tracing: ");
5462 if (mTransactionTracing) {
5463 result.append("enabled\n");
5464 mTransactionTracing->dump(result);
5465 } else {
5466 result.append("disabled\n");
5467 }
5468 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005469
5470 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005471 * HWC layer minidump
5472 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005473 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005474 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005475 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005476 continue;
5477 }
5478
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005479 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5480 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005481 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005482
5483 const DisplayDevice& ref = *display;
5484 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005485 result.append("\n");
5486 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005487
Ady Abraham2790e9f2021-04-28 13:14:20 -07005488 {
5489 DumpArgs plannerArgs;
5490 plannerArgs.add(); // first argument is ignored
5491 plannerArgs.add(String16("--layers"));
5492 dumpPlannerInfo(plannerArgs, result);
5493 }
5494
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005495 /*
5496 * Dump HWComposer state
5497 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005498 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005499 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005500 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005501 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005502 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005503 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005504
5505 /*
5506 * Dump gralloc state
5507 */
5508 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5509 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005510
rnleea2ecd832021-07-29 13:58:30 -07005511 /*
5512 * Dump flag/property manager state
5513 */
Robert Carr9b623c32022-03-21 15:55:22 -07005514 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005515
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005516 result.append(mTimeStats->miniDump());
5517 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005518}
5519
chaviw17ac24b2021-01-28 18:50:05 -08005520mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5521 if (saturation == 1) {
5522 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005523 }
5524
chaviw17ac24b2021-01-28 18:50:05 -08005525 float3 luminance{0.213f, 0.715f, 0.072f};
5526 luminance *= 1.0f - saturation;
5527 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5528 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5529 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5530 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5531 return saturationMatrix;
5532}
5533
5534void SurfaceFlinger::updateColorMatrixLocked() {
5535 mat4 colorMatrix =
5536 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5537
Chia-I Wu28f320b2018-05-03 11:02:56 -07005538 if (mCurrentState.colorMatrix != colorMatrix) {
5539 mCurrentState.colorMatrix = colorMatrix;
5540 mCurrentState.colorMatrixChanged = true;
5541 setTransactionFlags(eTransactionNeeded);
5542 }
5543}
5544
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005545status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005546#pragma clang diagnostic push
5547#pragma clang diagnostic error "-Wswitch-enum"
5548 switch (static_cast<ISurfaceComposerTag>(code)) {
5549 // These methods should at minimum make sure that the client requested
5550 // access to SF.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005551 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005552 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005553 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005554 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005555 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5556 // permission dynamically. Don't use the permission cache for this check.
5557 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005558 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005559 IPCThreadState* ipc = IPCThreadState::self();
5560 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5561 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005562 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005563 }
Robert Carr1db73f62016-12-21 12:58:51 -08005564 return OK;
5565 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005566 // The following calls are currently used by clients that do not
5567 // request necessary permissions. However, they do not expose any secret
5568 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005569 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005570 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005571 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005572 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005573 // Calling setTransactionState is safe, because you need to have been
5574 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005575 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005576 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005577 return OK;
5578 }
Huihong Luo1b0c49f2022-03-15 19:18:21 -07005579 case BOOT_FINISHED:
5580 // Used by apps to hook Choreographer to SurfaceFlinger.
5581 case CREATE_DISPLAY_EVENT_CONNECTION:
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005582 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005583 case CREATE_DISPLAY:
5584 case DESTROY_DISPLAY:
5585 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5586 case GET_PHYSICAL_DISPLAY_IDS:
5587 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005588 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005589 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005590 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005591 case GET_DISPLAY_STATE:
5592 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005593 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005594 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005595 case GET_DISPLAY_NATIVE_PRIMARIES:
5596 case SET_ACTIVE_COLOR_MODE:
5597 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005598 case CLEAR_BOOT_DISPLAY_MODE:
5599 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5600 case SET_AUTO_LOW_LATENCY_MODE:
5601 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005602 case CAPTURE_LAYERS:
5603 case CAPTURE_DISPLAY:
5604 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005605 case CLEAR_ANIMATION_FRAME_STATS:
5606 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005607 case OVERRIDE_HDR_TYPES:
5608 case ON_PULL_ATOM:
5609 case ENABLE_VSYNC_INJECTIONS:
5610 case INJECT_VSYNC:
5611 case GET_LAYER_DEBUG_INFO:
5612 case GET_COLOR_MANAGEMENT:
5613 case GET_COMPOSITION_PREFERENCE:
5614 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5615 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005616 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005617 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005618 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005619 case ADD_REGION_SAMPLING_LISTENER:
5620 case REMOVE_REGION_SAMPLING_LISTENER:
5621 case ADD_FPS_LISTENER:
5622 case REMOVE_FPS_LISTENER:
5623 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5624 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5625 case ADD_WINDOW_INFOS_LISTENER:
5626 case REMOVE_WINDOW_INFOS_LISTENER:
5627 case SET_DESIRED_DISPLAY_MODE_SPECS:
5628 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005629 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5630 case SET_DISPLAY_BRIGHTNESS:
5631 case ADD_HDR_LAYER_INFO_LISTENER:
5632 case REMOVE_HDR_LAYER_INFO_LISTENER:
5633 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005634 case SET_GLOBAL_SHADOW_SETTINGS:
5635 case GET_DISPLAY_DECORATION_SUPPORT:
5636 case SET_FRAME_RATE:
5637 case SET_OVERRIDE_FRAME_RATE:
5638 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005639 case ADD_TRANSACTION_TRACE_LISTENER:
5640 case GET_GPU_CONTEXT_PRIORITY:
5641 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005642 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005643 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005644 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005645
5646 // These codes are used for the IBinder protocol to either interrogate the recipient
5647 // side of the transaction for its canonical interface descriptor or to dump its state.
5648 // We let them pass by default.
5649 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5650 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5651 code == IBinder::SYSPROPS_TRANSACTION) {
5652 return OK;
5653 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005654 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005655 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005656 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005657 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5658 return OK;
5659 }
5660 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5661 return PERMISSION_DENIED;
5662#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005663}
5664
Ana Krulec13be8ad2018-08-21 02:43:56 +00005665status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5666 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005667 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5668 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005669 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005670
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005671 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5672 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005673 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005674 IPCThreadState* ipc = IPCThreadState::self();
5675 const int uid = ipc->getCallingUid();
5676 if (CC_UNLIKELY(uid != AID_SYSTEM
5677 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005678 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005679 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005680 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005681 return PERMISSION_DENIED;
5682 }
5683 int n;
5684 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005685 case 1000: // Unused.
5686 case 1001:
5687 return NAME_NOT_FOUND;
5688 case 1002: // Toggle flashing on surface damage.
5689 if (const int delay = data.readInt32(); delay > 0) {
5690 mDebugFlashDelay = delay;
5691 } else {
5692 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5693 }
5694 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005695 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005696 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005697 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005698 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005699 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005700 case 1005: { // Force commit ahead of next VSYNC.
5701 Mutex::Autolock lock(mStateLock);
5702 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5703 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005704 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005705 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005706 case 1007: // Unused.
5707 return NAME_NOT_FOUND;
5708 case 1008: // Toggle forced GPU composition.
5709 mDebugDisableHWC = data.readInt32() != 0;
5710 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005711 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005712 case 1009: // Toggle use of transform hint.
5713 mDebugDisableTransformHint = data.readInt32() != 0;
5714 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005715 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005716 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005717 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005718 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005719 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005720 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005721 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005722 return NO_ERROR;
5723 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005724 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005725 if (!display) {
5726 return NAME_NOT_FOUND;
5727 }
5728
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005729 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005730 return NO_ERROR;
5731 }
5732 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005733 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005734 // daltonize
5735 n = data.readInt32();
5736 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005737 case 1:
5738 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5739 break;
5740 case 2:
5741 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5742 break;
5743 case 3:
5744 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5745 break;
5746 default:
5747 mDaltonizer.setType(ColorBlindnessType::None);
5748 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005749 }
5750 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005751 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005752 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005753 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005754 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005755
5756 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005757 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005758 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005759 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005760 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005761 // apply a color matrix
5762 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005763 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005764 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005765 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005766 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005767 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005768 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005769 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005770 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005771 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005772 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005773
5774 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5775 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005776 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005777 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5778 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5779 }
5780
Chia-I Wu28f320b2018-05-03 11:02:56 -07005781 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005782 return NO_ERROR;
5783 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005784 case 1016: { // Unused.
5785 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005786 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005787 case 1017: {
5788 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005789 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005790 return NO_ERROR;
5791 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005792 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005793 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005794 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005795 return NO_ERROR;
5796 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005797 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005798 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005799 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005800 return NO_ERROR;
5801 }
Irvel468051e2016-06-13 16:44:44 -07005802 case 1020: { // Layer updates interceptor
5803 n = data.readInt32();
5804 if (n) {
5805 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005806 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005807 }
5808 else{
5809 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005810 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005811 }
5812 return NO_ERROR;
5813 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005814 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005815 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005816 static_cast<void>(
5817 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005818 return NO_ERROR;
5819 }
Romain Guy0147a172017-06-01 13:53:56 -07005820 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005821 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005822 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005823
Chia-I Wu28f320b2018-05-03 11:02:56 -07005824 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005825 return NO_ERROR;
5826 }
Romain Guy54f154a2017-10-24 21:40:32 +01005827 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005828 int32_t colorMode;
5829
Chia-I Wu0d711262018-05-21 15:19:35 -07005830 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005831 if (data.readInt32(&colorMode) == NO_ERROR) {
5832 mForceColorMode = static_cast<ColorMode>(colorMode);
5833 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005834 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005835 return NO_ERROR;
5836 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005837 // Deprecate, use 1030 to check whether the device is color managed.
5838 case 1024: {
5839 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005840 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005841 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005842 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005843 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005844 if (n == 1) {
5845 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005846 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005847 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005848 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005849 int64_t startingTime =
5850 (fixedStartingTime) ? fixedStartingTime : systemTime();
5851 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005852 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005853 mLayerTracing.notify("start", startingTime);
5854 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005855 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005856 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005857 } else if (n == 2) {
5858 std::string filename = std::string(data.readCString());
5859 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5860 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005861 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005862 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005863 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005864 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005865 mTracingEnabledChanged = tracingEnabledChanged;
5866 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005867 return NO_ERROR;
5868 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005869 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005870 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005871 return NO_ERROR;
5872 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005873 // Is a DisplayColorSetting supported?
5874 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005875 const auto display = getDefaultDisplayDevice();
5876 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005877 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005878 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005879
5880 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5881 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005882 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005883 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005884 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005885 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005886 reply->writeBool(true);
5887 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005888 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005889 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005890 break;
5891 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005892 reply->writeBool(
5893 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005894 break;
5895 }
5896 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005897 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005898 case 1028: { // Unused.
5899 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005900 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005901 // Set buffer size for SF tracing (value in KB)
5902 case 1029: {
5903 n = data.readInt32();
5904 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5905 ALOGW("Invalid buffer size: %d KB", n);
5906 reply->writeInt32(BAD_VALUE);
5907 return BAD_VALUE;
5908 }
5909
5910 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005911 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005912 reply->writeInt32(NO_ERROR);
5913 return NO_ERROR;
5914 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005915 // Is device color managed?
5916 case 1030: {
5917 reply->writeBool(useColorManagement);
5918 return NO_ERROR;
5919 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005920 // Override default composition data space
5921 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5922 // && adb shell stop zygote && adb shell start zygote
5923 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5924 // adb shell stop zygote && adb shell start zygote
5925 case 1031: {
5926 Mutex::Autolock _l(mStateLock);
5927 n = data.readInt32();
5928 if (n) {
5929 n = data.readInt32();
5930 if (n) {
5931 Dataspace dataspace = static_cast<Dataspace>(n);
5932 if (!validateCompositionDataspace(dataspace)) {
5933 return BAD_VALUE;
5934 }
5935 mDefaultCompositionDataspace = dataspace;
5936 }
5937 n = data.readInt32();
5938 if (n) {
5939 Dataspace dataspace = static_cast<Dataspace>(n);
5940 if (!validateCompositionDataspace(dataspace)) {
5941 return BAD_VALUE;
5942 }
5943 mWideColorGamutCompositionDataspace = dataspace;
5944 }
5945 } else {
5946 // restore composition data space.
5947 mDefaultCompositionDataspace = defaultCompositionDataspace;
5948 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5949 }
5950 return NO_ERROR;
5951 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005952 // Set trace flags
5953 case 1033: {
5954 n = data.readUint32();
5955 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005956 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005957 reply->writeInt32(NO_ERROR);
5958 return NO_ERROR;
5959 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005960 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005961 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005962 switch (n = data.readInt32()) {
5963 case 0:
5964 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005965 FTL_FAKE_GUARD(mStateLock,
5966 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005967 break;
5968 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005969 reply->writeBool(
5970 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005971 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005972 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005973 });
5974
5975 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005976 return NO_ERROR;
5977 }
Ady Abraham34392f72019-04-10 11:29:27 -07005978 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005979 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005980
Dominik Laskowskif1833852021-03-23 15:06:50 -07005981 const auto display = [&]() -> sp<IBinder> {
5982 uint64_t value;
5983 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005984 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005985 }
5986
Dominik Laskowskif1833852021-03-23 15:06:50 -07005987 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5988 return getPhysicalDisplayToken(*id);
5989 }
5990
5991 ALOGE("Invalid physical display ID");
5992 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005993 }();
5994
Shiyong Li2bcece92021-08-30 20:38:50 +00005995 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005996 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005997 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5998 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005999 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006000 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
6001 // manager frame rate policy a new policy which allows switching between all refresh
6002 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07006003 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006004 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07006005 return mScheduler
6006 ->schedule([this] {
6007 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006008 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006009
Dominik Laskowski756b7892021-08-04 12:53:59 -07006010 // This is a little racy, but not in a way that hurts anything. As
6011 // we grab the defaultMode from the display manager policy, we could
6012 // be setting a new display manager policy, leaving us using a stale
6013 // defaultMode. The defaultMode doesn't matter for the override
6014 // policy though, since we set allowGroupSwitching to true, so it's
6015 // not a problem.
6016 scheduler::RefreshRateConfigs::Policy overridePolicy;
6017 overridePolicy.defaultMode = display->refreshRateConfigs()
6018 .getDisplayManagerPolicy()
6019 .defaultMode;
6020 overridePolicy.allowGroupSwitching = true;
6021 constexpr bool kOverridePolicy = true;
6022 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
6023 kOverridePolicy);
6024 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006025 .get();
6026 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07006027 return mScheduler
6028 ->schedule([this] {
6029 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006030 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07006031 constexpr bool kOverridePolicy = true;
6032 return setDesiredDisplayModeSpecsInternal(display, {},
6033 kOverridePolicy);
6034 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01006035 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07006036 }
Ady Abraham07e54702020-04-16 15:05:37 -07006037 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02006038 // Inject a hotplug connected event for the primary display. This will deallocate and
6039 // reallocate the display state including framebuffers.
6040 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07006041 const hal::HWDisplayId hwcId =
6042 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
6043
6044 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02006045 return NO_ERROR;
6046 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07006047 // Modify the max number of display frames stored within FrameTimeline
6048 case 1038: {
6049 n = data.readInt32();
6050 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
6051 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
6052 return BAD_VALUE;
6053 }
6054 if (n == 0) {
6055 // restore to default
6056 mFrameTimeline->reset();
6057 return NO_ERROR;
6058 }
6059 mFrameTimeline->setMaxDisplayFrames(n);
6060 return NO_ERROR;
6061 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07006062 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07006063 PhysicalDisplayId displayId = [&]() {
6064 Mutex::Autolock lock(mStateLock);
6065 return getDefaultDisplayDeviceLocked()->getPhysicalId();
6066 }();
6067
6068 auto inUid = static_cast<uid_t>(data.readInt32());
6069 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08006070 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
6071 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07006072 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08006073 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006074 // Toggle caching feature
6075 // First argument is an int32 - nonzero enables caching and zero disables caching
6076 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6077 // caching to a particular physical display
6078 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006079 auto future = mScheduler->schedule([&] {
6080 n = data.readInt32();
6081 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6082 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6083 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6084 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6085 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6086 return NAME_NOT_FOUND;
6087 }
6088 }
6089 {
6090 Mutex::Autolock lock(mStateLock);
6091 mLayerCachingEnabled = n != 0;
6092 for (const auto& [_, display] : mDisplays) {
6093 if (!inputId || *inputId == display->getPhysicalId()) {
6094 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006095 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006096 }
6097 }
6098 return OK;
6099 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006100
Dominik Laskowski756b7892021-08-04 12:53:59 -07006101 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006102 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006103 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006104 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006105 return NO_ERROR;
6106 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006107 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006108 if (mTransactionTracing) {
6109 if (data.readInt32()) {
6110 // Transaction tracing is always running but allow the user to temporarily
6111 // increase the buffer when actively debugging.
6112 mTransactionTracing->setBufferSize(
6113 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6114 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006115 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006116 mTransactionTracing->setBufferSize(
6117 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006118 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006119 }
6120 reply->writeInt32(NO_ERROR);
6121 return NO_ERROR;
6122 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006123 case 1042: { // Write layers trace or transaction trace to file
6124 if (mTransactionTracing) {
6125 mTransactionTracing->writeToFile();
6126 }
6127 if (mLayerTracingEnabled) {
6128 mLayerTracing.writeToFile();
6129 }
6130 reply->writeInt32(NO_ERROR);
6131 return NO_ERROR;
6132 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006133 }
6134 }
6135 return err;
6136}
6137
Ady Abrahama09852a2020-02-20 14:23:42 -08006138void SurfaceFlinger::kernelTimerChanged(bool expired) {
6139 static bool updateOverlay =
6140 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006141 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006142
6143 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006144 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006145 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006146 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006147 if (!display) {
6148 ALOGW("%s: default display is null", __func__);
6149 return;
6150 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006151 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006152
6153 const auto desiredActiveMode = display->getDesiredActiveMode();
6154 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6155 ? std::make_optional(desiredActiveMode->mode->getId())
6156 : std::nullopt;
6157
6158 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6159
Ady Abraham1b11bc62021-06-03 19:51:19 -07006160 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006161 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006162 }
6163 }));
6164}
6165
ramindani32cf0602022-03-02 02:30:29 +00006166std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6167SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6168 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6169 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6170 const auto timeout = getIdleTimerTimeout(displayId);
6171 if (isKernelIdleTimerHwcSupported) {
6172 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6173 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6174 // In order to decide if we can use the HWC api for idle timer
6175 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6176 // without relying on hasDisplayCapability.
6177 // hasDisplayCapability relies on DisplayCapabilities
6178 // which are updated after we set the PowerMode::ON.
6179 // DISPLAY_IDLE_TIMER is a display driver property
6180 // and is available before the PowerMode::ON
6181 return {KernelIdleTimerController::HwcApi, timeout};
6182 }
6183 return {std::nullopt, timeout};
6184 }
6185 if (getKernelIdleTimerSyspropConfig(displayId)) {
6186 return {KernelIdleTimerController::Sysprop, timeout};
6187 }
6188
6189 return {std::nullopt, timeout};
6190}
6191
6192void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6193 KernelIdleTimerController controller,
6194 PhysicalDisplayId displayId) {
6195 switch (controller) {
6196 case KernelIdleTimerController::HwcApi: {
6197 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6198 break;
6199 }
6200 case KernelIdleTimerController::Sysprop: {
6201 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6202 break;
6203 }
6204 }
6205}
6206
Ana Krulecb9afd792020-06-11 13:16:15 -07006207void SurfaceFlinger::toggleKernelIdleTimer() {
6208 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6209
Ady Abraham3efa3942021-06-24 19:01:25 -07006210 const auto display = getDefaultDisplayDeviceLocked();
6211 if (!display) {
6212 ALOGW("%s: default display is null", __func__);
6213 return;
6214 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006215
Ady Abrahame9316b72021-09-24 17:04:36 -07006216 // If the support for kernel idle timer is disabled for the active display,
6217 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006218 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6219 display->refreshRateConfigs().kernelIdleTimerController();
6220 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006221 return;
6222 }
6223
Ady Abraham3efa3942021-06-24 19:01:25 -07006224 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006225
Ana Krulecb9afd792020-06-11 13:16:15 -07006226 switch (action) {
6227 case KernelIdleTimerAction::TurnOff:
6228 if (mKernelIdleTimerEnabled) {
6229 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006230 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6231 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6232 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006233 mKernelIdleTimerEnabled = false;
6234 }
6235 break;
6236 case KernelIdleTimerAction::TurnOn:
6237 if (!mKernelIdleTimerEnabled) {
6238 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006239 const std::chrono::milliseconds timeout =
6240 display->refreshRateConfigs().getIdleTimerTimeout();
6241 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6242 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006243 mKernelIdleTimerEnabled = true;
6244 }
6245 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006246 }
6247}
6248
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006249// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6250class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006251public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006252 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6253 ~WindowDisconnector() {
6254 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006255 }
6256
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006257private:
6258 ANativeWindow* mWindow;
6259 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006260};
6261
chaviw93df2ea2019-04-30 16:45:12 -07006262static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6263 switch (colorMode) {
6264 case ColorMode::DISPLAY_P3:
6265 case ColorMode::BT2100_PQ:
6266 case ColorMode::BT2100_HLG:
6267 case ColorMode::DISPLAY_BT2020:
6268 return Dataspace::DISPLAY_P3;
6269 default:
6270 return Dataspace::V0_SRGB;
6271 }
6272}
6273
chaviwf5bb97b2021-04-28 15:35:37 -05006274static bool hasCaptureBlackoutContentPermission() {
6275 IPCThreadState* ipc = IPCThreadState::self();
6276 const int pid = ipc->getCallingPid();
6277 const int uid = ipc->getCallingUid();
6278 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6279 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6280}
6281
chaviw4b9d5e12020-08-04 18:30:35 -07006282static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6283 IPCThreadState* ipc = IPCThreadState::self();
6284 const int pid = ipc->getCallingPid();
6285 const int uid = ipc->getCallingUid();
6286 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6287 return OK;
6288 }
6289
6290 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6291 // itself, we allow it to continue.
6292 if (captureArgs.uid == uid) {
6293 return OK;
6294 }
6295
6296 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6297 return PERMISSION_DENIED;
6298}
6299
Peiyong Lin05cc0112020-10-14 16:16:37 -07006300status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6301 static constexpr int kFifoPriority = 2;
6302 static constexpr int kOtherPriority = 0;
6303
6304 struct sched_param param = {0};
6305 int sched_policy;
6306 if (enabled) {
6307 sched_policy = SCHED_FIFO;
6308 param.sched_priority = kFifoPriority;
6309 } else {
6310 sched_policy = SCHED_OTHER;
6311 param.sched_priority = kOtherPriority;
6312 }
6313
6314 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6315 return -errno;
6316 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006317
6318 return NO_ERROR;
6319}
6320
6321status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6322 static const unsigned int kUclampMin =
6323 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6324
6325 if (!kUclampMin) {
6326 // uclamp.min set to 0 (default), skip setting
6327 return NO_ERROR;
6328 }
6329
6330 // Currently, there is no wrapper in bionic: b/183240349.
6331 struct sched_attr {
6332 uint32_t size;
6333 uint32_t sched_policy;
6334 uint64_t sched_flags;
6335 int32_t sched_nice;
6336 uint32_t sched_priority;
6337 uint64_t sched_runtime;
6338 uint64_t sched_deadline;
6339 uint64_t sched_period;
6340 uint32_t sched_util_min;
6341 uint32_t sched_util_max;
6342 };
6343
6344 sched_attr attr = {};
6345 attr.size = sizeof(attr);
6346
6347 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6348 attr.sched_util_min = enabled ? kUclampMin : 0;
6349 attr.sched_util_max = 1024;
6350
6351 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6352 return -errno;
6353 }
6354
Peiyong Lin05cc0112020-10-14 16:16:37 -07006355 return NO_ERROR;
6356}
6357
chaviwd2432892020-07-24 17:42:39 -07006358status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006359 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006360 ATRACE_CALL();
6361
chaviw4b9d5e12020-08-04 18:30:35 -07006362 status_t validate = validateScreenshotPermissions(args);
6363 if (validate != OK) {
6364 return validate;
6365 }
6366
chaviwd2432892020-07-24 17:42:39 -07006367 if (!args.displayToken) return BAD_VALUE;
6368
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006369 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006370 ui::LayerStack layerStack;
6371 ui::Size reqSize(args.width, args.height);
6372 ui::Dataspace dataspace;
6373 {
6374 Mutex::Autolock lock(mStateLock);
6375 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6376 if (!display) return NAME_NOT_FOUND;
6377 displayWeak = display;
6378 layerStack = display->getLayerStack();
6379
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006380 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006381 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006382 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006383 }
6384
arthurhung79e81aa2020-08-28 00:09:19 +08006385 // The dataspace is depended on the color mode of display, that could use non-native mode
6386 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6387 // and failed if display is not in native mode. This provide a way to force using native
6388 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006389 dataspace = args.dataspace;
6390 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006391 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6392 dataspace = pickDataspaceFromColorMode(colorMode);
6393 }
chaviwd2432892020-07-24 17:42:39 -07006394 }
6395
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006396 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006397 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006398 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006399 });
6400
chaviw4b9d5e12020-08-04 18:30:35 -07006401 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6402 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006403 };
chaviw03900772020-08-18 12:34:51 -07006404
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006405 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6406 args.pixelFormat, args.allowProtected, args.grayscale,
6407 captureListener);
6408 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006409}
6410
Dominik Laskowskif1833852021-03-23 15:06:50 -07006411status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006412 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006413 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006414 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006415 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006416 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006417 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006418 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006419
Dominik Laskowskif1833852021-03-23 15:06:50 -07006420 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006421 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006422 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006423 }
6424
chaviw93df2ea2019-04-30 16:45:12 -07006425 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006426 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006427 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006428
chaviw426b5c02020-07-27 11:20:15 -07006429 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006430 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6431 }
6432
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006433 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006434 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006435 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006436 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006437 });
chaviw93df2ea2019-04-30 16:45:12 -07006438
Marin Shalamanov1c434292020-06-12 01:47:29 +02006439 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006440 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006441 };
6442
Sally Qi59a9f502021-10-12 18:53:23 +00006443 if (captureListener == nullptr) {
6444 ALOGE("capture screen must provide a capture listener callback");
6445 return BAD_VALUE;
6446 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006447
6448 constexpr bool kAllowProtected = false;
6449 constexpr bool kGrayscale = false;
6450
6451 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6452 ui::PixelFormat::RGBA_8888, kAllowProtected, kGrayscale,
6453 captureListener);
6454 return fenceStatus(future.get());
chaviw93df2ea2019-04-30 16:45:12 -07006455}
6456
chaviw3efadb12020-07-27 10:07:15 -07006457status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006458 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006459 ATRACE_CALL();
6460
chaviw4b9d5e12020-08-04 18:30:35 -07006461 status_t validate = validateScreenshotPermissions(args);
6462 if (validate != OK) {
6463 return validate;
6464 }
6465
Marin Shalamanov1c434292020-06-12 01:47:29 +02006466 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006467 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006468 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006469 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006470 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006471
6472 // Call this before holding mStateLock to avoid any deadlocking.
6473 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6474
Robert Carrc0df3122019-04-11 13:18:21 -07006475 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006476 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006477
Vishnu Nairf9096652021-07-20 18:49:42 -07006478 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006479 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006480 ALOGE("captureLayers called with an invalid or removed parent");
6481 return NAME_NOT_FOUND;
6482 }
6483
chaviwf5bb97b2021-04-28 15:35:37 -05006484 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006485 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006486 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6487 return PERMISSION_DENIED;
6488 }
6489
Robert Carr6a160312021-05-17 12:08:20 -07006490 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006491 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006492 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006493 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006494 }
6495
chaviw3efadb12020-07-27 10:07:15 -07006496 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006497 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006498 crop.bottom = parentSourceBounds.getHeight();
6499 }
6500
chaviw17ac24b2021-01-28 18:50:05 -08006501 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006502 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6503 // crop was not specified, or an invalid frame scale was provided.
6504 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006505 }
chaviw17ac24b2021-01-28 18:50:05 -08006506 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006507
chaviw3efadb12020-07-27 10:07:15 -07006508 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006509 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006510 if (excludeLayer != nullptr) {
6511 excludeLayers.emplace(excludeLayer);
6512 } else {
6513 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6514 return NAME_NOT_FOUND;
6515 }
6516 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006517
arthurhung79e81aa2020-08-28 00:09:19 +08006518 // The dataspace is depended on the color mode of display, that could use non-native mode
6519 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6520 // and failed if display is not in native mode. This provide a way to force using native
6521 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006522 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006523 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006524
Chia-I Wu20261cb2018-08-23 12:55:44 -07006525 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006526 if (reqSize.width <= 0 || reqSize.height <= 0) {
6527 ALOGW("Failed to captureLayes: crop or scale too small");
6528 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006529 }
6530
chaviw79468ab2021-10-27 11:11:24 -05006531 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006532 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006533 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006534 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006535 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006536 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006537 });
6538
chaviw03900772020-08-18 12:34:51 -07006539 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006540 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6541 if (!layer->isVisible()) {
6542 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006543 } else if (args.childrenOnly && layer == parent.get()) {
6544 return;
6545 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006546 return;
chaviwa76b2712017-09-20 12:02:26 -07006547 }
Robert Carr866455f2019-04-02 16:28:26 -07006548
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006549 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006550 while (p != nullptr) {
6551 if (excludeLayers.count(p) != 0) {
6552 return;
6553 }
6554 p = p->getParent();
6555 }
6556
chaviwa76b2712017-09-20 12:02:26 -07006557 visitor(layer);
6558 });
6559 };
Robert Carr108b2c72019-04-02 16:32:58 -07006560
Sally Qi59a9f502021-10-12 18:53:23 +00006561 if (captureListener == nullptr) {
6562 ALOGE("capture screen must provide a capture listener callback");
6563 return BAD_VALUE;
6564 }
6565
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006566 auto future = captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize,
6567 args.pixelFormat, args.allowProtected, args.grayscale,
6568 captureListener);
6569 return fenceStatus(future.get());
chaviwa76b2712017-09-20 12:02:26 -07006570}
6571
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006572ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Sally Qi59a9f502021-10-12 18:53:23 +00006573 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6574 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6575 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006576 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006577
Garfield Tan9c9c1912021-07-19 12:02:16 -07006578 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6579 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6580 ") that exceeds render target size limit.",
6581 bufferSize.getWidth(), bufferSize.getHeight());
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006582 return ftl::yield<FenceResult>(base::unexpected(BAD_VALUE)).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006583 }
6584
Peiyong Lin05cc0112020-10-14 16:16:37 -07006585 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6586 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6587 // A protected layer has no implication on whether it's secure, which is explicitly set by
6588 // application to avoid being screenshot or drawn via unsecure display.
6589 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6590 bool hasProtectedLayer = false;
6591 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006592 auto future = mScheduler->schedule([=]() {
6593 bool protectedLayerFound = false;
6594 traverseLayers([&](Layer* layer) {
6595 protectedLayerFound =
6596 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6597 });
6598 return protectedLayerFound;
6599 });
6600 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006601 }
6602
Richard Liucbcb8952020-04-08 10:51:55 +00006603 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6604 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006605 (hasProtectedLayer && allowProtected && supportsProtected
6606 ? GRALLOC_USAGE_PROTECTED
6607 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006608 sp<GraphicBuffer> buffer =
6609 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6610 static_cast<android_pixel_format>(reqPixelFormat),
6611 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006612
6613 const status_t bufferStatus = buffer->initCheck();
6614 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6615 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006616 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6617 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6618 renderengine::impl::ExternalTexture::Usage::
6619 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006620 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006621 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006622}
6623
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006624ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006625 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6626 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6627 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006628 ATRACE_CALL();
6629
chaviwf5bb97b2021-04-28 15:35:37 -05006630 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006631
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006632 auto future = mScheduler->schedule([=, renderAreaFuture = std::move(renderAreaFuture)]() mutable
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006633 -> ftl::SharedFuture<FenceResult> {
chaviw03900772020-08-18 12:34:51 -07006634 ScreenCaptureResults captureResults;
6635 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6636 if (!renderArea) {
6637 ALOGW("Skipping screen capture because of invalid render area.");
6638 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006639 captureListener->onScreenCaptureCompleted(captureResults);
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006640 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
chaviw03900772020-08-18 12:34:51 -07006641 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006642
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006643 ftl::SharedFuture<FenceResult> renderFuture;
chaviw03900772020-08-18 12:34:51 -07006644 renderArea->render([&] {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006645 renderFuture =
6646 renderScreenImpl(*renderArea, traverseLayers, buffer, canCaptureBlackoutContent,
6647 regionSampling, grayscale, captureResults);
chaviw03900772020-08-18 12:34:51 -07006648 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006649
6650 if (captureListener) {
6651 // TODO: The future returned by std::async blocks the main thread. Return a chain of
6652 // futures to the Binder thread instead.
Sally Qi59a9f502021-10-12 18:53:23 +00006653 std::async([=]() mutable {
6654 ATRACE_NAME("captureListener is nonnull!");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006655 auto fenceResult = renderFuture.get();
6656 // TODO(b/232535621): Change ScreenCaptureResults to store a FenceResult.
6657 captureResults.result = fenceStatus(fenceResult);
6658 captureResults.fence = std::move(fenceResult).value_or(Fence::NO_FENCE);
Sally Qi59a9f502021-10-12 18:53:23 +00006659 captureListener->onScreenCaptureCompleted(captureResults);
6660 });
6661 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006662 return renderFuture;
Sally Qi59a9f502021-10-12 18:53:23 +00006663 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006664
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006665 if (captureListener) {
6666 return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
Sally Qi59a9f502021-10-12 18:53:23 +00006667 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006668
6669 // Flatten nested futures.
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006670 auto chain = ftl::Future(std::move(future)).then([](ftl::SharedFuture<FenceResult> future) {
6671 return future;
6672 });
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006673
6674 return chain.share();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006675}
6676
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006677ftl::SharedFuture<FenceResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006678 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006679 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6680 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6681 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006682 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006683
chaviw426b5c02020-07-27 11:20:15 -07006684 traverseLayers([&](Layer* layer) {
6685 captureResults.capturedSecureLayers =
6686 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6687 });
6688
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006689 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006690
chaviw426b5c02020-07-27 11:20:15 -07006691 // We allow the system server to take screenshots of secure layers for
6692 // use in situations like the Screen-rotation animation and place
6693 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006694 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006695 ALOGW("FB is protected: PERMISSION_DENIED");
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006696 return ftl::yield<FenceResult>(base::unexpected(PERMISSION_DENIED)).share();
chaviw426b5c02020-07-27 11:20:15 -07006697 }
6698
Alec Mouria90a5702021-04-16 16:36:21 +00006699 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006700 auto dataspace = renderArea.getReqDataSpace();
6701 auto parent = renderArea.getParentLayer();
Alec Mourifcedb9c2022-04-11 20:02:17 +00006702 auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
Sally Qi6c903ca2022-04-25 11:24:20 -07006703 auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
6704 auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
6705
Robert Carr12a3b9b2022-03-10 09:55:29 -08006706 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6707 Mutex::Autolock lock(mStateLock);
6708 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6709 return display.getLayerStack() == layerStack;
6710 });
6711 if (!display) {
6712 // If the layer is not on a display, use the dataspace for the default display.
6713 display = getDefaultDisplayDeviceLocked();
6714 }
6715
6716 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6717 dataspace = pickDataspaceFromColorMode(colorMode);
Alec Mourifcedb9c2022-04-11 20:02:17 +00006718 renderIntent = display->getCompositionDisplay()->getState().renderIntent;
Sally Qi6c903ca2022-04-25 11:24:20 -07006719 sdrWhitePointNits = display->getCompositionDisplay()->getState().sdrWhitePointNits;
6720 displayBrightnessNits = display->getCompositionDisplay()->getState().displayBrightnessNits;
Robert Carr12a3b9b2022-03-10 09:55:29 -08006721 }
6722 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006723
chaviwa76b2712017-09-20 12:02:26 -07006724 const auto reqWidth = renderArea.getReqWidth();
6725 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006726 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006727 const auto transform = renderArea.getTransform();
6728 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006729 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006730
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006731 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006732 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006733
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006734 // assume that bounds are never offset, and that they are the same as the
6735 // buffer bounds.
6736 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006737 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006738 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006739
Robert Carr12a3b9b2022-03-10 09:55:29 -08006740 clientCompositionDisplay.outputDataspace = dataspace;
Sally Qie258f092022-05-19 15:24:12 -07006741 clientCompositionDisplay.currentLuminanceNits = displayBrightnessNits;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006742 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Alec Mourifcedb9c2022-04-11 20:02:17 +00006743 clientCompositionDisplay.renderIntent =
6744 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(renderIntent);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006745
chaviw17ac24b2021-01-28 18:50:05 -08006746 const float colorSaturation = grayscale ? 0 : 1;
6747 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6748
chaviw50da5042018-04-09 13:49:37 -07006749 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006750
Vishnu Nair9b079a22020-01-21 14:36:08 -08006751 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006752 fillLayer.source.buffer.buffer = nullptr;
6753 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006754 fillLayer.geometry.boundaries =
6755 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006756 fillLayer.alpha = half(alpha);
6757 clientCompositionLayers.push_back(fillLayer);
6758
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006759 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006760 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006761 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006762 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006763 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006764
Lloyd Piquef16688f2019-02-19 17:47:57 -08006765 Region clip(renderArea.getBounds());
6766 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6767 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006768 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006769 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006770 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006771 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006772 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006773 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006774 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006775 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006776 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6777 BlurSetting::Disabled
6778 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6779 BlurSetting::Enabled,
Sally Qidb653012022-05-04 13:12:22 -07006780 isHdrLayer(layer) ? displayBrightnessNits : sdrWhitePointNits,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006781
Lloyd Piquef16688f2019-02-19 17:47:57 -08006782 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006783 std::vector<compositionengine::LayerFE::LayerSettings> results =
6784 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006785 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006786 for (auto& settings : results) {
6787 settings.geometry.positionTransform =
6788 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006789 // There's no need to process blurs when we're executing region sampling,
6790 // we're just trying to understand what we're drawing, and doing so without
6791 // blurs is already a pretty good approximation.
6792 if (regionSampling) {
6793 settings.backgroundBlurRadius = 0;
6794 }
Sally Qidb653012022-05-04 13:12:22 -07006795 captureResults.capturedHdrLayers |= isHdrLayer(layer);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006796 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006797
Yichi Chen40773d92020-04-01 10:10:18 +08006798 clientCompositionLayers.insert(clientCompositionLayers.end(),
6799 std::make_move_iterator(results.begin()),
6800 std::make_move_iterator(results.end()));
6801 renderedLayers.push_back(layer);
6802 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006803
chaviwa76b2712017-09-20 12:02:26 -07006804 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006805
Sally Qi59a9f502021-10-12 18:53:23 +00006806 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6807 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006808 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006809 std::back_inserter(clientRenderEngineLayers),
6810 [](compositionengine::LayerFE::LayerSettings& settings)
6811 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006812
Alec Mouri6338c9d2019-02-07 16:57:51 -08006813 // Use an empty fence for the buffer fence, since we just created the buffer so
6814 // there is no need for synchronization with the GPU.
6815 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006816 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006817
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006818 constexpr bool kUseFramebufferCache = false;
Dominik Laskowskib17c6212022-05-09 09:36:19 -07006819 auto chain =
6820 ftl::Future(getRenderEngine().drawLayers(clientCompositionDisplay,
6821 clientRenderEngineLayers, buffer,
6822 kUseFramebufferCache, std::move(bufferFence)))
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006823 .then(&toFenceResult);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006824
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006825 const auto future = chain.share();
Sally Qi59a9f502021-10-12 18:53:23 +00006826 for (auto* layer : renderedLayers) {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006827 layer->onLayerDisplayed(future);
Yichi Chen40773d92020-04-01 10:10:18 +08006828 }
Ady Abraham99599942021-01-27 20:27:23 -08006829
Peiyong Lin05cc0112020-10-14 16:16:37 -07006830 // Always switch back to unprotected context.
6831 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006832
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07006833 return future;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006834}
6835
chaviwbf023a62021-06-07 16:00:06 -05006836void SurfaceFlinger::windowInfosReported() {
chaviw95ef3c42019-02-14 10:55:09 -08006837 Mutex::Autolock _l(mStateLock);
Arthur Hung2274a312021-04-28 15:13:06 +00006838 signalSynchronousTransactions(CountDownLatch::eSyncInputWindows);
chaviw95ef3c42019-02-14 10:55:09 -08006839}
chaviw5f21a5e2019-02-14 10:00:34 -08006840
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006841// ---------------------------------------------------------------------------
6842
Edgar Arriaga844fa672020-01-16 14:21:42 -08006843void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6844 layersSortedByZ.traverse(visitor);
6845}
6846
Dan Stoza412903f2017-04-27 13:42:17 -07006847void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6848 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006849}
6850
Dan Stoza412903f2017-04-27 13:42:17 -07006851void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6852 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006853}
6854
chaviw4b9d5e12020-08-04 18:30:35 -07006855void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006856 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006857 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006858 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006859 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006860 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006861 continue;
6862 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006863 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006864 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006865 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006866 return;
6867 }
chaviwa76b2712017-09-20 12:02:26 -07006868 if (!layer->isVisible()) {
6869 return;
6870 }
chaviw4b9d5e12020-08-04 18:30:35 -07006871 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6872 return;
6873 }
chaviwa76b2712017-09-20 12:02:26 -07006874 visitor(layer);
6875 });
6876 }
6877}
6878
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006879status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006880 const sp<DisplayDevice>& display,
6881 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006882 Mutex::Autolock lock(mStateLock);
6883
Ady Abrahamfb853662021-04-09 11:46:40 -07006884 if (mDebugDisplayModeSetByBackdoor) {
6885 // ignore this request as mode is overridden by backdoor
6886 return NO_ERROR;
6887 }
6888
Ady Abraham3efa3942021-06-24 19:01:25 -07006889 status_t setPolicyResult = overridePolicy
6890 ? display->refreshRateConfigs().setOverridePolicy(policy)
6891 : display->refreshRateConfigs().setDisplayManagerPolicy(*policy);
6892 if (setPolicyResult < 0) {
6893 return BAD_VALUE;
6894 }
6895 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6896 return NO_ERROR;
6897 }
6898
Ady Abraham3efa3942021-06-24 19:01:25 -07006899 scheduler::RefreshRateConfigs::Policy currentPolicy =
6900 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006901
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006902 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006903
Ana Krulecb9afd792020-06-11 13:16:15 -07006904 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6905 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006906 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006907 if (isDisplayActiveLocked(display)) {
6908 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6909 toggleKernelIdleTimer();
6910 } else {
6911 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6912 }
Ady Abraham838de062019-02-04 10:24:03 -08006913
Ady Abraham690f4612021-07-01 23:24:03 -07006914 const DisplayModePtr preferredDisplayMode = [&] {
6915 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6916 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6917 return schedulerMode;
6918 }
6919
6920 return display->getMode(currentPolicy.defaultMode);
6921 }();
6922
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006923 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006924 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006925
Ady Abraham690f4612021-07-01 23:24:03 -07006926 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006927 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006928 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006929 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006930 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006931 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006932 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006933 }
6934
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006935 return NO_ERROR;
6936}
6937
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006938status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6939 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6940 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6941 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006942 ATRACE_CALL();
6943
6944 if (!displayToken) {
6945 return BAD_VALUE;
6946 }
6947
Dominik Laskowski756b7892021-08-04 12:53:59 -07006948 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006949 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006950 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006951 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006952 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006953 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006954 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006955 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006956 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006957 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006958 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006959 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006960 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006961 {Fps::fromValue(primaryRefreshRateMin),
6962 Fps::fromValue(primaryRefreshRateMax)},
6963 {Fps::fromValue(appRequestRefreshRateMin),
6964 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006965 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006966
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006967 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006968 }
6969 });
6970
6971 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006972}
6973
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006974status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6975 ui::DisplayModeId* outDefaultMode,
6976 bool* outAllowGroupSwitching,
6977 float* outPrimaryRefreshRateMin,
6978 float* outPrimaryRefreshRateMax,
6979 float* outAppRequestRefreshRateMin,
6980 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006981 ATRACE_CALL();
6982
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006983 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006984 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006985 return BAD_VALUE;
6986 }
6987
6988 Mutex::Autolock lock(mStateLock);
6989 const auto display = getDisplayDeviceLocked(displayToken);
6990 if (!display) {
6991 return NAME_NOT_FOUND;
6992 }
6993
Ady Abraham3efa3942021-06-24 19:01:25 -07006994 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006995 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006996 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006997
6998 scheduler::RefreshRateConfigs::Policy policy =
6999 display->refreshRateConfigs().getDisplayManagerPolicy();
7000 *outDefaultMode = policy.defaultMode.value();
7001 *outAllowGroupSwitching = policy.allowGroupSwitching;
7002 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
7003 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
7004 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
7005 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
7006 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07007007}
7008
Vishnu Nairf9096652021-07-20 18:49:42 -07007009wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
7010 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07007011}
7012
Dominik Laskowski75848362019-11-11 17:57:20 -08007013void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007014 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07007015 if (!layer->isRemovedFromCurrentState()) {
7016 mScheduler->registerLayer(layer);
7017 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007018}
7019
7020void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
7021 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07007022 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07007023 if (!layer->isRemovedFromCurrentState()) {
7024 mScheduler->deregisterLayer(layer);
7025 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08007026 if (mTransactionTracing) {
7027 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08007028 }
Valerie Hauc5686802019-11-22 14:18:09 -08007029}
7030
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007031void SurfaceFlinger::onLayerUpdate() {
7032 scheduleCommit(FrameHint::kActive);
7033}
7034
Valerie Hauc5686802019-11-22 14:18:09 -08007035// WARNING: ONLY CALL THIS FROM LAYER DTOR
7036// Here we add children in the current state to offscreen layers and remove the
7037// layer itself from the offscreen layer list. Since
7038// this is the dtor, it is safe to access the current state. This keeps us
7039// from dangling children layers such that they are not reachable from the
7040// Drawing state nor the offscreen layer list
7041// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07007042void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08007043 for (auto& child : layer->getCurrentChildren()) {
7044 mOffscreenLayers.emplace(child.get());
7045 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07007046 mOffscreenLayers.erase(layer);
7047}
7048
Robert Carr867be372021-06-29 17:36:02 -07007049void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
7050 mOffscreenLayers.erase(layer);
7051}
7052
Vishnu Nair08f6eae2019-11-26 14:01:39 -08007053status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
7054 float lightPosY, float lightPosZ,
7055 float lightRadius) {
7056 Mutex::Autolock _l(mStateLock);
7057 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
7058 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
7059 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
7060 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
7061 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
7062
7063 // these values are overridden when calculating the shadow settings for a layer.
7064 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
7065 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08007066 return NO_ERROR;
7067}
7068
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007069const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
7070 const {
7071 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
7072 // on the work to remove the table in that bug rather than adding more to
7073 // it.
7074 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007075 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
7076 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08007077 };
7078 return genericLayerMetadataKeyMap;
7079}
7080
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007081status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7082 PhysicalDisplayId displayId = [&]() {
7083 Mutex::Autolock lock(mStateLock);
7084 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7085 }();
7086
7087 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7088 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7089 return NO_ERROR;
7090}
7091
Dominik Laskowski20134642020-04-20 22:36:44 -07007092void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007093 for (const auto& [ignored, display] : mDisplays) {
7094 if (display->isInternal()) {
7095 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007096 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007097 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007098}
7099
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007100status_t SurfaceFlinger::addTransactionTraceListener(
7101 const sp<gui::ITransactionTraceListener>& listener) {
7102 if (!listener) {
7103 return BAD_VALUE;
7104 }
7105
7106 mInterceptor->addTransactionTraceListener(listener);
7107
7108 return NO_ERROR;
7109}
7110
Huihong Luo02186fb2022-02-23 14:21:54 -08007111int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007112 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007113}
7114
Ady Abraham899dcdb2021-06-15 16:56:21 -07007115int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7116 std::chrono::nanoseconds presentLatency) {
7117 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7118 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007119 pipelineDepth++;
7120 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007121 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007122}
7123
Ady Abraham899dcdb2021-06-15 16:56:21 -07007124status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007125 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007126
7127 if (!getHwComposer().isHeadless()) {
7128 if (const auto display = getDefaultDisplayDevice()) {
7129 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007130 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007131 }
7132
7133 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007134 return NO_ERROR;
7135}
7136
rnleeed20fa42021-08-10 18:00:03 -07007137uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007138 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007139
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007140 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7141 refreshRate = *frameRateOverride;
7142 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007143 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007144 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007145 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007146 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007147
Ady Abraham899dcdb2021-06-15 16:56:21 -07007148 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7149}
7150
7151int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7152 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7153 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7154 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7155}
7156
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007157void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state) {
7158 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007159 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007160 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7161 return;
arthurhungdba591c2021-02-08 17:28:49 +08007162 }
7163
7164 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007165 bool addToRoot = state.addToRoot;
7166 if (state.initialParent != nullptr) {
7167 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007168 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007169 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007170 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007171 }
arthurhungdba591c2021-02-08 17:28:49 +08007172 }
7173
Garfield Tand712ad32021-10-27 13:44:22 -07007174 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007175 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007176 mCurrentState.layersSortedByZ.add(layer);
7177 } else if (parent == nullptr) {
7178 layer->onRemovedFromCurrentState();
7179 } else if (parent->isRemovedFromCurrentState()) {
7180 parent->addChild(layer);
7181 layer->onRemovedFromCurrentState();
7182 } else {
7183 parent->addChild(layer);
7184 }
7185
Ady Abraham1273ac12021-08-26 17:31:53 -07007186 layer->updateTransformHint(mActiveDisplayTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +08007187
Arthur Hung23e07502021-10-15 11:58:19 +00007188 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007189}
Ady Abraham562c2712021-05-07 15:10:42 -07007190
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007191void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007192 if (!mLumaSampling || !mRegionSamplingThread) {
7193 return;
7194 }
7195
Dominik Laskowski756b7892021-08-04 12:53:59 -07007196 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007197}
7198
Ady Abrahamed3290f2021-05-17 15:12:14 -07007199void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7200 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7201 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7202}
7203
7204void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7205 ATRACE_CALL();
7206
Ady Abrahamdb036a82021-07-16 14:18:34 -07007207 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7208 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7209 }
7210
Ady Abrahamed3290f2021-05-17 15:12:14 -07007211 if (!activeDisplay) {
7212 ALOGE("%s: activeDisplay is null", __func__);
7213 return;
7214 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007215 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007216 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007217 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007218 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007219 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007220 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007221 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007222
7223 // Update the kernel timer for the current active display, since the policy
7224 // for this display might have changed when it was not the active display.
7225 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007226}
7227
chaviw60c9d3e2021-06-04 12:52:17 -05007228status_t SurfaceFlinger::addWindowInfosListener(
7229 const sp<IWindowInfosListener>& windowInfosListener) const {
7230 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7231 return NO_ERROR;
7232}
7233
7234status_t SurfaceFlinger::removeWindowInfosListener(
7235 const sp<IWindowInfosListener>& windowInfosListener) const {
7236 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7237 return NO_ERROR;
7238}
7239
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007240std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7241 const BufferData& bufferData, const char* layerName) const {
7242 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7243 bool bufferSizeExceedsLimit = false;
7244 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7245 if (cacheIdChanged && bufferData.buffer != nullptr) {
7246 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7247 bufferData.buffer->getHeight());
7248 if (!bufferSizeExceedsLimit) {
7249 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7250 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7251 }
7252 } else if (cacheIdChanged) {
7253 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7254 } else if (bufferData.buffer != nullptr) {
7255 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7256 bufferData.buffer->getHeight());
7257 if (!bufferSizeExceedsLimit) {
7258 buffer = std::make_shared<
7259 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7260 renderengine::impl::ExternalTexture::
7261 Usage::READABLE);
7262 }
7263 }
7264 ALOGE_IF(bufferSizeExceedsLimit,
7265 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7266 "limit.",
7267 layerName);
7268 return buffer;
7269}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007270
7271bool SurfaceFlinger::commitCreatedLayers() {
7272 std::vector<LayerCreatedState> createdLayers;
7273 {
7274 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7275 createdLayers = std::move(mCreatedLayers);
7276 mCreatedLayers.clear();
7277 if (createdLayers.size() == 0) {
7278 return false;
7279 }
7280 }
7281
7282 Mutex::Autolock _l(mStateLock);
7283 for (const auto& createdLayer : createdLayers) {
7284 handleLayerCreatedLocked(createdLayer);
7285 }
7286 createdLayers.clear();
7287 mLayersAdded = true;
7288 return true;
7289}
Huihong Luof5029222021-12-16 14:33:46 -08007290
7291// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007292
Huihong Luo1b0c49f2022-03-15 19:18:21 -07007293binder::Status SurfaceComposerAIDL::bootFinished() {
7294 status_t status = checkAccessPermission();
7295 if (status != OK) {
7296 return binderStatusFromStatusT(status);
7297 }
7298 mFlinger->bootFinished();
7299 return binder::Status::ok();
7300}
7301
7302binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
7303 VsyncSource vsyncSource, EventRegistration eventRegistration,
7304 sp<IDisplayEventConnection>* outConnection) {
7305 sp<IDisplayEventConnection> conn =
7306 mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration);
7307 if (conn == nullptr) {
7308 *outConnection = nullptr;
7309 return binderStatusFromStatusT(BAD_VALUE);
7310 } else {
7311 *outConnection = conn;
7312 return binder::Status::ok();
7313 }
7314}
7315
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007316binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
7317 const sp<Client> client = new Client(mFlinger);
7318 if (client->initCheck() == NO_ERROR) {
7319 *outClient = client;
7320 return binder::Status::ok();
7321 } else {
7322 *outClient = nullptr;
7323 return binderStatusFromStatusT(BAD_VALUE);
7324 }
7325}
7326
Huihong Luo07e72362022-02-14 14:26:04 -08007327binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7328 sp<IBinder>* outDisplay) {
7329 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007330 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007331 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007332 }
Huihong Luo37396db2022-02-15 10:43:00 -08007333 String8 displayName8 = String8::format("%s", displayName.c_str());
7334 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7335 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007336}
7337
7338binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7339 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007340 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007341 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007342 }
Huihong Luo37396db2022-02-15 10:43:00 -08007343 mFlinger->destroyDisplay(display);
7344 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007345}
7346
7347binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7348 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7349 std::vector<int64_t> displayIds;
7350 displayIds.reserve(physicalDisplayIds.size());
7351 for (auto item : physicalDisplayIds) {
7352 displayIds.push_back(static_cast<int64_t>(item.value));
7353 }
7354 *outDisplayIds = displayIds;
7355 return binder::Status::ok();
7356}
7357
7358binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7359 status_t status = checkAccessPermission();
7360 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007361 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007362 }
7363
7364 PhysicalDisplayId id;
7365 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7366 if (status == NO_ERROR) {
7367 *outDisplayId = id.value;
7368 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007369 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007370}
7371
7372binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7373 sp<IBinder>* outDisplay) {
7374 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7375 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7376 return binder::Status::ok();
7377}
7378
Huihong Luo37396db2022-02-15 10:43:00 -08007379binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7380 status_t status = checkAccessPermission();
7381 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007382 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007383 }
7384 mFlinger->setPowerMode(display, mode);
7385 return binder::Status::ok();
7386}
7387
Huihong Luo0a81aa32022-02-22 16:02:36 -08007388binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7389 std::vector<FrameEvent>* outSupported) {
7390 status_t status;
7391 if (!outSupported) {
7392 status = UNEXPECTED_NULL;
7393 } else {
7394 outSupported->clear();
7395 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7396 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007397 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007398}
7399
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007400binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7401 gui::DisplayStatInfo* outStatInfo) {
7402 DisplayStatInfo statInfo;
7403 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7404 if (status == NO_ERROR) {
7405 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7406 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7407 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007408 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007409}
7410
7411binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7412 gui::DisplayState* outState) {
7413 ui::DisplayState state;
7414 status_t status = mFlinger->getDisplayState(display, &state);
7415 if (status == NO_ERROR) {
7416 outState->layerStack = state.layerStack.id;
7417 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7418 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7419 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7420 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007421 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007422}
7423
Huihong Luoa79ddf42022-02-17 00:01:38 -08007424binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7425 gui::StaticDisplayInfo* outInfo) {
7426 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7427 ui::StaticDisplayInfo info;
7428 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7429 if (status == NO_ERROR) {
7430 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7431 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7432 outInfo->density = info.density;
7433 outInfo->secure = info.secure;
7434 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7435
7436 gui::DeviceProductInfo dinfo;
7437 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7438 dinfo.name = std::move(dpi->name);
7439 dinfo.manufacturerPnpId =
7440 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7441 dinfo.productId = dpi->productId;
Kriti Dang1de958d2022-05-30 15:26:58 +02007442 dinfo.relativeAddress =
7443 std::vector<uint8_t>(dpi->relativeAddress.begin(), dpi->relativeAddress.end());
Huihong Luoa79ddf42022-02-17 00:01:38 -08007444 if (const auto* model =
7445 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7446 gui::DeviceProductInfo::ModelYear modelYear;
7447 modelYear.year = model->year;
7448 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7449 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7450 &dpi->manufactureOrModelDate)) {
7451 gui::DeviceProductInfo::ManufactureYear date;
7452 date.modelYear.year = manufacture->year;
7453 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7454 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7455 &dpi->manufactureOrModelDate)) {
7456 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7457 date.manufactureYear.modelYear.year = manufacture->year;
7458 date.week = manufacture->week;
7459 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7460 }
7461
7462 outInfo->deviceProductInfo = dinfo;
7463 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007464 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007465}
7466
Huihong Luo38603fd2022-02-21 14:32:54 -08007467binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7468 gui::DynamicDisplayInfo* outInfo) {
7469 ui::DynamicDisplayInfo info;
7470 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7471 if (status == NO_ERROR) {
7472 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7473 outInfo->supportedDisplayModes.clear();
7474 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7475 for (const auto& mode : info.supportedDisplayModes) {
7476 gui::DisplayMode outMode;
7477 outMode.id = mode.id;
7478 outMode.resolution.width = mode.resolution.width;
7479 outMode.resolution.height = mode.resolution.height;
7480 outMode.xDpi = mode.xDpi;
7481 outMode.yDpi = mode.yDpi;
7482 outMode.refreshRate = mode.refreshRate;
7483 outMode.appVsyncOffset = mode.appVsyncOffset;
7484 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7485 outMode.presentationDeadline = mode.presentationDeadline;
7486 outMode.group = mode.group;
7487 outInfo->supportedDisplayModes.push_back(outMode);
7488 }
7489
7490 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7491
7492 outInfo->supportedColorModes.clear();
7493 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7494 for (const auto& cmode : info.supportedColorModes) {
7495 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7496 }
7497
7498 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7499
7500 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7501 hdrCapabilities.supportedHdrTypes.clear();
7502 hdrCapabilities.supportedHdrTypes.reserve(
7503 info.hdrCapabilities.getSupportedHdrTypes().size());
7504 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7505 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7506 }
7507 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7508 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7509 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7510
7511 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7512 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7513 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7514 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007515 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007516}
7517
Huihong Luoca3d9a42022-02-22 11:07:34 -08007518binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7519 gui::DisplayPrimaries* outPrimaries) {
7520 ui::DisplayPrimaries primaries;
7521 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7522 if (status == NO_ERROR) {
7523 outPrimaries->red.X = primaries.red.X;
7524 outPrimaries->red.Y = primaries.red.Y;
7525 outPrimaries->red.Z = primaries.red.Z;
7526
7527 outPrimaries->green.X = primaries.green.X;
7528 outPrimaries->green.Y = primaries.green.Y;
7529 outPrimaries->green.Z = primaries.green.Z;
7530
7531 outPrimaries->blue.X = primaries.blue.X;
7532 outPrimaries->blue.Y = primaries.blue.Y;
7533 outPrimaries->blue.Z = primaries.blue.Z;
7534
7535 outPrimaries->white.X = primaries.white.X;
7536 outPrimaries->white.Y = primaries.white.Y;
7537 outPrimaries->white.Z = primaries.white.Z;
7538 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007539 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007540}
7541
7542binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7543 status_t status = checkAccessPermission();
7544 if (status == OK) {
7545 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7546 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007547 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007548}
7549
7550binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7551 int displayModeId) {
7552 status_t status = checkAccessPermission();
7553 if (status == OK) {
7554 status = mFlinger->setBootDisplayMode(display,
7555 static_cast<ui::DisplayModeId>(displayModeId));
7556 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007557 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007558}
7559
Huihong Luo37396db2022-02-15 10:43:00 -08007560binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7561 status_t status = checkAccessPermission();
7562 if (status == OK) {
7563 status = mFlinger->clearBootDisplayMode(display);
7564 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007565 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007566}
7567
7568binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7569 status_t status = checkAccessPermission();
7570 if (status == OK) {
7571 status = mFlinger->getBootDisplayModeSupport(outMode);
7572 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007573 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007574}
7575
7576binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7577 status_t status = checkAccessPermission();
7578 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007579 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007580 }
7581 mFlinger->setAutoLowLatencyMode(display, on);
7582 return binder::Status::ok();
7583}
7584
7585binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7586 status_t status = checkAccessPermission();
7587 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007588 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007589 }
7590 mFlinger->setGameContentType(display, on);
7591 return binder::Status::ok();
7592}
7593
Huihong Luof5029222021-12-16 14:33:46 -08007594binder::Status SurfaceComposerAIDL::captureDisplay(
7595 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7596 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007597 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007598}
7599
7600binder::Status SurfaceComposerAIDL::captureDisplayById(
7601 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7602 status_t status;
7603 IPCThreadState* ipc = IPCThreadState::self();
7604 const int uid = ipc->getCallingUid();
7605 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7606 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7607 status = mFlinger->captureDisplay(*id, captureListener);
7608 } else {
7609 status = PERMISSION_DENIED;
7610 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007611 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007612}
7613
7614binder::Status SurfaceComposerAIDL::captureLayers(
7615 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7616 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007617 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007618}
7619
Huihong Luo4ed1c912022-02-22 14:30:01 -08007620binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7621 status_t status = checkAccessPermission();
7622 if (status == OK) {
7623 status = mFlinger->clearAnimationFrameStats();
7624 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007625 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007626}
7627
7628binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7629 status_t status = checkAccessPermission();
7630 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007631 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007632 }
7633
7634 FrameStats stats;
7635 status = mFlinger->getAnimationFrameStats(&stats);
7636 if (status == NO_ERROR) {
7637 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7638 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7639 for (const auto& t : stats.desiredPresentTimesNano) {
7640 outStats->desiredPresentTimesNano.push_back(t);
7641 }
7642 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7643 for (const auto& t : stats.actualPresentTimesNano) {
7644 outStats->actualPresentTimesNano.push_back(t);
7645 }
7646 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7647 for (const auto& t : stats.frameReadyTimesNano) {
7648 outStats->frameReadyTimesNano.push_back(t);
7649 }
7650 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007651 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007652}
7653
Huihong Luo05539a12022-02-23 10:29:40 -08007654binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7655 const std::vector<int32_t>& hdrTypes) {
7656 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7657 // permission dynamically. Don't use the permission cache for this check.
7658 status_t status = checkAccessPermission(false);
7659 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007660 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007661 }
7662
7663 std::vector<ui::Hdr> hdrTypesVector;
7664 for (int32_t i : hdrTypes) {
7665 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7666 }
7667 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007668 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007669}
7670
7671binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7672 status_t status;
7673 const int uid = IPCThreadState::self()->getCallingUid();
7674 if (uid != AID_SYSTEM) {
7675 status = PERMISSION_DENIED;
7676 } else {
7677 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7678 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007679 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007680}
7681
7682binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7683 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007684 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007685 }
7686
7687 status_t status = checkAccessPermission();
7688 if (status == OK) {
7689 status = mFlinger->enableVSyncInjections(enable);
7690 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007691 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007692}
7693
7694binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7695 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007696 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007697 }
7698
7699 status_t status = checkAccessPermission();
7700 if (status == OK) {
7701 status = mFlinger->injectVSync(when);
7702 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007703 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007704}
7705
7706binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7707 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007708 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007709 }
7710
7711 IPCThreadState* ipc = IPCThreadState::self();
7712 const int pid = ipc->getCallingPid();
7713 const int uid = ipc->getCallingUid();
7714 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7715 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007716 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007717 }
7718 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007719 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007720}
7721
7722binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7723 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007724 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007725}
7726
7727binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7728 ui::Dataspace dataspace;
7729 ui::PixelFormat pixelFormat;
7730 ui::Dataspace wideColorGamutDataspace;
7731 ui::PixelFormat wideColorGamutPixelFormat;
7732 status_t status =
7733 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7734 &wideColorGamutPixelFormat);
7735 if (status == NO_ERROR) {
7736 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7737 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7738 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7739 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7740 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007741 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007742}
7743
7744binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7745 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7746 status_t status = checkAccessPermission();
7747 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007748 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007749 }
7750
7751 ui::PixelFormat format;
7752 ui::Dataspace dataspace;
7753 uint8_t componentMask;
7754 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7755 &componentMask);
7756 if (status == NO_ERROR) {
7757 outAttrs->format = static_cast<int32_t>(format);
7758 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7759 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7760 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007761 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007762}
7763
7764binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7765 bool enable,
7766 int8_t componentMask,
7767 int64_t maxFrames) {
7768 status_t status = checkAccessPermission();
7769 if (status == OK) {
7770 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7771 static_cast<uint8_t>(componentMask),
7772 static_cast<uint64_t>(maxFrames));
7773 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007774 return binderStatusFromStatusT(status);
7775}
7776
7777binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7778 int64_t maxFrames, int64_t timestamp,
7779 gui::DisplayedFrameStats* outStats) {
7780 if (!outStats) {
7781 return binderStatusFromStatusT(BAD_VALUE);
7782 }
7783
7784 status_t status = checkAccessPermission();
7785 if (status != OK) {
7786 return binderStatusFromStatusT(status);
7787 }
7788
7789 DisplayedFrameStats stats;
7790 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7791 static_cast<uint64_t>(timestamp), &stats);
7792 if (status == NO_ERROR) {
7793 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7794 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7795 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7796 for (const auto& s : stats.component_0_sample) {
7797 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7798 }
7799 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7800 for (const auto& s : stats.component_1_sample) {
7801 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7802 }
7803 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7804 for (const auto& s : stats.component_2_sample) {
7805 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7806 }
7807 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7808 for (const auto& s : stats.component_3_sample) {
7809 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7810 }
7811 }
7812 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007813}
7814
7815binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7816 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007817 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007818}
7819
Huihong Luo37396db2022-02-15 10:43:00 -08007820binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7821 bool* outIsWideColorDisplay) {
7822 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007823 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007824}
7825
Huihong Luo02186fb2022-02-23 14:21:54 -08007826binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7827 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7828 const sp<gui::IRegionSamplingListener>& listener) {
7829 status_t status = checkReadFrameBufferPermission();
7830 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007831 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007832 }
7833 android::Rect rect;
7834 rect.left = samplingArea.left;
7835 rect.top = samplingArea.top;
7836 rect.right = samplingArea.right;
7837 rect.bottom = samplingArea.bottom;
7838 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007839 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007840}
7841
7842binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7843 const sp<gui::IRegionSamplingListener>& listener) {
7844 status_t status = checkReadFrameBufferPermission();
7845 if (status == OK) {
7846 status = mFlinger->removeRegionSamplingListener(listener);
7847 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007848 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007849}
7850
7851binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7852 const sp<gui::IFpsListener>& listener) {
7853 status_t status = checkReadFrameBufferPermission();
7854 if (status == OK) {
7855 status = mFlinger->addFpsListener(taskId, 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::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7861 status_t status = checkReadFrameBufferPermission();
7862 if (status == OK) {
7863 status = mFlinger->removeFpsListener(listener);
7864 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007865 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007866}
7867
7868binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7869 const sp<gui::ITunnelModeEnabledListener>& listener) {
7870 status_t status = checkAccessPermission();
7871 if (status == OK) {
7872 status = mFlinger->addTunnelModeEnabledListener(listener);
7873 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007874 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007875}
7876
7877binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7878 const sp<gui::ITunnelModeEnabledListener>& listener) {
7879 status_t status = checkAccessPermission();
7880 if (status == OK) {
7881 status = mFlinger->removeTunnelModeEnabledListener(listener);
7882 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007883 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007884}
7885
7886binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7887 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7888 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7889 float appRequestRefreshRateMax) {
7890 status_t status = checkAccessPermission();
7891 if (status == OK) {
7892 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7893 static_cast<ui::DisplayModeId>(defaultMode),
7894 allowGroupSwitching, primaryRefreshRateMin,
7895 primaryRefreshRateMax,
7896 appRequestRefreshRateMin,
7897 appRequestRefreshRateMax);
7898 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007899 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007900}
7901
7902binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7903 gui::DisplayModeSpecs* outSpecs) {
7904 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007905 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007906 }
7907
7908 status_t status = checkAccessPermission();
7909 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007910 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007911 }
7912
7913 ui::DisplayModeId displayModeId;
7914 bool allowGroupSwitching;
7915 float primaryRefreshRateMin;
7916 float primaryRefreshRateMax;
7917 float appRequestRefreshRateMin;
7918 float appRequestRefreshRateMax;
7919 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7920 &allowGroupSwitching, &primaryRefreshRateMin,
7921 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7922 &appRequestRefreshRateMax);
7923 if (status == NO_ERROR) {
7924 outSpecs->defaultMode = displayModeId;
7925 outSpecs->allowGroupSwitching = allowGroupSwitching;
7926 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7927 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7928 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7929 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7930 }
7931
Huihong Luo3bdef862022-03-03 11:57:19 -08007932 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007933}
7934
Huihong Luo37396db2022-02-15 10:43:00 -08007935binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7936 bool* outSupport) {
7937 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007938 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007939}
7940
7941binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7942 const gui::DisplayBrightness& brightness) {
7943 status_t status = checkControlDisplayBrightnessPermission();
7944 if (status == OK) {
7945 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7946 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007947 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007948}
7949
7950binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7951 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7952 status_t status = checkControlDisplayBrightnessPermission();
7953 if (status == OK) {
7954 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7955 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007956 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007957}
7958
7959binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7960 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7961 status_t status = checkControlDisplayBrightnessPermission();
7962 if (status == OK) {
7963 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7964 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007965 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007966}
7967
7968binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7969 status_t status = checkAccessPermission();
7970 if (status == OK) {
7971 status = mFlinger->notifyPowerBoost(boostId);
7972 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007973 return binderStatusFromStatusT(status);
7974}
7975
7976binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7977 const gui::Color& spotColor,
7978 float lightPosY, float lightPosZ,
7979 float lightRadius) {
7980 status_t status = checkAccessPermission();
7981 if (status != OK) {
7982 return binderStatusFromStatusT(status);
7983 }
7984
7985 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7986 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7987 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7988 lightPosZ, lightRadius);
7989 return binderStatusFromStatusT(status);
7990}
7991
7992binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7993 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7994 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7995 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7996 if (status != NO_ERROR) {
7997 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7998 return binderStatusFromStatusT(status);
7999 }
8000
8001 if (!support || !support.has_value()) {
8002 outSupport->reset();
8003 } else {
8004 outSupport->emplace();
8005 outSupport->value().format = static_cast<int32_t>(support->format);
8006 outSupport->value().alphaInterpretation =
8007 static_cast<int32_t>(support->alphaInterpretation);
8008 }
8009
8010 return binder::Status::ok();
8011}
8012
8013binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
8014 status_t status;
8015 const int c_uid = IPCThreadState::self()->getCallingUid();
8016 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
8017 status = mFlinger->setOverrideFrameRate(uid, frameRate);
8018 } else {
8019 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
8020 status = PERMISSION_DENIED;
8021 }
8022 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08008023}
8024
Huihong Luo02186fb2022-02-23 14:21:54 -08008025binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
8026 const sp<gui::ITransactionTraceListener>& listener) {
8027 status_t status;
8028 IPCThreadState* ipc = IPCThreadState::self();
8029 const int uid = ipc->getCallingUid();
8030 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
8031 status = mFlinger->addTransactionTraceListener(listener);
8032 } else {
8033 status = PERMISSION_DENIED;
8034 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008035 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008036}
8037
8038binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
8039 *outPriority = mFlinger->getGpuContextPriority();
8040 return binder::Status::ok();
8041}
8042
8043binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
8044 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08008045 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008046}
8047
8048binder::Status SurfaceComposerAIDL::addWindowInfosListener(
8049 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8050 status_t status;
8051 const int uid = IPCThreadState::self()->getCallingUid();
8052 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8053 status = mFlinger->addWindowInfosListener(windowInfosListener);
8054 } else {
8055 status = PERMISSION_DENIED;
8056 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008057 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008058}
8059
8060binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
8061 const sp<gui::IWindowInfosListener>& windowInfosListener) {
8062 status_t status;
8063 const int uid = IPCThreadState::self()->getCallingUid();
8064 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
8065 status = mFlinger->removeWindowInfosListener(windowInfosListener);
8066 } else {
8067 status = PERMISSION_DENIED;
8068 }
Huihong Luo3bdef862022-03-03 11:57:19 -08008069 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08008070}
8071
Huihong Luo07e72362022-02-14 14:26:04 -08008072status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
8073 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
8074 IPCThreadState* ipc = IPCThreadState::self();
8075 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
8076 ipc->getCallingUid());
8077 return PERMISSION_DENIED;
8078 }
8079 return OK;
8080}
8081
Huihong Luo37396db2022-02-15 10:43:00 -08008082status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
8083 IPCThreadState* ipc = IPCThreadState::self();
8084 const int pid = ipc->getCallingPid();
8085 const int uid = ipc->getCallingUid();
8086 if ((uid != AID_GRAPHICS) &&
8087 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
8088 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
8089 return PERMISSION_DENIED;
8090 }
8091 return OK;
8092}
8093
Huihong Luo02186fb2022-02-23 14:21:54 -08008094status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
8095 IPCThreadState* ipc = IPCThreadState::self();
8096 const int pid = ipc->getCallingPid();
8097 const int uid = ipc->getCallingUid();
8098 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
8099 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
8100 return PERMISSION_DENIED;
8101 }
8102 return OK;
8103}
8104
Dominik Laskowski9dab3432019-03-27 13:21:10 -07008105} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07008106
Mathias Agopian3f844832013-08-07 21:24:32 -07008107#if defined(__gl_h_)
8108#error "don't include gl/gl.h in this file"
8109#endif
8110
8111#if defined(__gl2_h_)
8112#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008113#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008114
8115// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008116#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"