blob: 46b1a60a77773e98887de2ca362133a338d9f26f [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>
153
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700154#undef NO_THREAD_SAFETY_ANALYSIS
155#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800156 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500157
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800158namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700159
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700160using namespace std::string_literals;
161
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800162using namespace hardware::configstore;
163using namespace hardware::configstore::V1_0;
164using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800165
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800166using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
167using aidl::android::hardware::graphics::composer3::Capability;
168using aidl::android::hardware::graphics::composer3::DisplayCapability;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800169using CompositionStrategyPredictionState = android::compositionengine::impl::
170 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800171
Yiwei Zhang5434a782018-12-05 18:06:32 -0800172using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700173using gui::DisplayInfo;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800174using gui::GameMode;
Huihong Luo6fac5232021-11-22 16:05:23 -0800175using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500176using gui::IWindowInfosListener;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800177using gui::LayerMetadata;
chaviw98318de2021-05-19 16:45:23 -0500178using gui::WindowInfo;
Huihong Luo3bdef862022-03-03 11:57:19 -0800179using gui::aidl_utils::binderStatusFromStatusT;
Peiyong Lin9f034472018-03-28 15:29:00 -0700180using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700181using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800182using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700183using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900184
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800185using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
186
Peiyong Line9d809e2020-04-14 13:10:48 -0700187namespace hal = android::hardware::graphics::composer::hal;
188
Steven Thomasb02664d2017-07-26 18:48:28 -0700189namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700190
191#pragma clang diagnostic push
192#pragma clang diagnostic error "-Wswitch-enum"
193
194bool isWideColorMode(const ColorMode colorMode) {
195 switch (colorMode) {
196 case ColorMode::DISPLAY_P3:
197 case ColorMode::ADOBE_RGB:
198 case ColorMode::DCI_P3:
199 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700200 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700201 case ColorMode::BT2100_PQ:
202 case ColorMode::BT2100_HLG:
203 return true;
204 case ColorMode::NATIVE:
205 case ColorMode::STANDARD_BT601_625:
206 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
207 case ColorMode::STANDARD_BT601_525:
208 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
209 case ColorMode::STANDARD_BT709:
210 case ColorMode::SRGB:
211 return false;
212 }
213 return false;
214}
215
216#pragma clang diagnostic pop
217
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100218// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700219constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800220
221float getDensityFromProperty(const char* property, bool required) {
222 char value[PROPERTY_VALUE_MAX];
223 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
224 if (!density && required) {
225 ALOGE("%s must be defined as a build property", property);
226 return FALLBACK_DENSITY;
227 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700228 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800229}
230
Peiyong Lin9d846a52018-11-05 13:18:20 -0800231// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
232bool validateCompositionDataspace(Dataspace dataspace) {
233 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
234}
235
ramindani32cf0602022-03-02 02:30:29 +0000236std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700237 const auto displayIdleTimerMsKey = [displayId] {
238 std::stringstream ss;
239 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
240 return ss.str();
241 }();
242
ramindani32cf0602022-03-02 02:30:29 +0000243 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
244 if (displayIdleTimerMs > 0) {
245 return std::chrono::milliseconds(displayIdleTimerMs);
246 }
247
248 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
249 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
250 return std::chrono::milliseconds(millis);
251}
252
253bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700254 const auto displaySupportKernelIdleTimerKey = [displayId] {
255 std::stringstream ss;
256 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
257 return ss.str();
258 }();
259
Ady Abraham6d885932021-09-03 18:05:48 -0700260 const auto displaySupportKernelIdleTimer =
261 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000262 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700263}
264
Steven Thomasb02664d2017-07-26 18:48:28 -0700265} // namespace anonymous
266
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800267// ---------------------------------------------------------------------------
268
Mathias Agopian99b49842011-06-27 16:05:52 -0700269const String16 sHardwareTest("android.permission.HARDWARE_TEST");
270const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800271const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700272const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400273const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700274const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500275const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000276const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500277
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800278const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700279
280// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700281int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700282bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800283bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800284int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100285uint32_t SurfaceFlinger::maxGraphicsWidth;
286uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600287bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700288bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700289Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
290ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
291Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
292ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000293LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700294
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800295std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
296 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800297 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700298 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800299 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700300 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800301 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700302 return std::string("Enhanced");
303 default:
304 return std::string("Unknown ") +
305 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800306 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800307}
308
Hongwei Wang46213ea2020-12-04 17:17:31 -0800309bool callingThreadHasRotateSurfaceFlingerAccess() {
310 IPCThreadState* ipc = IPCThreadState::self();
311 const int pid = ipc->getCallingPid();
312 const int uid = ipc->getCallingUid();
313 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
314 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
315}
316
Leon Scroggins9a20f722021-12-28 14:43:12 +0000317bool callingThreadHasInternalSystemWindowAccess() {
318 IPCThreadState* ipc = IPCThreadState::self();
319 const int pid = ipc->getCallingPid();
320 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500321 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
322 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000323}
324
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700325SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
326 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800327 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000328 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700329 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800330 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800331 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700332 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700333 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700334 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800335 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700336 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
Xiang Wang839fe5b2022-04-04 17:39:38 +0000337 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
Dominik Laskowski91f635e2022-01-08 05:46:09 -0800338 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make(*this)) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700339 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700340}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800341
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700342SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800343 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800344
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800346
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900347 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700348
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900349 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700350
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900351 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800352
Brian Lindahla13f2d52020-03-05 11:54:17 +0100353 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
354 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
355
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900356 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900357 mDefaultCompositionDataspace =
358 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700359 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
360 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900361 defaultCompositionDataspace = mDefaultCompositionDataspace;
362 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
363 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
364 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
365 wideColorGamutCompositionPixelFormat =
366 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700367
Yichi Chenda901bf2019-06-28 14:58:27 +0800368 mColorSpaceAgnosticDataspace =
369 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
370
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700371 mLayerCachingEnabled = [] {
372 const bool enable =
373 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
374 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
375 }();
376
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900377 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800378
Sundong Ahn85131bd2019-02-18 15:51:53 +0900379 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800380
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381 // debugging stuff...
382 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700383
Mathias Agopianb4b17302013-03-20 18:36:41 -0700384 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700385 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700386
Alec Mouri5f487d42020-02-06 09:26:19 -0800387 property_get("ro.build.type", value, "user");
388 mIsUserBuild = strcmp(value, "user") == 0;
389
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700390 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000391
392 // DDMS debugging deprecated (b/120782499)
393 property_get("debug.sf.ddms", value, "0");
394 int debugDdms = atoi(value);
395 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700396
Ady Abrahamadb9a992019-09-19 21:21:55 +0000397 property_get("debug.sf.enable_gl_backpressure", value, "0");
398 mPropagateBackpressureClientComposition = atoi(value);
399 ALOGI_IF(mPropagateBackpressureClientComposition,
400 "Enabling backpressure propagation for Client Composition");
401
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800402 property_get("ro.surface_flinger.supports_background_blur", value, "0");
403 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700404 mSupportsBlur = supportsBlurs;
405 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800406 property_get("ro.sf.blurs_are_expensive", value, "0");
407 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800408
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800409 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700410 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
411 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800412 mGraphicBufferProducerListSizeLogThreshold =
413 std::max(static_cast<int>(0.95 *
414 static_cast<double>(mMaxGraphicBufferProducerListSize)),
415 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700416
Dan Stozaec460082018-12-17 15:35:09 -0800417 property_get("debug.sf.luma_sampling", value, "1");
418 mLumaSampling = atoi(value);
419
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800420 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800421 mDisableClientCompositionCache = atoi(value);
422
Vishnu Nair3539d812022-02-26 09:20:17 -0800423 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
Vishnu Naira3140382022-02-24 14:07:11 -0800424 mPredictCompositionStrategy = atoi(value);
425
Romain Guy11d63f42017-07-20 12:47:14 -0700426 // We should be reading 'persist.sys.sf.color_saturation' here
427 // but since /data may be encrypted, we need to wait until after vold
428 // comes online to attempt to read the property. The property is
429 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800430
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700431 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800432 // Without the override SurfaceFlinger cannot connect to HIDL
433 // services that are not listed in the manifests. Considered
434 // deriving the setting from the set service name, but it
435 // would be brittle if the name that's not 'default' is used
436 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700437 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000438 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800439 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800440
Ady Abraham29d0da32020-07-16 18:39:33 -0700441 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400442
Dominik Laskowski46471e62022-01-14 15:34:03 -0800443 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
444 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800445 }
John Reck49d9ad32022-02-23 19:03:31 -0500446
447 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
ramindani4d48f902021-09-20 21:07:45 +0000448}
449
450LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
451 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
452 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000453 }
Ady Abraham9dada822022-02-03 10:26:59 -0800454
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000455 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800456 return LatchUnsignaledConfig::AutoSingleLayer;
457 }
458
459 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800460}
461
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700462SurfaceFlinger::~SurfaceFlinger() = default;
463
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700464void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800465 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700466 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800467
Dominik Laskowski756b7892021-08-04 12:53:59 -0700468 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000469 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800470
Andy McFadden13a082e2012-08-24 10:16:42 -0700471 // restore initial conditions (default device unblank, etc)
472 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800473
474 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700475 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800476}
477
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700478void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700479 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800480}
481
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700482sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700483 // onTransact already checks for some permissions, but adding an additional check here.
484 // This is to ensure that only system and graphics can request to create a secure
485 // display. Secure displays can show secure content so we add an additional restriction on it.
486 const int uid = IPCThreadState::self()->getCallingUid();
487 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
488 ALOGE("Only privileged processes can create a secure display");
489 return nullptr;
490 }
491
Mathias Agopiane57f2922012-08-09 16:29:12 -0700492 class DisplayToken : public BBinder {
493 sp<SurfaceFlinger> flinger;
494 virtual ~DisplayToken() {
495 // no more references, this display must be terminated
496 Mutex::Autolock _l(flinger->mStateLock);
497 flinger->mCurrentState.displays.removeItem(this);
498 flinger->setTransactionFlags(eDisplayTransactionNeeded);
499 }
500 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700501 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700502 : flinger(flinger) {
503 }
504 };
505
506 sp<BBinder> token = new DisplayToken(this);
507
508 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700509 // Display ID is assigned when virtual display is allocated by HWC.
510 DisplayDeviceState state;
511 state.isSecure = secure;
512 state.displayName = displayName;
513 mCurrentState.displays.add(token, state);
514 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700515 return token;
516}
517
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700518void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700519 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700520
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700521 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700522 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800523 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700524 return;
525 }
526
Dominik Laskowski075d3172018-05-24 15:50:06 -0700527 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700528 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800529 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700530 return;
531 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700532 mInterceptor->saveDisplayDeletion(state.sequenceId);
533 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700534 setTransactionFlags(eDisplayTransactionNeeded);
535}
536
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800537void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
538 auto& generator = mVirtualDisplayIdGenerators.hal;
539 if (!generator && enable) {
540 ALOGI("Enabling HAL virtual displays");
541 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
542 } else if (generator && !enable) {
543 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
544 generator.reset();
545 }
546}
547
Dominik Laskowski263eec42021-07-21 23:13:24 -0700548VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
549 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800550 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
551 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700552 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800553 return *id;
554 }
555
556 generator->releaseId(*id);
557 } else {
558 ALOGW("%s: Exhausted HAL virtual displays", __func__);
559 }
560
561 ALOGW("%s: Falling back to GPU virtual display", __func__);
562 }
563
564 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
565 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
566 return *id;
567}
568
569void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
570 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
571 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
572 generator->releaseId(*id);
573 }
574 return;
575 }
576
577 const auto id = GpuVirtualDisplayId::tryCast(displayId);
578 LOG_ALWAYS_FATAL_IF(!id);
579 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
580}
581
Ady Abrahamed3290f2021-05-17 15:12:14 -0700582std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800583 std::vector<PhysicalDisplayId> displayIds;
584 displayIds.reserve(mPhysicalDisplayTokens.size());
Ady Abraham2a0066d2021-07-15 20:16:58 -0700585 const auto defaultDisplayId = [this]() REQUIRES(mStateLock) {
586 if (const auto display = getDefaultDisplayDeviceLocked()) {
587 return display->getPhysicalId();
588 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700589
Ady Abraham2a0066d2021-07-15 20:16:58 -0700590 // fallback to the internal display id if the active display is unknown
591 return getInternalDisplayIdLocked();
592 }();
593 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800594
595 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700596 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200597 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800598 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700599 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700600
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800601 return displayIds;
602}
603
Vishnu Nair8c8db542021-09-17 19:51:45 -0700604status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
605 Mutex::Autolock lock(mStateLock);
606 *id = getInternalDisplayIdLocked();
607 return NO_ERROR;
608}
609
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800610sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
611 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200612 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700613}
614
Ady Abraham37965d42018-11-01 13:43:32 -0700615status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
616 if (!outGetColorManagement) {
617 return BAD_VALUE;
618 }
619 *outGetColorManagement = useColorManagement;
620 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700621}
622
Lloyd Pique441d5042018-10-18 16:49:51 -0700623HWComposer& SurfaceFlinger::getHwComposer() const {
624 return mCompositionEngine->getHwComposer();
625}
626
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700627renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
628 return mCompositionEngine->getRenderEngine();
629}
630
Lloyd Pique70d91362018-10-18 16:02:55 -0700631compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
632 return *mCompositionEngine.get();
633}
634
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100635void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700636 if (mBootFinished == true) {
637 ALOGE("Extra call to bootFinished");
638 return;
639 }
640 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700641 if (mStartPropertySetThread->join() != NO_ERROR) {
642 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800643 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700644
645 if (mRenderEnginePrimeCacheFuture.valid()) {
646 mRenderEnginePrimeCacheFuture.get();
647 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800648 const nsecs_t now = systemTime();
649 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000650 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700651
Mikael Pessa90092f42019-08-26 17:22:04 -0700652 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700653 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700654 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700655
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700656 // wait patiently for the window manager death
657 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700658 mWindowManager = defaultServiceManager()->getService(name);
659 if (mWindowManager != 0) {
660 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700661 }
662
663 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700664 // formerly we would just kill the process, but we now ask it to exit so it
665 // can choose where to stop the animation.
666 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700667
668 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
669 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
670 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700671
Denis Hsue70cc6c2020-06-17 10:17:30 +0800672 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
673
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000674 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800675 if (input == nullptr) {
676 ALOGE("Failed to link to input service");
677 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700678 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800679 }
680
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800681 readPersistentProperties();
Xiang Wang839fe5b2022-04-04 17:39:38 +0000682 mPowerAdvisor->onBootFinished();
683 mPowerAdvisor->enablePowerHint(mFlagManager.use_adpf_cpu_hint());
684 if (mPowerAdvisor->usePowerHintSession()) {
Xiang Wang76236e12022-03-22 17:25:30 +0000685 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
686 std::vector<int32_t> tidList;
687 tidList.emplace_back(gettid());
688 if (renderEngineTid.has_value()) {
689 tidList.emplace_back(*renderEngineTid);
690 }
Xiang Wang839fe5b2022-04-04 17:39:38 +0000691 if (!mPowerAdvisor->startPowerHintSession(tidList)) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000692 ALOGW("Cannot start power hint session");
693 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000694 }
695
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800696 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800697
Ady Abraham8a82ba62020-01-17 12:43:17 -0800698 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800699 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800700 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800701 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800702}
703
Dan Stoza436ccf32018-06-21 12:10:12 -0700704uint32_t SurfaceFlinger::getNewTexture() {
705 {
706 std::lock_guard lock(mTexturePoolMutex);
707 if (!mTexturePool.empty()) {
708 uint32_t name = mTexturePool.back();
709 mTexturePool.pop_back();
710 ATRACE_INT("TexturePoolSize", mTexturePool.size());
711 return name;
712 }
713
714 // The pool was too small, so increase it for the future
715 ++mTexturePoolSize;
716 }
717
718 // The pool was empty, so we need to get a new texture name directly using a
719 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700720 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700721 uint32_t name = 0;
722 getRenderEngine().genTextures(1, &name);
723 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700724 };
725 if (std::this_thread::get_id() == mMainThreadId) {
726 return genTextures();
727 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700728 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700729 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700730}
731
Mathias Agopian3f844832013-08-07 21:24:32 -0700732void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700733 std::lock_guard lock(mTexturePoolMutex);
734 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
735 // to actually delete this or not based on mTexturePoolSize
736 mTexturePool.push_back(texture);
737 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700738}
739
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500740static std::optional<renderengine::RenderEngine::RenderEngineType>
741chooseRenderEngineTypeViaSysProp() {
742 char prop[PROPERTY_VALUE_MAX];
743 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
744
745 if (strcmp(prop, "gles") == 0) {
746 return renderengine::RenderEngine::RenderEngineType::GLES;
747 } else if (strcmp(prop, "threaded") == 0) {
748 return renderengine::RenderEngine::RenderEngineType::THREADED;
749 } else if (strcmp(prop, "skiagl") == 0) {
750 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
751 } else if (strcmp(prop, "skiaglthreaded") == 0) {
752 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
753 } else {
754 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
755 return {};
756 }
757}
758
Wei Wangf9b05ee2017-07-19 20:59:39 -0700759// Do not call property_set on main thread which will be blocked by init
760// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700761void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700762 ALOGI( "SurfaceFlinger's main thread ready to run. "
763 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700764 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800765
Steven Thomasb02664d2017-07-26 18:48:28 -0700766 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700767 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800768 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500769 auto builder = renderengine::RenderEngineCreationArgs::Builder()
770 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
771 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
772 .setUseColorManagerment(useColorManagement)
773 .setEnableProtectedContext(enable_protected_contents(false))
774 .setPrecacheToneMapperShaderOnly(false)
775 .setSupportsBackgroundBlur(mSupportsBlur)
776 .setContextPriority(
777 useContextPriority
778 ? renderengine::RenderEngine::ContextPriority::REALTIME
779 : renderengine::RenderEngine::ContextPriority::MEDIUM);
780 if (auto type = chooseRenderEngineTypeViaSysProp()) {
781 builder.setRenderEngineType(type.value());
782 }
783 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700784 mMaxRenderTargetSize =
785 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700786
787 // Set SF main policy after initializing RenderEngine which has its own policy.
788 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
789 ALOGW("Failed to set main task profile");
790 }
791
Alec Mourie4034bb2019-11-19 12:45:54 -0800792 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700793 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800794 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000795 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800796
Ady Abraham9dada822022-02-03 10:26:59 -0800797 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
798
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800799 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
800 enableHalVirtualDisplays(true);
801 }
802
Lloyd Piqueba04e622017-12-14 17:11:26 -0800803 // Process any initial hotplug and resulting display changes.
804 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700805 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700806 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200807 const auto displayId = display->getPhysicalId();
808 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700809 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800810
Mathias Agopian92a979a2012-08-02 18:32:23 -0700811 // initialize our drawing state
812 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700813
Andy McFadden13a082e2012-08-24 10:16:42 -0700814 // set initial conditions (e.g. unblank default device)
815 initializeDisplays();
816
Xiang Wang839fe5b2022-04-04 17:39:38 +0000817 mPowerAdvisor->init();
Alec Mouridea1ac52021-06-23 18:12:18 -0700818
Steven Thomas137d4bc2019-07-25 16:55:14 -0700819 char primeShaderCache[PROPERTY_VALUE_MAX];
820 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
821 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700822 if (setSchedFifo(false) != NO_ERROR) {
823 ALOGW("Can't set SCHED_OTHER for primeCache");
824 }
825
826 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
827
828 if (setSchedFifo(true) != NO_ERROR) {
829 ALOGW("Can't set SCHED_OTHER for primeCache");
830 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700831 }
Dan Stoza4e637772016-07-28 13:31:51 -0700832
Ady Abrahamed3290f2021-05-17 15:12:14 -0700833 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400834
Wei Wangf9b05ee2017-07-19 20:59:39 -0700835 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700836
837 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800838 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700839 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700840
841 if (mStartPropertySetThread->Start() != NO_ERROR) {
842 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800843 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800844
Dan Stoza9e56aa02015-11-02 13:00:03 -0800845 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700846}
847
Romain Guy11d63f42017-07-20 12:47:14 -0700848void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700849 Mutex::Autolock _l(mStateLock);
850
Romain Guy11d63f42017-07-20 12:47:14 -0700851 char value[PROPERTY_VALUE_MAX];
852
853 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800854 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700855 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800856 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100857
858 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700859 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800860
861 property_get("persist.sys.sf.color_mode", value, "0");
862 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700863}
864
Mathias Agopiana67e4182012-06-19 17:26:12 -0700865void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800866 // Start boot animation service by setting a property mailbox
867 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700868 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800869 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700870 if (mStartPropertySetThread->join() != NO_ERROR) {
871 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800872 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700873}
874
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800875// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800876
Brian Anderson6b376712017-04-04 10:51:39 -0700877status_t SurfaceFlinger::getSupportedFrameTimestamps(
878 std::vector<FrameEvent>* outSupported) const {
879 *outSupported = {
880 FrameEvent::REQUESTED_PRESENT,
881 FrameEvent::ACQUIRE,
882 FrameEvent::LATCH,
883 FrameEvent::FIRST_REFRESH_START,
884 FrameEvent::LAST_REFRESH_START,
885 FrameEvent::GPU_COMPOSITION_DONE,
886 FrameEvent::DEQUEUE_READY,
887 FrameEvent::RELEASE,
888 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800889
890 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
891
Ady Abrahamde549d42022-01-26 19:19:17 -0800892 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700893 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
894 }
895 return NO_ERROR;
896}
897
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800898status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
899 if (!displayToken || !state) {
900 return BAD_VALUE;
901 }
902
903 Mutex::Autolock lock(mStateLock);
904
905 const auto display = getDisplayDeviceLocked(displayToken);
906 if (!display) {
907 return NAME_NOT_FOUND;
908 }
909
910 state->layerStack = display->getLayerStack();
911 state->orientation = display->getOrientation();
912
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200913 const Rect layerStackRect = display->getLayerStackSpaceRect();
914 state->layerStackSpaceRect =
915 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800916
917 return NO_ERROR;
918}
919
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100920status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
921 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800922 if (!displayToken || !info) {
923 return BAD_VALUE;
924 }
925
926 Mutex::Autolock lock(mStateLock);
927
928 const auto display = getDisplayDeviceLocked(displayToken);
929 if (!display) {
930 return NAME_NOT_FOUND;
931 }
932
Dominik Laskowski55c85402020-01-21 16:25:47 -0800933 if (const auto connectionType = display->getConnectionType())
934 info->connectionType = *connectionType;
935 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800936 return INVALID_OPERATION;
937 }
938
939 if (mEmulatedDisplayDensity) {
940 info->density = mEmulatedDisplayDensity;
941 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100942 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800943 ? mInternalDisplayDensity
944 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800945 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700946 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800947
948 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200949 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000950 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800951
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800952 return NO_ERROR;
953}
954
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100955status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
956 ui::DynamicDisplayInfo* info) {
957 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700958 return BAD_VALUE;
959 }
960
Dominik Laskowski22488f62019-03-28 09:53:04 -0700961 Mutex::Autolock lock(mStateLock);
962
Marin Shalamanov5801c942020-12-17 17:00:13 +0100963 const auto display = getDisplayDeviceLocked(displayToken);
964 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700965 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700966 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700967
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700968 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
969 if (!displayId) {
970 return INVALID_OPERATION;
971 }
972
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800973 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700974
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100975 const auto& supportedModes = display->getSupportedModes();
976 info->supportedDisplayModes.clear();
977 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800978
979 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100980 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800981 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700982
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800983 auto [width, height] = mode->getResolution();
984 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700985
ramindani06e518e2022-03-14 18:47:53 +0000986 if (const auto physicalOrientation = display->getPhysicalOrientation();
987 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800988 std::swap(width, height);
989 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700990 }
991
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100992 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800993
Huan Songf7eeb102022-03-28 11:02:38 -0700994 outMode.xDpi = xDpi;
995 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800996
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100997 const nsecs_t period = mode->getVsyncPeriod();
998 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800999
Ady Abraham8287e852020-08-12 14:44:58 -07001000 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001001 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001002 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1003 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1004 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001005
Andy McFadden91b2ca82014-06-13 14:04:23 -07001006 // This is how far in advance a buffer must be queued for
1007 // presentation at a given time. If you want a buffer to appear
1008 // on the screen at time N, you must submit the buffer before
1009 // (N - presentationDeadline).
1010 //
1011 // Normally it's one full refresh period (to give SF a chance to
1012 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001013 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001014 // composer or panel must be accounted for here.
1015 //
1016 // We add an additional 1ms to allow for processing time and
1017 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001018 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001019
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001020 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001021 }
1022
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001023 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001024 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001025 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001026
Marin Shalamanovb173f752021-02-16 19:38:36 +01001027 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001028 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001029 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001030 info->gameContentTypeSupported =
1031 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001032
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001033 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001034
1035 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001036 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1037 if (const auto modeId = display->translateModeId(*hwcId)) {
1038 info->preferredBootDisplayMode = modeId->value();
1039 }
1040 }
1041 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001042
Dan Stoza7f7da322014-05-02 15:26:25 -07001043 return NO_ERROR;
1044}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001045
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001046status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
1047 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001048 return BAD_VALUE;
1049 }
1050
Ady Abrahame90dd522020-12-29 12:08:45 -08001051 *stats = mScheduler->getDisplayStatInfo(systemTime());
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001052 return NO_ERROR;
1053}
1054
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001055void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001056 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001057
1058 if (!info.mode) {
1059 ALOGW("requested display mode is null");
1060 return;
1061 }
1062 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001063 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001064 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001065 return;
1066 }
1067
Ady Abraham690f4612021-07-01 23:24:03 -07001068 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001069 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001070
Alec Mouri754c98a2019-03-18 18:53:42 -07001071 // Start receiving vsync samples now, so that we can detect a period
1072 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001073 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001074 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001075 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001076 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001077
Ady Abraham690f4612021-07-01 23:24:03 -07001078 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001079 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001080 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001081}
1082
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001083status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001084 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001085
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001086 if (!displayToken) {
1087 return BAD_VALUE;
1088 }
Ady Abraham838de062019-02-04 10:24:03 -08001089
Dominik Laskowski756b7892021-08-04 12:53:59 -07001090 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001091 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001092 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001093 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001094 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001095 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001096 }
1097
1098 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001099 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001100 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001101 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001102
1103 const auto mode = display->getMode(DisplayModeId{modeId});
1104 if (!mode) {
1105 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1106 return BAD_VALUE;
1107 }
1108
1109 const auto fps = mode->getFps();
1110 // Keep the old switching type.
1111 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001112 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001113 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1114 allowGroupSwitching,
1115 {fps, fps}};
1116 constexpr bool kOverridePolicy = false;
1117
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001118 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001119 });
1120
1121 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001122}
1123
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001124void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001125 ATRACE_CALL();
1126
Dominik Laskowski22488f62019-03-28 09:53:04 -07001127 const auto display = getDefaultDisplayDeviceLocked();
1128 if (!display) {
1129 return;
1130 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001131
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001132 const auto upcomingModeInfo =
1133 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1134
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001135 if (!upcomingModeInfo.mode) {
1136 // There is no pending mode change. This can happen if the active
1137 // display changed and the mode change happened on a different display.
1138 return;
1139 }
1140
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001141 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001142 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1143 // We need to generate new sequenceId in order to recreate the display (and this
1144 // way the framebuffer).
1145 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001146 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001147 processDisplayChangesLocked();
1148
1149 // processDisplayChangesLocked will update all necessary components so we're done here.
1150 return;
1151 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001152
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001153 // We just created this display so we can call even if we are not on the main thread.
1154 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001155 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001156
Ady Abraham690f4612021-07-01 23:24:03 -07001157 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001158 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001159 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001160
Dominik Laskowski068173d2021-08-11 17:22:59 -07001161 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001162 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001163 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001164}
1165
Ady Abraham690f4612021-07-01 23:24:03 -07001166void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1167 display->clearDesiredActiveModeState();
1168 if (isDisplayActiveLocked(display)) {
1169 mScheduler->setModeChangePending(false);
1170 }
Ady Abraham53852a52019-05-28 18:07:44 -07001171}
1172
Ady Abraham690f4612021-07-01 23:24:03 -07001173void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1174 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1175 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001176 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001177 updatePhaseConfiguration(refreshRate);
1178}
1179
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001180void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001181 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001182
Marin Shalamanovdd594312021-11-09 16:37:37 +01001183 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1184
Ady Abraham690f4612021-07-01 23:24:03 -07001185 for (const auto& iter : mDisplays) {
1186 const auto& display = iter.second;
1187 if (!display || !display->isInternal()) {
1188 continue;
1189 }
1190
1191 // Store the local variable to release the lock.
1192 const auto desiredActiveMode = display->getDesiredActiveMode();
1193 if (!desiredActiveMode) {
1194 // No desired active mode pending to be applied
1195 continue;
1196 }
1197
1198 if (!isDisplayActiveLocked(display)) {
1199 // display is no longer the active display, so abort the mode change
1200 clearDesiredActiveModeState(display);
1201 continue;
1202 }
1203
1204 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1205 if (!desiredMode) {
1206 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1207 desiredActiveMode->mode->getId().value());
1208 clearDesiredActiveModeState(display);
1209 continue;
1210 }
1211
1212 const auto refreshRate = desiredMode->getFps();
1213 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1214 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1215 to_string(display->getId()).c_str());
1216
1217 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001218 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001219 desiredActiveModeChangeDone(display);
1220 continue;
1221 }
1222
1223 // Desired active mode was set, it is different than the mode currently in use, however
1224 // allowed modes might have changed by the time we process the refresh.
1225 // Make sure the desired mode is still allowed
1226 const auto displayModeAllowed =
1227 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1228 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001229 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001230 continue;
1231 }
1232
1233 // TODO(b/142753666) use constrains
1234 hal::VsyncPeriodChangeConstraints constraints;
1235 constraints.desiredTimeNanos = systemTime();
1236 constraints.seamlessRequired = false;
1237 hal::VsyncPeriodChangeTimeline outTimeline;
1238
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001239 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1240 display->initiateModeChange(*desiredActiveMode,
1241 constraints, &outTimeline));
1242
Ady Abraham690f4612021-07-01 23:24:03 -07001243 if (status != NO_ERROR) {
1244 // initiateModeChange may fail if a hotplug event is just about
1245 // to be sent. We just log the error in this case.
1246 ALOGW("initiateModeChange failed: %d", status);
1247 continue;
1248 }
1249 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1250
Marin Shalamanovdd594312021-11-09 16:37:37 +01001251 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001252 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001253 mSetActiveModePending = true;
1254 } else {
1255 // Updating the internal state should be done outside the loop,
1256 // because it can recreate a DisplayDevice and modify mDisplays
1257 // which will invalidate the iterator.
1258 displayToUpdateImmediately = display->getPhysicalId();
1259 }
1260 }
1261
1262 if (displayToUpdateImmediately) {
1263 updateInternalStateWithChangedMode();
1264
1265 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1266 const auto desiredActiveMode = display->getDesiredActiveMode();
1267 if (desiredActiveMode &&
1268 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1269 desiredActiveModeChangeDone(display);
1270 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001271 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001272}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001273
Alec Mouridea1ac52021-06-23 18:12:18 -07001274void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001275 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001276 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001277 ATRACE_NAME(whence);
Xiang Wang839fe5b2022-04-04 17:39:38 +00001278 if (mPowerAdvisor->isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001279 for (const auto& [_, display] : mDisplays) {
1280 constexpr bool kDisable = false;
Xiang Wang839fe5b2022-04-04 17:39:38 +00001281 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
Alec Mouridea1ac52021-06-23 18:12:18 -07001282 }
1283 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001284 });
1285
1286 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001287}
1288
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001289std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1290 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001291
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001292 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001293 // filter out all wide color modes. The typical reason why this happens is that the
1294 // hardware is not good enough to support GPU composition of wide color, and thus the
1295 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001296 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1297 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001298 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1299 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001300 }
Michael Wright28f24d02016-07-12 13:30:53 -07001301
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001302 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001303}
1304
Daniel Solomon42d04562019-01-20 21:03:19 -08001305status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1306 ui::DisplayPrimaries &primaries) {
1307 if (!displayToken) {
1308 return BAD_VALUE;
1309 }
1310
1311 // Currently we only support this API for a single internal display.
1312 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001313 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001314 }
1315
1316 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1317 return NO_ERROR;
1318}
1319
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001320status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001321 if (!displayToken) {
1322 return BAD_VALUE;
1323 }
1324
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001325 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001326 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001327 if (!display) {
1328 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1329 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001330 return NAME_NOT_FOUND;
1331 }
1332
1333 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001334 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1335 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001336 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001337 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001338
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001339 const auto modes = getDisplayColorModes(*display);
1340 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1341
1342 if (mode < ColorMode::NATIVE || !exists) {
1343 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1344 decodeColorMode(mode).c_str(), mode, displayToken.get());
1345 return BAD_VALUE;
1346 }
1347
1348 display->getCompositionDisplay()->setColorProfile(
1349 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1350
1351 return NO_ERROR;
1352 });
1353
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001354 // TODO(b/195698395): Propagate error.
1355 future.wait();
1356 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001357}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001358
Kriti Dang7defaf32021-11-15 11:55:43 +01001359status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001360 auto future = mScheduler->schedule(
1361 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1362
1363 *outSupport = future.get();
1364 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001365}
1366
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001367status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1368 ui::DisplayModeId modeId) {
1369 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001370 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001371 const auto display = getDisplayDeviceLocked(displayToken);
1372 if (!display) {
1373 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1374 return NAME_NOT_FOUND;
1375 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001376
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001377 if (display->isVirtual()) {
1378 ALOGE("%s: Invalid operation on virtual display", whence);
1379 return INVALID_OPERATION;
1380 }
1381
1382 const auto displayId = display->getPhysicalId();
1383 const auto mode = display->getMode(DisplayModeId{modeId});
1384 if (!mode) {
1385 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1386 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001387 return BAD_VALUE;
1388 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001389
1390 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001391 });
1392 return future.get();
1393}
1394
1395status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001396 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001397 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001398 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1399 return getHwComposer().clearBootDisplayMode(*displayId);
1400 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001401 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001402 return BAD_VALUE;
1403 }
1404 });
1405 return future.get();
1406}
1407
Galia Peycheva5492cb52019-10-30 14:13:16 +01001408void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001409 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001410 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001411 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1412 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1413 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001414 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001415 }
1416 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001417}
1418
Galia Peycheva5492cb52019-10-30 14:13:16 +01001419void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001420 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001421 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001422 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001423 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001424 getHwComposer().setContentType(*displayId, type);
1425 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001426 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001427 }
1428 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001429}
1430
Svetoslavd85084b2014-03-20 10:28:31 -07001431status_t SurfaceFlinger::clearAnimationFrameStats() {
1432 Mutex::Autolock _l(mStateLock);
1433 mAnimFrameTracker.clearStats();
1434 return NO_ERROR;
1435}
1436
1437status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1438 Mutex::Autolock _l(mStateLock);
1439 mAnimFrameTracker.getStats(outStats);
1440 return NO_ERROR;
1441}
1442
Kriti Dang49ad4132021-01-08 11:49:56 +01001443status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1444 const std::vector<ui::Hdr>& hdrTypes) {
1445 Mutex::Autolock lock(mStateLock);
1446
1447 auto display = getDisplayDeviceLocked(displayToken);
1448 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001449 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001450 return NAME_NOT_FOUND;
1451 }
1452
1453 display->overrideHdrTypes(hdrTypes);
1454 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1455 return NO_ERROR;
1456}
1457
Tej Singhe2751772021-04-06 22:05:29 -07001458status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1459 *success = mTimeStats->onPullAtom(atomId, pulledData);
1460 return NO_ERROR;
1461}
1462
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001463status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1464 ui::PixelFormat* outFormat,
1465 ui::Dataspace* outDataspace,
1466 uint8_t* outComponentMask) const {
1467 if (!outFormat || !outDataspace || !outComponentMask) {
1468 return BAD_VALUE;
1469 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001470
1471 Mutex::Autolock lock(mStateLock);
1472
1473 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1474 if (!displayId) {
1475 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001476 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001477
1478 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001479 outDataspace, outComponentMask);
1480}
1481
Kevin DuBois74e53772018-11-19 10:52:38 -08001482status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1483 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001484 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001485 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001486 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001487 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1488 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1489 componentMask, maxFrames);
1490 } else {
1491 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1492 return NAME_NOT_FOUND;
1493 }
1494 });
1495
1496 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001497}
1498
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001499status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1500 uint64_t maxFrames, uint64_t timestamp,
1501 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001502 Mutex::Autolock lock(mStateLock);
1503
1504 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1505 if (!displayId) {
1506 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001507 }
1508
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001509 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001510}
1511
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001512status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1513 if (!outSupported) {
1514 return BAD_VALUE;
1515 }
1516 *outSupported = getRenderEngine().supportsProtectedContent();
1517 return NO_ERROR;
1518}
1519
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001520status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1521 bool* outIsWideColorDisplay) const {
1522 if (!displayToken || !outIsWideColorDisplay) {
1523 return BAD_VALUE;
1524 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001525
1526 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001527 const auto display = getDisplayDeviceLocked(displayToken);
1528 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001529 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001530 }
Peiyong Linff84a152019-05-17 18:36:19 -07001531
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001532 *outIsWideColorDisplay =
1533 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001534 return NO_ERROR;
1535}
1536
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001537status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001538 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001539 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001540
Dominik Laskowski6505f792019-09-18 11:10:05 -07001541 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001542 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001543 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001544 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001545
Dominik Laskowski756b7892021-08-04 12:53:59 -07001546 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001547 return NO_ERROR;
1548}
1549
1550status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001551 Mutex::Autolock lock(mStateLock);
Ady Abrahame90dd522020-12-29 12:08:45 -08001552 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(when);
Ady Abraham56b42a42020-12-28 16:48:48 -08001553 const auto expectedPresent = calculateExpectedPresentTime(stats);
Ady Abraham9c53ee72020-07-22 21:16:18 -07001554 return mScheduler->injectVSync(when, /*expectedVSyncTime=*/expectedPresent,
1555 /*deadlineTimestamp=*/expectedPresent)
1556 ? NO_ERROR
1557 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001558}
1559
Huihong Luo05539a12022-02-23 10:29:40 -08001560status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001561 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001562 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001563 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001564 mDrawingState.traverseInZOrder([&](Layer* layer) {
1565 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1566 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001567 });
1568
1569 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001570 return NO_ERROR;
1571}
1572
Peiyong Linc6780972018-10-28 15:24:08 -07001573status_t SurfaceFlinger::getCompositionPreference(
1574 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1575 Dataspace* outWideColorGamutDataspace,
1576 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001577 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001578 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001579 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001580 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001581 return NO_ERROR;
1582}
1583
Dan Stozaec460082018-12-17 15:35:09 -08001584status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1585 const sp<IBinder>& stopLayerHandle,
1586 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001587 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001588 return BAD_VALUE;
1589 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001590
1591 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1592 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001593 return NO_ERROR;
1594}
1595
Dan Stozaec460082018-12-17 15:35:09 -08001596status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001597 if (!listener) {
1598 return BAD_VALUE;
1599 }
Dan Stozaec460082018-12-17 15:35:09 -08001600 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001601 return NO_ERROR;
1602}
Dan Gittik57e63c52019-01-18 16:37:54 +00001603
Alec Mouria9a68a62021-03-04 19:14:50 -08001604status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001605 if (!listener) {
1606 return BAD_VALUE;
1607 }
1608
Alec Mouria9a68a62021-03-04 19:14:50 -08001609 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001610 return NO_ERROR;
1611}
1612
1613status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1614 if (!listener) {
1615 return BAD_VALUE;
1616 }
1617 mFpsReporter->removeListener(listener);
1618 return NO_ERROR;
1619}
1620
Galia Peycheva8f04b302021-04-27 13:25:38 +02001621status_t SurfaceFlinger::addTunnelModeEnabledListener(
1622 const sp<gui::ITunnelModeEnabledListener>& listener) {
1623 if (!listener) {
1624 return BAD_VALUE;
1625 }
1626
1627 mTunnelModeEnabledReporter->addListener(listener);
1628 return NO_ERROR;
1629}
1630
1631status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1632 const sp<gui::ITunnelModeEnabledListener>& listener) {
1633 if (!listener) {
1634 return BAD_VALUE;
1635 }
1636
1637 mTunnelModeEnabledReporter->removeListener(listener);
1638 return NO_ERROR;
1639}
1640
Dan Gittik57e63c52019-01-18 16:37:54 +00001641status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1642 bool* outSupport) const {
1643 if (!displayToken || !outSupport) {
1644 return BAD_VALUE;
1645 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001646
1647 Mutex::Autolock lock(mStateLock);
1648
Dan Gittik57e63c52019-01-18 16:37:54 +00001649 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1650 if (!displayId) {
1651 return NAME_NOT_FOUND;
1652 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001653 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001654 return NO_ERROR;
1655}
1656
Alec Mouricdf16792021-12-10 13:16:06 -08001657bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1658 bool hasHdrLayers = false;
1659 mDrawingState.traverse([&,
1660 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1661 hasHdrLayers |= (layer->isVisible() &&
1662 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1663 isHdrDataspace(layer->getDataSpace()));
1664 });
1665 return hasHdrLayers;
1666}
1667
John Reck22be6962021-03-10 12:59:54 -05001668status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1669 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001670 if (!displayToken) {
1671 return BAD_VALUE;
1672 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001673
Dominik Laskowski756b7892021-08-04 12:53:59 -07001674 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001675 return ftl::chain(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001676 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001677 const bool supportsDisplayBrightnessCommand =
1678 getHwComposer().getComposer()->isSupported(
1679 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1680 // If we support applying display brightness as a command, then we also support
1681 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001682 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001683 auto compositionDisplay = display->getCompositionDisplay();
1684 float currentDimmingRatio =
1685 compositionDisplay->editState().sdrWhitePointNits /
1686 compositionDisplay->editState().displayBrightnessNits;
1687 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1688 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001689 FTL_FAKE_GUARD(kMainThreadContext,
1690 display->stageBrightness(brightness.displayBrightness));
1691
Alec Mouri6da0e272022-02-07 12:45:57 -08001692 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1693 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001694 scheduleComposite(FrameHint::kNone);
1695 } else {
1696 scheduleCommit(FrameHint::kNone);
1697 }
1698 return ftl::yield<status_t>(OK);
1699 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001700 return getHwComposer()
1701 .setDisplayBrightness(display->getPhysicalId(),
1702 brightness.displayBrightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00001703 brightness.displayBrightnessNits,
Alec Mouri90a19272021-12-30 14:11:38 -08001704 Hwc2::Composer::DisplayBrightnessOptions{
1705 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001706 }
Alec Mouricdf16792021-12-10 13:16:06 -08001707
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001708 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001709 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001710 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001711 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001712 }))
1713 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001714 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001715}
1716
John Reck88270902021-03-18 11:27:35 -04001717status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1718 const sp<gui::IHdrLayerInfoListener>& listener) {
1719 if (!displayToken) {
1720 return BAD_VALUE;
1721 }
1722
1723 Mutex::Autolock lock(mStateLock);
1724
1725 const auto display = getDisplayDeviceLocked(displayToken);
1726 if (!display) {
1727 return NAME_NOT_FOUND;
1728 }
1729 const auto displayId = display->getId();
1730 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1731 if (!hdrInfoReporter) {
1732 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1733 }
1734 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001735
1736
1737 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001738 return OK;
1739}
1740
1741status_t SurfaceFlinger::removeHdrLayerInfoListener(
1742 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1743 if (!displayToken) {
1744 return BAD_VALUE;
1745 }
1746
1747 Mutex::Autolock lock(mStateLock);
1748
1749 const auto display = getDisplayDeviceLocked(displayToken);
1750 if (!display) {
1751 return NAME_NOT_FOUND;
1752 }
1753 const auto displayId = display->getId();
1754 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1755 if (hdrInfoReporter) {
1756 hdrInfoReporter->removeListener(listener);
1757 }
1758 return OK;
1759}
1760
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001761status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001762 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001763 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001764
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001765 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001766 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001767 }
1768
1769 return NO_ERROR;
1770}
1771
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001772status_t SurfaceFlinger::getDisplayDecorationSupport(
1773 const sp<IBinder>& displayToken,
1774 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001775 if (!displayToken || !outSupport) {
1776 return BAD_VALUE;
1777 }
1778
1779 Mutex::Autolock lock(mStateLock);
1780
1781 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1782 if (!displayId) {
1783 return NAME_NOT_FOUND;
1784 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001785 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001786 return NO_ERROR;
1787}
1788
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001789// ----------------------------------------------------------------------------
1790
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001791sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham62f216c2020-10-13 19:07:23 -07001792 ISurfaceComposer::VsyncSource vsyncSource,
1793 ISurfaceComposer::EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001794 const auto& handle =
1795 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001796
Ady Abraham62f216c2020-10-13 19:07:23 -07001797 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001798}
1799
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001800void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001801 if (hint == FrameHint::kActive) {
1802 mScheduler->resetIdleTimer();
1803 }
Xiang Wang839fe5b2022-04-04 17:39:38 +00001804 mPowerAdvisor->notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001805 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001806}
1807
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001808void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1809 mMustComposite = true;
1810 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001811}
1812
1813void SurfaceFlinger::scheduleRepaint() {
1814 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001815 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001816}
1817
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001818void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001819 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001820}
1821
Ady Abraham2492a022020-07-24 11:09:55 -07001822nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001823 if (const auto display = getDefaultDisplayDeviceLocked()) {
1824 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001825 }
1826
Marin Shalamanov045b7002021-01-07 16:56:24 +01001827 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001828}
1829
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001830void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1831 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001832 const std::string tracePeriod = [vsyncPeriod]() {
1833 if (ATRACE_ENABLED() && vsyncPeriod) {
1834 std::stringstream ss;
1835 ss << "(" << *vsyncPeriod << ")";
1836 return ss.str();
1837 }
1838 return std::string();
1839 }();
1840 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001841
Steven Thomas3cfac282017-02-06 12:29:30 -08001842 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001843 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1844 if (displayId) {
1845 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1846 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001847 display->onVsync(timestamp);
1848 }
1849
Dominik Laskowski075d3172018-05-24 15:50:06 -07001850 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001851 return;
1852 }
1853
Ady Abrahame1166472021-07-15 10:56:06 -07001854 const bool isActiveDisplay =
1855 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1856 if (!isActiveDisplay) {
1857 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001858 return;
1859 }
1860
Alec Mourif8e689c2019-05-20 18:32:22 -07001861 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001862 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001863 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001864 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001865 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001866}
1867
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001868void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001869 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1870 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001871}
1872
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001873void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1874 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001875 const bool connected = connection == hal::Connection::CONNECTED;
1876 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001877
Steven Thomasb02664d2017-07-26 18:48:28 -07001878 // Only lock if we're not on the main thread. This function is normally
1879 // called on a hwbinder thread, but for the primary display it's called on
1880 // the main thread with the state lock already held, so don't attempt to
1881 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001882 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001883
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001884 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001885
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001886 if (std::this_thread::get_id() == mMainThreadId) {
1887 // Process all pending hot plug events immediately if we are on the main thread.
1888 processDisplayHotplugEventsLocked();
1889 }
1890
Lloyd Piqueba04e622017-12-14 17:11:26 -08001891 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001892}
1893
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001894void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1895 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001896 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001897 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001898
1899 if (timeline.refreshRequired) {
1900 scheduleComposite(FrameHint::kNone);
1901 }
Ady Abraham7159f572019-10-11 11:10:18 -07001902}
1903
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001904void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001905 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001906 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1907}
1908
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001909void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001910 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001911 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001912}
1913
Yichi Chen3401b562022-01-17 15:42:35 +08001914void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001915 ATRACE_CALL();
1916 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001917}
1918
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001919void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001920 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001921
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001922 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001923 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001924 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001925
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001926 if (const auto display = getDefaultDisplayDeviceLocked();
1927 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001928 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001929 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001930 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001931}
1932
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001933SurfaceFlinger::FenceWithFenceTime SurfaceFlinger::previousFrameFence() {
Ady Abrahamccf4b472021-05-11 19:53:01 -07001934 const auto now = systemTime();
1935 const auto vsyncPeriod = mScheduler->getDisplayStatInfo(now).vsyncPeriod;
1936 const bool expectedPresentTimeIsTheNextVsync = mExpectedPresentTime - now <= vsyncPeriod;
1937 return expectedPresentTimeIsTheNextVsync ? mPreviousPresentFences[0]
1938 : mPreviousPresentFences[1];
Alec Mouri6d414b52020-03-17 11:18:05 -07001939}
1940
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001941bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001942 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001943 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001944
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001945 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001946 return false;
1947 }
1948
Dan Stoza59083052020-04-28 10:13:20 -07001949 const status_t status = fence->wait(graceTimeMs);
1950 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1951 // which calls wait(0) again internally
1952 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001953}
1954
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001955nsecs_t SurfaceFlinger::previousFramePresentTime() {
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001956 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001957
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001958 if (fence == FenceTime::NO_FENCE) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001959 return Fence::SIGNAL_TIME_INVALID;
1960 }
1961
1962 return fence->getSignalTime();
1963}
1964
Ady Abraham56b42a42020-12-28 16:48:48 -08001965nsecs_t SurfaceFlinger::calculateExpectedPresentTime(DisplayStatInfo stats) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001966 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham8cb21882020-08-26 18:22:05 -07001967 return mVsyncModulator->getVsyncConfig().sfOffset > 0 ? stats.vsyncTime
1968 : stats.vsyncTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001969}
1970
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001971bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1972 FTL_FAKE_GUARD(kMainThreadContext) {
Matt Buckleyef51fba2021-10-12 19:30:12 +00001973 // we set this once at the beginning of commit to ensure consistency throughout the whole frame
Xiang Wang839fe5b2022-04-04 17:39:38 +00001974 mPowerHintSessionData.sessionEnabled = mPowerAdvisor->usePowerHintSession();
Matt Buckleyef51fba2021-10-12 19:30:12 +00001975 if (mPowerHintSessionData.sessionEnabled) {
1976 mPowerHintSessionData.commitStart = systemTime();
1977 }
1978
Dan Stoza28d46a52020-04-28 09:54:54 -07001979 // calculate the expected present time once and use the cached
1980 // value throughout this frame to make sure all layers are
1981 // seeing this same value.
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001982 if (expectedVsyncTime >= frameTime) {
1983 mExpectedPresentTime = expectedVsyncTime;
Snild Dolkow819636c2021-01-22 14:42:08 +01001984 } else {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001985 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(frameTime);
Snild Dolkow819636c2021-01-22 14:42:08 +01001986 mExpectedPresentTime = calculateExpectedPresentTime(stats);
1987 }
1988
1989 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001990 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07001991
Matt Buckleyef51fba2021-10-12 19:30:12 +00001992 if (mPowerHintSessionData.sessionEnabled) {
Xiang Wang839fe5b2022-04-04 17:39:38 +00001993 mPowerAdvisor->setTargetWorkDuration(mExpectedPresentTime -
1994 mPowerHintSessionData.commitStart);
Matt Buckleyef51fba2021-10-12 19:30:12 +00001995 }
Ady Abraham893c99d2021-04-30 16:00:23 -07001996 const auto vsyncIn = [&] {
1997 if (!ATRACE_ENABLED()) return 0.f;
1998 return (mExpectedPresentTime - systemTime()) / 1e6f;
1999 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002000 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
2001 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002002
Dan Stoza28d46a52020-04-28 09:54:54 -07002003 // When Backpressure propagation is enabled we want to give a small grace period
2004 // for the present fence to fire instead of just giving up on this frame to handle cases
2005 // where present fence is just about to get signaled.
2006 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002007 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002008
2009 // Pending frames may trigger backpressure propagation.
2010 const TracedOrdinal<bool> framePending = {"PrevFramePending",
2011 previousFramePending(graceTimeForPresentFenceMs)};
2012
2013 // Frame missed counts for metrics tracking.
2014 // A frame is missed if the prior frame is still pending. If no longer pending,
2015 // then we still count the frame as missed if the predicted present time
2016 // was further in the past than when the fence actually fired.
2017
2018 // Add some slop to correct for drift. This should generally be
2019 // smaller than a typical frame duration, but should not be so small
2020 // that it reports reasonable drift as a missed frame.
Ady Abrahame90dd522020-12-29 12:08:45 -08002021 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(systemTime());
Dan Stoza28d46a52020-04-28 09:54:54 -07002022 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
2023 const nsecs_t previousPresentTime = previousFramePresentTime();
2024 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2025 framePending ||
2026 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002027 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002028 previousPresentTime - frameMissedSlop))};
2029 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2030 mHadDeviceComposition && frameMissed};
2031 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2032 mHadClientComposition && frameMissed};
2033
2034 if (frameMissed) {
2035 mFrameMissedCount++;
2036 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002037 }
2038
2039 if (hwcFrameMissed) {
2040 mHwcFrameMissedCount++;
2041 }
2042
2043 if (gpuFrameMissed) {
2044 mGpuFrameMissedCount++;
2045 }
2046
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002047 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002048 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002049 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002050 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002051 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002052 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002053 }
2054
2055 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002056 // the mode, hence we update SF.
2057 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002058 {
2059 Mutex::Autolock lock(mStateLock);
2060 updateInternalStateWithChangedMode();
2061 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002062 }
2063
John Reck2ec53912020-07-07 16:53:55 -07002064 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002065 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002066 scheduleCommit(FrameHint::kNone);
2067 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002068 }
2069 }
2070
Dan Stoza28d46a52020-04-28 09:54:54 -07002071 if (mTracingEnabledChanged) {
Vishnu Nair7891e962021-11-11 12:07:21 -08002072 mLayerTracingEnabled = mLayerTracing.isEnabled();
Dan Stoza28d46a52020-04-28 09:54:54 -07002073 mTracingEnabledChanged = false;
2074 }
2075
Ady Abraham29d0da32020-07-16 18:39:33 -07002076 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002077 Mutex::Autolock lock(mStateLock);
2078 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002079 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002080 }
2081 }
2082
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002083 // Composite if transactions were committed, or if requested by HWC.
2084 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002085 {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002086 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(stats.vsyncPeriod));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002087
chaviw6b9ffea2021-11-08 09:25:48 -06002088 bool needsTraversal = false;
2089 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002090 needsTraversal |= commitCreatedLayers();
2091 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002092 }
2093
2094 const bool shouldCommit =
2095 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2096 if (shouldCommit) {
2097 commitTransactions();
2098 }
2099
2100 if (transactionFlushNeeded()) {
2101 setTransactionFlags(eTransactionFlushNeeded);
2102 }
2103
2104 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002105 mustComposite |= latchBuffers();
2106
chaviw6b9ffea2021-11-08 09:25:48 -06002107 // This has to be called after latchBuffers because we want to include the layers that have
2108 // been latched in the commit callback
2109 if (!needsTraversal) {
2110 // Invoke empty transaction callbacks early.
2111 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2112 } else {
2113 // Invoke OnCommit callbacks.
2114 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2115 }
2116
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002117 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002118 }
2119
2120 // Layers need to get updated (in the previous line) before we can use them for
2121 // choosing the refresh rate.
2122 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2123 // and may eventually call to ~Layer() if it holds the last reference
2124 {
2125 Mutex::Autolock _l(mStateLock);
2126 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002127 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002128 }
2129
Dan Stoza28d46a52020-04-28 09:54:54 -07002130 updateCursorAsync();
2131 updateInputFlinger();
2132
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002133 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2134 // This will block and tracing should only be enabled for debugging.
2135 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
2136 }
2137
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002138 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002139
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002140 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002141}
2142
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002143void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2144 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002145 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002146
Matt Buckleyef51fba2021-10-12 19:30:12 +00002147 if (mPowerHintSessionData.sessionEnabled) {
2148 mPowerHintSessionData.compositeStart = systemTime();
2149 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07002150
Lloyd Piqueab039b52019-02-13 14:22:42 -08002151 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002152 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002153 refreshArgs.outputs.reserve(displays.size());
2154 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002155 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2156 }
2157 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002158 if (auto layerFE = layer->getCompositionEngineLayerFE())
2159 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002160 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002161 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002162 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002163 if (auto layerFE = layer->getCompositionEngineLayerFE())
2164 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002165 }
2166
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002167 refreshArgs.outputColorSetting = useColorManagement
2168 ? mDisplayColorSetting
2169 : compositionengine::OutputColorSetting::kUnmanaged;
2170 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2171 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002172
2173 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002174 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002175 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002176 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002177
2178 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2179 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2180 mDrawingState.colorMatrixChanged = false;
2181 }
2182
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002183 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002184
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002185 if (mDebugFlashDelay != 0) {
2186 refreshArgs.devOptForceClientComposition = true;
2187 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002188 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002189
Ady Abraham43065bd2021-12-10 17:22:15 -08002190 const auto expectedPresentTime = mExpectedPresentTime.load();
2191 const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
Ady Abrahamcaba2982021-06-16 16:45:04 -07002192 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2193 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002194 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002195 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002196 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002197
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002198 // Store the present time just before calling to the composition engine so we could notify
2199 // the scheduler.
2200 const auto presentTime = systemTime();
2201
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002202 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002203
2204 if (mPowerHintSessionData.sessionEnabled) {
2205 mPowerHintSessionData.presentEnd = systemTime();
2206 }
2207
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002208 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002209
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002210 if (mScheduler->onPostComposition(presentTime)) {
2211 scheduleComposite(FrameHint::kNone);
2212 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002213
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002214 postFrame();
2215 postComposition();
2216
Midas Chien50f52e22020-09-26 17:57:42 +08002217 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002218
Vishnu Nair9cf89262022-02-26 09:17:49 -08002219 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2220 TimeStats::ClientCompositionRecord clientCompositionRecord;
2221 for (const auto& [_, display] : displays) {
2222 const auto& state = display->getCompositionDisplay()->getState();
2223 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2224 mHadDeviceComposition |= state.usesDeviceComposition;
2225 mReusedClientComposition |= state.reusedClientComposition;
2226 clientCompositionRecord.predicted |=
2227 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2228 clientCompositionRecord.predictionSucceeded |=
2229 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002230 }
2231
Vishnu Nair9cf89262022-02-26 09:17:49 -08002232 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2233 clientCompositionRecord.reused = mReusedClientComposition;
2234 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2235 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2236
Yichi Chen28dee2c2020-07-06 21:24:14 +08002237 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002238 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2239 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002240
David Sodman7e4ae112018-02-09 15:02:28 -08002241 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002242 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002243 // This will block and should only be used for debugging.
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002244 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
Vishnu Nairdf529052019-06-07 14:53:14 -07002245 }
Robert Carr167bdde2021-07-28 11:26:51 -07002246
2247 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002248 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002249
2250 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002251 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002252 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002253
2254 // calculate total render time for performance hinting if adpf cpu hint is enabled,
2255 if (mPowerHintSessionData.sessionEnabled) {
2256 const nsecs_t flingerDuration =
2257 (mPowerHintSessionData.presentEnd - mPowerHintSessionData.commitStart);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002258 mPowerAdvisor->sendActualWorkDuration(flingerDuration, mPowerHintSessionData.presentEnd);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002259 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002260}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002261
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002262void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002263 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002264
Vishnu Nair4351ad52019-02-11 14:13:02 -08002265 if (mVisibleRegionsDirty) {
2266 computeLayerBounds();
2267 }
2268
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002269 for (auto& layer : mLayersPendingRefresh) {
2270 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002271 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002272 invalidateLayerStack(layer, visibleReg);
2273 }
2274 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002275}
2276
Ana Krulece588e312018-09-18 12:32:24 -07002277void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2278 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002279 // Update queue of past composite+present times and determine the
2280 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002281 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002282 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002283 while (!getBE().mCompositePresentTimes.empty()) {
2284 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002285 // Cached values should have been updated before calling this method,
2286 // which helps avoid duplicate syscalls.
2287 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2288 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2289 break;
2290 }
2291 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002292 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002293 }
2294
2295 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002296 while (getBE().mCompositePresentTimes.size() > 16) {
2297 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002298 }
2299
Ana Krulece588e312018-09-18 12:32:24 -07002300 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002301}
2302
Ana Krulece588e312018-09-18 12:32:24 -07002303void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2304 nsecs_t compositeToPresentLatency) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002305 // Avoid division by 0 by defaulting to 60Hz
2306 const auto vsyncPeriod = stats.vsyncPeriod ?: (60_Hz).getPeriodNsecs();
2307
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002308 // Integer division and modulo round toward 0 not -inf, so we need to
2309 // treat negative and positive offsets differently.
Ady Abraham8287e852020-08-12 14:44:58 -07002310 nsecs_t idealLatency = (mVsyncConfiguration->getCurrentConfigs().late.sfOffset > 0)
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002311 ? (vsyncPeriod -
2312 (mVsyncConfiguration->getCurrentConfigs().late.sfOffset % vsyncPeriod))
2313 : ((-mVsyncConfiguration->getCurrentConfigs().late.sfOffset) % vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002314
Ady Abraham8287e852020-08-12 14:44:58 -07002315 // Just in case mVsyncConfiguration->getCurrentConfigs().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002316 if (idealLatency <= 0) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002317 idealLatency = vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002318 }
2319
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002320 // Snap the latency to a value that removes scheduling jitter from the
2321 // composition and present times, which often have >1ms of jitter.
2322 // Reducing jitter is important if an app attempts to extrapolate
2323 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002324 // Snapping also allows an app to precisely calculate
Ady Abraham8287e852020-08-12 14:44:58 -07002325 // mVsyncConfiguration->getCurrentConfigs().late.sf with (presentLatency % interval).
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002326 const nsecs_t bias = vsyncPeriod / 2;
2327 const int64_t extraVsyncs = ((compositeToPresentLatency - idealLatency + bias) / vsyncPeriod);
Ady Abraham8d7e7842022-02-03 01:42:45 +00002328 const nsecs_t snappedCompositeToPresentLatency =
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002329 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002330
David Sodman99974d22017-11-28 12:04:33 -08002331 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002332 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002333 getBE().mCompositorTiming.interval = vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002334 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002335}
2336
John Reck49d9ad32022-02-23 19:03:31 -05002337bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
2338 if (!isHdrDataspace(layer->getDataSpace())) {
2339 return false;
2340 }
2341 if (mIgnoreHdrCameraLayers) {
2342 auto buffer = layer->getBuffer();
2343 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2344 return false;
2345 }
2346 }
2347 return true;
2348}
2349
ramindani06e518e2022-03-14 18:47:53 +00002350ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2351 bool isPrimary) const {
2352 const auto id = PhysicalDisplayId::tryCast(displayId);
2353 if (!id) {
2354 return ui::ROTATION_0;
2355 }
2356 if (getHwComposer().getComposer()->isSupported(
2357 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2358 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2359 case Hwc2::AidlTransform::ROT_90:
2360 return ui::ROTATION_90;
2361 case Hwc2::AidlTransform::ROT_180:
2362 return ui::ROTATION_180;
2363 case Hwc2::AidlTransform::ROT_270:
2364 return ui::ROTATION_270;
2365 default:
2366 return ui::ROTATION_0;
2367 }
2368 }
2369
2370 if (isPrimary) {
2371 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2372 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2373 case Values::ORIENTATION_90:
2374 return ui::ROTATION_90;
2375 case Values::ORIENTATION_180:
2376 return ui::ROTATION_180;
2377 case Values::ORIENTATION_270:
2378 return ui::ROTATION_270;
2379 default:
2380 break;
2381 }
2382 }
2383 return ui::ROTATION_0;
2384}
2385
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002386void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002387 ATRACE_CALL();
2388 ALOGV("postComposition");
2389
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002390 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002391
David Sodman73beded2017-11-15 11:56:06 -08002392 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002393 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002394 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002395 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002396 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002397 ->getRenderSurface()
2398 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002399 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002400 } else {
2401 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2402 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002403
David Sodman73beded2017-11-15 11:56:06 -08002404 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002405 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002406 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002407 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002408 mPreviousPresentFences[0].fenceTime =
2409 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2410
2411 getBE().mDisplayTimeline.push(mPreviousPresentFences[0].fenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002412
Vishnu Nair9a69a042021-06-18 13:19:49 -07002413 nsecs_t now = systemTime();
2414
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002415 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2416 // information from previous' frame classification is already available when sending jank info
2417 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002418 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002419 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002420
Vishnu Nair9a69a042021-06-18 13:19:49 -07002421 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002422
Lloyd Piqueab039b52019-02-13 14:22:42 -08002423 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2424 // be sampled a little later than when we started doing work for this frame,
2425 // but that should be okay since updateCompositorTiming has snapping logic.
2426 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002427 mPreviousPresentFences[0].fenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002428 CompositorTiming compositorTiming;
2429 {
David Sodman99974d22017-11-28 12:04:33 -08002430 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2431 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002432 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002433
Robert Carrc747ad02021-06-11 14:01:24 -07002434 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002435 layer->onPostComposition(display, glCompositionDoneFenceTime,
2436 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002437 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002438 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002439
John Reck88270902021-03-18 11:27:35 -04002440 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2441 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002442 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002443 {
2444 Mutex::Autolock lock(mStateLock);
2445 if (mFpsReporter) {
2446 mFpsReporter->dispatchLayerFps();
2447 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002448
2449 if (mTunnelModeEnabledReporter) {
2450 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2451 }
John Reck88270902021-03-18 11:27:35 -04002452 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002453 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2454 if (reporter && reporter->hasListeners()) {
2455 if (const auto display = getDisplayDeviceLocked(displayId)) {
2456 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002457 }
2458 }
2459 }
Robert Carr167bdde2021-07-28 11:26:51 -07002460 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2461 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002462 }
2463
Robert Carr167bdde2021-07-28 11:26:51 -07002464 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2465 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2466 HdrLayerInfoReporter::HdrLayerInfo info;
2467 int32_t maxArea = 0;
2468 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2469 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002470 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002471 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002472 const auto* outputLayer =
2473 compositionDisplay->getOutputLayerForLayer(layerFe);
2474 if (outputLayer) {
2475 info.numberOfHdrLayers++;
2476 const auto displayFrame = outputLayer->getState().displayFrame;
2477 const int32_t area = displayFrame.width() * displayFrame.height();
2478 if (area > maxArea) {
2479 maxArea = area;
2480 info.maxW = displayFrame.width();
2481 info.maxH = displayFrame.height();
2482 }
John Reckdb1a16b2021-07-09 13:05:52 -04002483 }
John Reck88270902021-03-18 11:27:35 -04002484 }
2485 }
Robert Carr167bdde2021-07-28 11:26:51 -07002486 });
2487 listener->dispatchHdrLayerInfo(info);
2488 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002489 }
2490
Robert Carr167bdde2021-07-28 11:26:51 -07002491 mSomeDataspaceChanged = false;
2492 mVisibleRegionsWereDirtyThisFrame = false;
2493
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002494 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002495 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002496 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002497
Ady Abrahamed3290f2021-05-17 15:12:14 -07002498 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002499 mPreviousPresentFences[0].fenceTime->isValid()) {
2500 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002501 }
2502
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002503 const bool isDisplayConnected =
2504 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002505
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002506 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002507 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002508 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002509 }
2510 }
2511
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002512 if (mAnimCompositionPending) {
2513 mAnimCompositionPending = false;
2514
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002515 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2516 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002517 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002518 // The HWC doesn't support present fences, so use the refresh
2519 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002520 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002521 mAnimFrameTracker.setActualPresentTime(presentTime);
2522 }
2523 mAnimFrameTracker.advanceFrame();
2524 }
Dan Stozab90cf072015-03-05 11:05:59 -08002525
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002526 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002527
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002528 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002529
Alec Mouri717bcb62020-02-10 17:07:19 -08002530 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2531 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2532 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2533
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002534 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002535 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002536 return;
2537 }
2538
2539 nsecs_t currentTime = systemTime();
2540 if (mHasPoweredOff) {
2541 mHasPoweredOff = false;
2542 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002543 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002544 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002545 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2546 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002547 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002548 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002549 }
David Sodman4a36e932017-11-07 14:29:47 -08002550 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002551 }
David Sodman4a36e932017-11-07 14:29:47 -08002552 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002553
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002554 // Cleanup any outstanding resources due to rendering a prior frame.
2555 getRenderEngine().cleanupPostRender();
2556
Dan Stoza436ccf32018-06-21 12:10:12 -07002557 {
2558 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002559 if (mTexturePool.size() < mTexturePoolSize) {
2560 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002561 const size_t offset = mTexturePool.size();
2562 mTexturePool.resize(mTexturePoolSize);
2563 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2564 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002565 } else if (mTexturePool.size() > mTexturePoolSize) {
2566 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2567 const size_t offset = mTexturePoolSize;
2568 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2569 mTexturePool.resize(mTexturePoolSize);
2570 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002571 }
2572 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002573
Dan Stoza45de5ba2019-04-25 14:12:09 -07002574 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2575 // side-effect of getTotalSize(), so we check that again here
2576 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002577 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002578 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2579 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002580}
2581
chaviw79468ab2021-10-27 11:11:24 -05002582FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002583 const ui::Size maxSize = [this] {
2584 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002585
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002586 // The LayerTraceGenerator tool runs without displays.
2587 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002588
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002589 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2590 [](ui::Size size, const auto& pair) -> ui::Size {
2591 const auto& display = pair.second;
2592 return {std::max(size.getWidth(), display->getWidth()),
2593 std::max(size.getHeight(), display->getHeight())};
2594 });
2595 }();
chaviwb09c6552021-08-12 17:20:43 -05002596
2597 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2598 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002599 const float xMax = maxSize.getWidth() * 10.f;
2600 const float yMax = maxSize.getHeight() * 10.f;
2601
2602 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002603}
2604
2605void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002606 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002607 for (const auto& layer : mDrawingState.layersSortedByZ) {
2608 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002609 }
2610}
2611
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002612void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002613 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002614 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002616 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2617 logFrameStats();
2618 }
2619 }
2620}
2621
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002622void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002623 ATRACE_CALL();
2624
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002625 // Keep a copy of the drawing state (that is going to be overwritten
2626 // by commitTransactionsLocked) outside of mStateLock so that the side
2627 // effects of the State assignment don't happen with mStateLock held,
2628 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002629 State drawingState(mDrawingState);
2630
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002631 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002632 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633
Mathias Agopianca4d3602011-05-19 15:38:14 -07002634 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002635 // so we can call commitTransactionsLocked unconditionally.
2636 // We clear the flags with mStateLock held to guarantee that
2637 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002638 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002639 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002640
Mathias Agopianca4d3602011-05-19 15:38:14 -07002641 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002642}
2643
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002644std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2645 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002646 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2647 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002648
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002649 int attempt = 0;
2650 constexpr int kMaxAttempts = 3;
2651 do {
2652 hwcModes = getHwComposer().getModes(displayId);
2653 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2654 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2655
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002656 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2657 return mode.hwcId == *activeModeHwcId;
2658 };
2659
2660 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2661 break;
2662 }
2663 } while (++attempt < kMaxAttempts);
2664
2665 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002666 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002667 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002668 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002669
2670 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002671 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2672 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002673 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002674
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002675 ui::DisplayModeId nextModeId = 1 +
2676 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2677 [](ui::DisplayModeId max, const auto& pair) {
2678 return std::max(max, pair.first.value());
2679 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002680
2681 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002682 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002683 const DisplayModeId id{nextModeId++};
2684 newModes.try_emplace(id,
2685 DisplayMode::Builder(hwcMode.hwcId)
2686 .setId(id)
2687 .setPhysicalDisplayId(displayId)
2688 .setResolution({hwcMode.width, hwcMode.height})
2689 .setVsyncPeriod(hwcMode.vsyncPeriod)
2690 .setDpiX(hwcMode.dpiX)
2691 .setDpiY(hwcMode.dpiY)
2692 .setGroup(hwcMode.configGroup)
2693 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002694 }
2695
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002696 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002697 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002698 [](const auto& lhs, const auto& rhs) {
2699 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002700 });
2701
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002702 // Keep IDs if modes have not changed.
2703 const auto& modes = sameModes ? oldModes : newModes;
2704 const DisplayModePtr activeMode =
2705 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2706 return pair.second->getHwcId() == activeModeHwcId;
2707 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002708
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002709 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002710}
2711
Lloyd Piqueba04e622017-12-14 17:11:26 -08002712void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2713 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002714 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002715 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002716
Dominik Laskowski075d3172018-05-24 15:50:06 -07002717 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002718 continue;
2719 }
2720
Marin Shalamanova524a092020-07-27 21:39:55 +02002721 const auto displayId = info->id;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002722 const auto it = mPhysicalDisplayTokens.find(displayId);
2723
Peiyong Line9d809e2020-04-14 13:10:48 -07002724 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002725 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002726
Dominik Laskowski55c85402020-01-21 16:25:47 -08002727 if (it == mPhysicalDisplayTokens.end()) {
2728 ALOGV("Creating display %s", to_string(displayId).c_str());
2729
Dominik Laskowski075d3172018-05-24 15:50:06 -07002730 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002731 state.physical = {.id = displayId,
2732 .type = getHwComposer().getDisplayConnectionType(displayId),
2733 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002734 .deviceProductInfo = std::move(info->deviceProductInfo),
2735 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002736 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002737 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002738 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002739
2740 sp<IBinder> token = new BBinder();
2741 mCurrentState.displays.add(token, state);
2742 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002743 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002744 } else {
2745 ALOGV("Recreating display %s", to_string(displayId).c_str());
2746
2747 const auto token = it->second;
2748 auto& state = mCurrentState.displays.editValueFor(token);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002749 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId
Marin Shalamanova903d032020-12-29 20:35:13 +01002750 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002751 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002752 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2753 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2754 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002755 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002756 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002757 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002758
Dominik Laskowski55c85402020-01-21 16:25:47 -08002759 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002760 if (index >= 0) {
2761 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2762 mInterceptor->saveDisplayDeletion(state.sequenceId);
2763 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002764 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002765 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002766 }
2767
2768 processDisplayChangesLocked();
2769 }
2770
2771 mPendingHotplugEvents.clear();
2772}
2773
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002774void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002775 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2776 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002777 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2778 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002779}
2780
Lloyd Pique99d3da52018-01-22 17:48:03 -08002781sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002782 const wp<IBinder>& displayToken,
2783 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002784 const DisplayDeviceState& state,
2785 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002786 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002787 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002788 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002789 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002790 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002791 creationArgs.hasWideColorGamut = false;
2792 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002793
Dominik Laskowski55c85402020-01-21 16:25:47 -08002794 if (const auto& physical = state.physical) {
2795 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002796 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002797 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002798 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2799 getKernelIdleTimerProperties(compositionDisplay->getId());
2800
Ady Abraham3efa3942021-06-24 19:01:25 -07002801 scheduler::RefreshRateConfigs::Config config =
2802 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2803 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002804 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002805 .idleTimerTimeout = idleTimerTimeoutMs,
2806 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002807 creationArgs.refreshRateConfigs =
2808 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2809 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002810 }
2811
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002812 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
2813 creationArgs.isPrimary = id == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002814
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002815 if (useColorManagement) {
2816 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2817 for (ColorMode colorMode : modes) {
2818 if (isWideColorMode(colorMode)) {
2819 creationArgs.hasWideColorGamut = true;
2820 }
2821
2822 std::vector<RenderIntent> renderIntents =
2823 getHwComposer().getRenderIntents(*id, colorMode);
2824 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002825 }
2826 }
tangrobin6753a022018-08-10 10:58:54 +08002827 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002828
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002829 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2830 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2831 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002832 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002833
Lloyd Pique90c115d2018-09-18 21:39:42 -07002834 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002835 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002836 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002837
Lloyd Pique99d3da52018-01-22 17:48:03 -08002838 // Make sure that composition can never be stalled by a virtual display
2839 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002840 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002841 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002842 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2843 }
2844
Dominik Laskowski718f9602019-11-09 20:01:35 -08002845 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002846 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2847 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002848
Lloyd Pique99d3da52018-01-22 17:48:03 -08002849 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002850 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002851
Lloyd Pique9370a482019-10-03 17:58:30 -07002852 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002853
Ady Abraham8565ad22021-06-22 17:45:44 -07002854 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002855
2856 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002857 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002858 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002859 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002860 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002861 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002862 display->getCompositionDisplay()->setColorProfile(
2863 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2864 RenderIntent::COLORIMETRIC,
2865 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002866 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002867 FTL_FAKE_GUARD(kMainThreadContext,
2868 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002869 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002870 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002871
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002872 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002873 display->setProjection(state.orientation, state.layerStackSpaceRect,
2874 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002875 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002876 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002877
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002878 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002879}
2880
Marin Shalamanovae685592020-02-12 17:12:22 +01002881void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2882 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002883 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002884 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2885 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002886 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002887 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2888 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002889 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002890 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002891 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002892 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002893 int format;
2894 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002895 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002896 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002897 } else {
2898 // Virtual displays without a surface are dormant:
2899 // they have external state (layer stack, projection,
2900 // etc.) but no internal state (i.e. a DisplayDevice).
2901 return;
2902 }
2903
2904 compositionengine::DisplayCreationArgsBuilder builder;
2905 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002906 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002907 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002908 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002909 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002910
Marin Shalamanov045b7002021-01-07 16:56:24 +01002911 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002912 builder.setIsSecure(state.isSecure);
Xiang Wang839fe5b2022-04-04 17:39:38 +00002913 builder.setPowerAdvisor(mPowerAdvisor.get());
Marin Shalamanovae685592020-02-12 17:12:22 +01002914 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002915 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002916 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002917
2918 sp<compositionengine::DisplaySurface> displaySurface;
2919 sp<IGraphicBufferProducer> producer;
2920 sp<IGraphicBufferProducer> bqProducer;
2921 sp<IGraphicBufferConsumer> bqConsumer;
2922 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2923
Marin Shalamanovae685592020-02-12 17:12:22 +01002924 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002925 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2926 LOG_FATAL_IF(!displayId);
2927 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2928 bqProducer, bqConsumer, state.displayName);
2929 displaySurface = surface;
2930 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002931 } else {
2932 ALOGE_IF(state.surface != nullptr,
2933 "adding a supported display, but rendering "
2934 "surface is provided (%p), ignoring it",
2935 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002936 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2937 LOG_FATAL_IF(!displayId);
2938 displaySurface =
2939 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002940 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002941 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002942 producer = bqProducer;
2943 }
2944
Marin Shalamanov700e6392020-02-12 20:22:26 +01002945 LOG_FATAL_IF(!displaySurface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002946 const auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay),
2947 state, displaySurface, producer);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002948 mDisplays.emplace(displayToken, display);
Ady Abraham3efa3942021-06-24 19:01:25 -07002949 if (display->isPrimary()) {
2950 initScheduler(display);
2951 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002952 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002953 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002954 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002955}
2956
2957void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002958 auto display = getDisplayDeviceLocked(displayToken);
2959 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002960 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002961
2962 if (display->isVirtual()) {
2963 releaseVirtualDisplay(display->getVirtualId());
2964 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002965 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01002966 }
2967 }
2968
2969 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08002970
2971 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002972 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002973 // Destroy the display without holding the mStateLock.
2974 // This is a temporary solution until we can manage transaction queues without
2975 // holding the mStateLock.
2976 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
2977 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
2978 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
2979 // ends up running on the main thread causing a deadlock since setTransactionstate
2980 // will try to acquire the mStateLock. Instead we extend the lifetime of
2981 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
2982 // The display will be disconnected and removed from the mDisplays list so it will
2983 // not be accessible.
2984 }));
2985 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002986}
2987
2988void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2989 const DisplayDeviceState& currentState,
2990 const DisplayDeviceState& drawingState) {
2991 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2992 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002993
2994 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01002995 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02002996 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002997
Marin Shalamanovae685592020-02-12 17:12:22 +01002998 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2999 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003000 if (display->isVirtual()) {
3001 releaseVirtualDisplay(display->getVirtualId());
3002 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003003 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003004
Marin Shalamanovae685592020-02-12 17:12:22 +01003005 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003006
Marin Shalamanov700e6392020-02-12 20:22:26 +01003007 if (const auto& physical = currentState.physical) {
3008 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3009 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003010
Marin Shalamanovae685592020-02-12 17:12:22 +01003011 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003012
Marin Shalamanov700e6392020-02-12 20:22:26 +01003013 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003014 const auto display = getDisplayDeviceLocked(displayToken);
3015 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003016
3017 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003018 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003019 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003020 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003021 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003022 return;
3023 }
3024
3025 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3026 if (currentState.layerStack != drawingState.layerStack) {
3027 display->setLayerStack(currentState.layerStack);
3028 }
Evan Rosky2239b372021-05-20 13:43:47 -07003029 if (currentState.flags != drawingState.flags) {
3030 display->setFlags(currentState.flags);
3031 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003032 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003033 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3034 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3035 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3036 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003037 if (isDisplayActiveLocked(display)) {
3038 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003039 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003040 }
3041 if (currentState.width != drawingState.width ||
3042 currentState.height != drawingState.height) {
3043 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003044
Ady Abrahamed3290f2021-05-17 15:12:14 -07003045 if (isDisplayActiveLocked(display)) {
3046 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003047 }
3048 }
3049 }
3050}
Ady Abraham3efa3942021-06-24 19:01:25 -07003051void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003052 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003053 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003054 updatePhaseConfiguration(refreshRate);
3055 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003056}
Marin Shalamanovae685592020-02-12 17:12:22 +01003057
Lloyd Pique347200f2017-12-14 17:00:15 -08003058void SurfaceFlinger::processDisplayChangesLocked() {
3059 // here we take advantage of Vector's copy-on-write semantics to
3060 // improve performance by skipping the transaction entirely when
3061 // know that the lists are identical
3062 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3063 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3064 if (!curr.isIdenticalTo(draw)) {
3065 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003066
3067 // find the displays that were removed
3068 // (ie: in drawing state but not in current state)
3069 // also handle displays that changed
3070 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003071 for (size_t i = 0; i < draw.size(); i++) {
3072 const wp<IBinder>& displayToken = draw.keyAt(i);
3073 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003074 if (j < 0) {
3075 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003076 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003077 } else {
3078 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003079 const DisplayDeviceState& currentState = curr[j];
3080 const DisplayDeviceState& drawingState = draw[i];
3081 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003082 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003083 }
3084
3085 // find displays that were added
3086 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003087 for (size_t i = 0; i < curr.size(); i++) {
3088 const wp<IBinder>& displayToken = curr.keyAt(i);
3089 if (draw.indexOfKey(displayToken) < 0) {
3090 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003091 }
3092 }
3093 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003094
3095 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003096}
3097
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003098void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3099 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003100 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3101 if (displayTransactionNeeded) {
3102 processDisplayChangesLocked();
3103 processDisplayHotplugEventsLocked();
3104 }
Robert Carrb552ff52021-06-11 13:35:54 -07003105 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106
Robert Carre450fb52021-06-11 13:21:09 -07003107 if (mSomeChildrenChanged) {
3108 mVisibleRegionsDirty = true;
3109 mSomeChildrenChanged = false;
3110 }
3111
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003112 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003113 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003114 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003115 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003116 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003117 // the hint is set before we acquire a buffer from the surface texture.
3118 //
3119 // NOTE: layer transactions have taken place already, so we use their
3120 // drawing state. However, SurfaceFlinger's own transaction has not
3121 // happened yet, so we must use the current state layer list
3122 // (soon to become the drawing state list).
3123 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003124 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003125 ui::LayerStack layerStack;
3126
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003127 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003128 // NOTE: we rely on the fact that layers are sorted by
3129 // layerStack first (so we don't have to traverse the list
3130 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003131 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3132 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003133 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003134
3135 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003136 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003137 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3138 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003139 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003140
3141 // Pick the primary display if another display mirrors the layer.
3142 if (hintDisplay) {
3143 hintDisplay = nullptr;
3144 break;
3145 }
3146
3147 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003148 }
3149 }
Chet Haase91d25932013-04-11 15:24:55 -07003150
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003151 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003152 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3153 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003154
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003155 // could be null when this layer is using a layerStack
3156 // that is not visible on any display. Also can occur at
3157 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003158 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003159 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003160
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003161 layer->updateTransformHint(hintDisplay->getTransformHint());
Robert Carr2047fae2016-11-28 14:09:09 -08003162 });
Mathias Agopian84300952012-11-21 16:02:13 -08003163 }
3164
Robert Carr1f0a16a2016-10-24 16:27:39 -07003165 if (mLayersAdded) {
3166 mLayersAdded = false;
3167 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003168 mVisibleRegionsDirty = true;
3169 }
3170
3171 // some layers might have been removed, so
3172 // we need to update the regions they're exposing.
3173 if (mLayersRemoved) {
3174 mLayersRemoved = false;
3175 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003176 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003177 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003178 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003179 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003180 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003181 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003182 }
Robert Carr2047fae2016-11-28 14:09:09 -08003183 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184 }
3185
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003186 doCommitTransactions();
3187 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3188 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003189}
3190
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003191void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003192 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003193 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003194 return;
3195 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003196
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003197 std::vector<WindowInfo> windowInfos;
3198 std::vector<DisplayInfo> displayInfos;
3199 bool updateWindowInfo = false;
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003200 if (mVisibleRegionsDirty || mInputInfoChanged) {
3201 mInputInfoChanged = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003202 updateWindowInfo = true;
3203 buildWindowInfos(windowInfos, displayInfos);
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003204 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003205 if (!updateWindowInfo && mInputWindowCommands.empty()) {
3206 return;
3207 }
3208 BackgroundExecutor::getInstance().execute([updateWindowInfo,
3209 windowInfos = std::move(windowInfos),
3210 displayInfos = std::move(displayInfos),
3211 inputWindowCommands =
3212 std::move(mInputWindowCommands),
3213 inputFlinger = mInputFlinger, this]() {
3214 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3215 if (updateWindowInfo) {
3216 mWindowInfosListenerInvoker->windowInfosChanged(windowInfos, displayInfos,
3217 inputWindowCommands.syncInputWindows);
3218 } else if (inputWindowCommands.syncInputWindows) {
3219 // If the caller requested to sync input windows, but there are no
3220 // changes to input windows, notify immediately.
3221 windowInfosReported();
3222 }
3223 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3224 inputFlinger->setFocusedWindow(focusRequest);
3225 }
3226 });
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003227
Arthur Hung6cbb9752019-09-05 16:38:18 +08003228 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003229}
3230
Alec Mouricdf16792021-12-10 13:16:06 -08003231void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3232 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3233 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3234 if (!supportsDisplayBrightnessCommand) {
3235 return;
3236 }
3237
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003238 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003239 if (const auto brightness = display->getStagedBrightness(); brightness) {
3240 if (!needsComposite) {
3241 const status_t error =
3242 getHwComposer()
3243 .setDisplayBrightness(display->getPhysicalId(), *brightness,
Alec Mouri4d8a05d2022-03-23 18:14:26 +00003244 display->getCompositionDisplay()
3245 ->getState()
3246 .displayBrightnessNits,
Alec Mouricdf16792021-12-10 13:16:06 -08003247 Hwc2::Composer::DisplayBrightnessOptions{
3248 .applyImmediately = true})
3249 .get();
3250
3251 ALOGE_IF(error != NO_ERROR,
3252 "Error setting display brightness for display %s: %d (%s)",
3253 display->getDebugName().c_str(), error, strerror(error));
3254 }
3255 display->persistBrightness(needsComposite);
3256 }
3257 }
3258}
3259
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003260void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3261 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003262 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3263
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003264 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003265 const auto layerStack = display->getLayerStack();
3266 const auto info = display->getInputInfo();
3267
3268 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003269 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003270 continue;
3271 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003272
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003273 // If the layer stack is mirrored on multiple displays, the first display that is configured
3274 // to receive input takes precedence.
3275 auto& otherInfo = it->second;
3276 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003277 ALOGW_IF(display->receivesInput(),
3278 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003279 layerStack.id);
3280 } else {
3281 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003282 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003283 }
Robert Carr720e5062018-07-30 17:45:14 -07003284
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003285 static size_t sNumWindowInfos = 0;
3286 outWindowInfos.reserve(sNumWindowInfos);
3287 sNumWindowInfos = 0;
3288
Robert Carr720e5062018-07-30 17:45:14 -07003289 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003290 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003291
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003292 // Do not create WindowInfos for windows on displays that cannot receive input.
3293 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3294 const auto& info = opt->get();
3295 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003296 }
Robert Carr720e5062018-07-30 17:45:14 -07003297 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003298
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003299 sNumWindowInfos = outWindowInfos.size();
3300
3301 outDisplayInfos.reserve(displayInputInfos.size());
3302 for (const auto& [_, info] : displayInputInfos) {
3303 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003304 }
Robert Carr720e5062018-07-30 17:45:14 -07003305}
3306
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003307void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003308 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003309 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003310 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003311 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003312 }
3313 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003314
3315 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003316}
3317
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003318void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003319 // If this is called from the main thread mStateLock must be locked before
3320 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003321 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003322
3323 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003324
3325 const auto display = getDefaultDisplayDeviceLocked();
3326 if (!display || mBootStage != BootStage::FINISHED) {
3327 return;
3328 }
3329 ATRACE_CALL();
3330
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003331 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3332 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003333 return;
3334 }
3335
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003336 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003337}
3338
Ady Abraham62a0be22020-12-08 16:54:10 -08003339void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3340 PhysicalDisplayId displayId = [&]() {
3341 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3342 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3343 }();
3344
3345 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3346}
3347
Ady Abraham3efa3942021-06-24 19:01:25 -07003348void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003349 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003350 // If the scheduler is already initialized, this means that we received
3351 // a hotplug(connected) on the primary display. In that case we should
3352 // update the scheduler with the most recent display information.
3353 ALOGW("Scheduler already initialized, updating instead");
3354 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003355 return;
3356 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003357 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003358 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3359 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003360
Marin Shalamanova903d032020-12-29 20:35:13 +01003361 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003362 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003363
Dominik Laskowski068173d2021-08-11 17:22:59 -07003364 using Feature = scheduler::Feature;
3365 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003366
Dominik Laskowski068173d2021-08-11 17:22:59 -07003367 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3368 features |= Feature::kContentDetection;
3369 }
3370 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3371 features |= Feature::kTracePredictedVsync;
3372 }
3373 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003374 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003375 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003376 }
3377
Dominik Laskowski068173d2021-08-11 17:22:59 -07003378 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3379 static_cast<ISchedulerCallback&>(*this),
3380 features);
3381 {
3382 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003383 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003384 features |= Feature::kKernelIdleTimer;
3385 }
3386
3387 mScheduler->createVsyncSchedule(features);
3388 mScheduler->setRefreshRateConfigs(std::move(configs));
3389 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003390 setVsyncEnabled(false);
3391 mScheduler->startTimers();
3392
Ady Abraham9c53ee72020-07-22 21:16:18 -07003393 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003394 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003395 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003396 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003397 /*workDuration=*/configs.late.appWorkDuration,
3398 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003399 impl::EventThread::InterceptVSyncsCallback());
3400 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003401 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3402 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3403 /*readyDuration=*/configs.late.sfWorkDuration,
3404 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003405 mInterceptor->saveVSyncEvent(timestamp);
3406 });
3407
Dominik Laskowski756b7892021-08-04 12:53:59 -07003408 mScheduler->initVsync(mScheduler->getVsyncDispatch(), *mFrameTimeline->getTokenManager(),
3409 configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003410
3411 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003412 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003413 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003414 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003415 // initialization, so that the EventThreads always contain a reference to a
3416 // prior configuration.
3417 //
3418 // This is a bit hacky, but this avoids a back-pointer into the main SF
3419 // classes from EventThread, and there should be no run-time binder cost
3420 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003421 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003422}
3423
Marin Shalamanov5801c942020-12-17 17:00:13 +01003424void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3425 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003426 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003427 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003428}
3429
Ady Abraham55fa7272020-09-30 19:19:27 -07003430void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3431 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003432 mScheduler->setDuration(mAppConnectionHandle,
3433 /*workDuration=*/config.appWorkDuration,
3434 /*readyDuration=*/config.sfWorkDuration);
3435 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003436 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3437 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003438 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003439}
3440
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003441void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003442 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003443
Lloyd Pique58e24a32019-08-01 15:50:14 -07003444 if (!mLayersPendingRemoval.isEmpty()) {
3445 // Notify removed layers now that they can't be drawn from
3446 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003447 // Ensure any buffers set to display on any children are released.
3448 if (l->isRemovedFromCurrentState()) {
3449 l->latchAndReleaseBuffer();
3450 }
3451
3452 // If the layer has been removed and has no parent, then it will not be reachable
3453 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3454 // ensure we can copy its current to drawing state.
3455 if (!l->getParent()) {
3456 mOffscreenLayers.emplace(l.get());
3457 }
3458 }
3459 mLayersPendingRemoval.clear();
3460 }
3461
3462 // If this transaction is part of a window animation then the next frame
3463 // we composite should be considered an animation as well.
3464 mAnimCompositionPending = mAnimTransactionPending;
3465
3466 mDrawingState = mCurrentState;
3467 // clear the "changed" flags in current state
3468 mCurrentState.colorMatrixChanged = false;
3469
Robert Carra70e91c2021-06-11 13:59:52 -07003470 if (mVisibleRegionsDirty) {
3471 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3472 rootLayer->commitChildList();
3473 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003474 }
Robert Carra70e91c2021-06-11 13:59:52 -07003475
Lloyd Pique58e24a32019-08-01 15:50:14 -07003476 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003477 if (mNumClones > 0) {
3478 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3479 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003480}
3481
chaviw74d90ad2019-04-26 14:45:26 -07003482void SurfaceFlinger::commitOffscreenLayers() {
3483 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003484 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003485 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3486 layer->doTransaction(0);
3487 layer->commitChildList();
3488 }
chaviw74d90ad2019-04-26 14:45:26 -07003489 });
3490 }
3491}
3492
Chia-I Wuab0c3192017-08-01 11:29:00 -07003493void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003494 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003495 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003496 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003497 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003498 }
3499 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003500}
3501
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003502bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003503 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003504
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003505 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506
Mathias Agopian4fec8732012-06-29 14:12:52 -07003507 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003508 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003509 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003510
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003511 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3512
Eric Penner51c59cd2014-07-28 19:51:58 -07003513 // Store the set of layers that need updates. This set must not change as
3514 // buffers are being latched, as this could result in a deadlock.
3515 // Example: Two producers share the same command stream and:
3516 // 1.) Layer 0 is latched
3517 // 2.) Layer 0 gets a new frame
3518 // 2.) Layer 1 gets a new frame
3519 // 3.) Layer 1 is latched.
3520 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3521 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003522 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003523 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3524 const uint32_t flags = layer->doTransaction(0);
3525 if (flags & Layer::eVisibleRegion) {
3526 mVisibleRegionsDirty = true;
3527 }
3528 }
Robert Carrb552ff52021-06-11 13:35:54 -07003529
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003530 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003531 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003532 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003533 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003534 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003535 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003536 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003537 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003538 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003539 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003540 }
Robert Carr2047fae2016-11-28 14:09:09 -08003541 });
Robert Carrb552ff52021-06-11 13:35:54 -07003542 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003543
chaviw49a108c2019-08-12 11:23:06 -07003544 // The client can continue submitting buffers for offscreen layers, but they will not
3545 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3546 // layers to ensure dequeueBuffer doesn't block indefinitely.
3547 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003548 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003549 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3550 }
3551
Lloyd Piquef2c79392018-12-20 16:23:33 -08003552 if (!mLayersWithQueuedFrames.empty()) {
3553 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3554 // writes to Layer current state. See also b/119481871
3555 Mutex::Autolock lock(mStateLock);
3556
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003557 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003558 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003559 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003560 newDataLatched = true;
3561 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003562 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003563 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003564 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003565
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003566 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003567
3568 // If we will need to wake up at some time in the future to deal with a
3569 // queued frame that shouldn't be displayed during this vsync period, wake
3570 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003571 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003572 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003573 }
3574
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003575 // enter boot animation on first buffer latch
3576 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3577 ALOGI("Enter boot animation");
3578 mBootStage = BootStage::BOOTANIMATION;
3579 }
3580
Robert Carr6a0382d2021-07-01 15:57:17 -07003581 if (mNumClones > 0) {
3582 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3583 }
chaviw74b03172019-08-19 11:09:03 -07003584
Dan Stoza6b9454d2014-11-07 16:00:59 -08003585 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003586 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003587}
3588
Robert Carrc0df3122019-04-11 13:18:21 -07003589status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003590 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003591 bool addToRoot, uint32_t* outTransformHint) {
arthurhungdba591c2021-02-08 17:28:49 +08003592 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
3593 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
3594 ISurfaceComposer::MAX_LAYERS);
Robert Carr26b98f42022-04-11 15:54:31 -07003595 static_cast<void>(mScheduler->schedule([=] {
3596 ALOGE("Dumping random sampling of on-screen layers: ");
3597 mDrawingState.traverse([&](Layer *layer) {
3598 // Aim to dump about 200 layers to avoid totally trashing
3599 // logcat. On the other hand, if there really are 4096 layers
3600 // something has gone totally wrong its probably the most
3601 // useful information in logcat.
3602 if (rand() % 20 == 13) {
3603 ALOGE("Layer: %s", layer->getName().c_str());
3604 }
3605 });
3606 for (Layer* offscreenLayer : mOffscreenLayers) {
3607 if (rand() % 20 == 13) {
3608 ALOGE("Offscreen-layer: %s", offscreenLayer->getName().c_str());
3609 }
3610 }
3611 }));
arthurhungdba591c2021-02-08 17:28:49 +08003612 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003613 }
3614
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003615 {
3616 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3617 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3618 }
arthurhungdba591c2021-02-08 17:28:49 +08003619
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003620 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003621 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003622 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003623 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003624 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003625 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003626 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003627 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003628
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003629 setTransactionFlags(eTransactionNeeded);
3630 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003631}
3632
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003633uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003634 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003635}
3636
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003637uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3638 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003639}
3640
Dominik Laskowski94000c42022-03-17 12:55:14 -07003641void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003642 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003643 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003644
3645 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003646 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003647 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648}
3649
Ady Abraham9dada822022-02-03 10:26:59 -08003650bool SurfaceFlinger::stopTransactionProcessing(
3651 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3652 applyTokensWithUnsignaledTransactions) const {
3653 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3654 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3655 // then we should have only one applyToken for processing.
3656 // so we can stop further transactions on this applyToken.
3657 return !applyTokensWithUnsignaledTransactions.empty();
3658 }
3659
3660 return false;
3661}
3662
ramindani9eff2492022-03-23 00:28:26 +00003663int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3664 std::vector<TransactionState>& transactions,
3665 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3666 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3667 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3668 applyTokensWithUnsignaledTransactions,
3669 /*tryApplyUnsignaled*/ true);
3670}
3671
Robert Carr79dc06a2022-02-22 15:28:59 -08003672int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003673 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003674 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003675 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3676 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003677 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003678 auto it = mPendingTransactionQueues.begin();
3679 while (it != mPendingTransactionQueues.end()) {
3680 auto& [applyToken, transactionQueue] = *it;
3681 while (!transactionQueue.empty()) {
3682 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3683 ATRACE_NAME("stopTransactionProcessing");
3684 break;
3685 }
3686
3687 auto& transaction = transactionQueue.front();
3688 const auto ready =
3689 transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3690 transaction.isAutoTimestamp,
3691 transaction.desiredPresentTime,
3692 transaction.originUid, transaction.states,
3693 bufferLayersReadyToPresent, transactions.size(),
3694 tryApplyUnsignaled);
3695 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3696 if (ready == TransactionReadiness::NotReady) {
3697 setTransactionFlags(eTransactionFlushNeeded);
3698 break;
3699 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003700 if (ready == TransactionReadiness::NotReadyBarrier) {
3701 transactionsPendingBarrier++;
3702 setTransactionFlags(eTransactionFlushNeeded);
3703 break;
3704 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003705 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003706 const bool frameNumberChanged = state.bufferData->flags.test(
3707 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003708 if (frameNumberChanged) {
3709 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3710 } else {
3711 // Barrier function only used for BBQ which always includes a frame number
3712 bufferLayersReadyToPresent[state.surface] =
3713 std::numeric_limits<uint64_t>::max();
3714 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003715 });
3716 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3717 if (appliedUnsignaled) {
3718 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3719 }
3720
3721 transactions.emplace_back(std::move(transaction));
3722 transactionQueue.pop();
3723 }
3724
3725 if (transactionQueue.empty()) {
3726 it = mPendingTransactionQueues.erase(it);
3727 mTransactionQueueCV.broadcast();
3728 } else {
3729 it = std::next(it, 1);
3730 }
3731 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003732 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003733}
3734
Vishnu Nair7891e962021-11-11 12:07:21 -08003735bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003736 // to prevent onHandleDestroyed from being called while the lock is held,
3737 // we must keep a copy of the transactions (specifically the composer
3738 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003739 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003740 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003741 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003742 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003743 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003744 Mutex::Autolock _l(mStateLock);
3745 {
3746 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003747
Robert Carr79dc06a2022-02-22 15:28:59 -08003748 int lastTransactionsPendingBarrier = 0;
3749 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003750 // First collect transactions from the pending transaction queues.
3751 // We are not allowing unsignaled buffers here as we want to
3752 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003753 transactionsPendingBarrier =
3754 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3755 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003756
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003757 // Second, collect transactions from the transaction queue.
3758 // Here as well we are not allowing unsignaled buffers for the same
3759 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003760 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003761 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003762 const bool pendingTransactions =
3763 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003764 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003765 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003766 if (pendingTransactions) {
3767 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003768 return TransactionReadiness::NotReady;
3769 }
3770
3771 return transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3772 transaction.isAutoTimestamp,
3773 transaction.desiredPresentTime,
3774 transaction.originUid, transaction.states,
3775 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003776 transactions.size(),
3777 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003778 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003779 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003780 if (ready != TransactionReadiness::Ready) {
3781 if (ready == TransactionReadiness::NotReadyBarrier) {
3782 transactionsPendingBarrier++;
3783 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003784 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003785 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003786 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003787 const bool frameNumberChanged = state.bufferData->flags.test(
3788 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003789 if (frameNumberChanged) {
3790 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3791 } else {
3792 // Barrier function only used for BBQ which always includes a frame number.
3793 // This value only used for barrier logic.
3794 bufferLayersReadyToPresent[state.surface] =
3795 std::numeric_limits<uint64_t>::max();
3796 }
Xiang Wang76236e12022-03-22 17:25:30 +00003797 });
Ady Abraham9dada822022-02-03 10:26:59 -08003798 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003799 }
ramindani4d48f902021-09-20 21:07:45 +00003800 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003801 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003802 }
Arthur Hung58144272021-01-16 03:43:53 +00003803
Robert Carr79dc06a2022-02-22 15:28:59 -08003804 // Transactions with a buffer pending on a barrier may be on a different applyToken
3805 // than the transaction which satisfies our barrier. In fact this is the exact use case
3806 // that the primitive is designed for. This means we may first process
3807 // the barrier dependent transaction, determine it ineligible to complete
3808 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3809 // The barrier dependent transaction was eligible to be presented in this frame
3810 // but we would have prevented it without case. To fix this we continually
3811 // loop through flushPendingTransactionQueues until we perform an iteration
3812 // where the number of transactionsPendingBarrier doesn't change. This way
3813 // we can continue to resolve dependency chains of barriers as far as possible.
3814 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3815 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3816 transactionsPendingBarrier =
3817 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3818 applyTokensWithUnsignaledTransactions,
3819 /*tryApplyUnsignaled*/ false);
3820 }
3821
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003822 // We collected all transactions that could apply without latching unsignaled buffers.
3823 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3824 // transactions that were not applied and try to apply them unsignaled.
3825 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003826 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3827 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003828 }
3829
Vishnu Nair7891e962021-11-11 12:07:21 -08003830 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003831 }
ramindani4d48f902021-09-20 21:07:45 +00003832 }
3833}
3834
Vishnu Nair7891e962021-11-11 12:07:21 -08003835bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3836 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003837 bool needsTraversal = false;
3838 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003839 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003840 needsTraversal |=
3841 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3842 transaction.displays, transaction.flags,
3843 transaction.inputWindowCommands,
3844 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3845 transaction.buffer, transaction.postTime,
3846 transaction.permissions, transaction.hasListenerCallbacks,
3847 transaction.listenerCallbacks, transaction.originPid,
3848 transaction.originUid, transaction.id);
3849 if (transaction.transactionCommittedSignal) {
3850 mTransactionCommittedSignals.emplace_back(
3851 std::move(transaction.transactionCommittedSignal));
3852 }
3853 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003854
Dominik Laskowski46471e62022-01-14 15:34:03 -08003855 if (mTransactionTracing) {
3856 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003857 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003858 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003859}
3860
3861bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003862 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003863 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003864}
3865
Ady Abraham8db10102021-03-15 17:19:23 -07003866bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3867 // The amount of time SF can delay a frame if it is considered early based
3868 // on the VsyncModulator::VsyncConfig::appWorkDuration
3869 constexpr static std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3870
3871 const auto currentVsyncPeriod = mScheduler->getDisplayStatInfo(systemTime()).vsyncPeriod;
3872 const auto earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
3873
3874 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3875 if (!prediction.has_value()) {
3876 return false;
3877 }
3878
3879 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3880 kEarlyLatchMaxThreshold.count()) {
3881 return false;
3882 }
3883
3884 return prediction->presentTime >= expectedPresentTime &&
3885 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3886}
Ady Abraham9dada822022-02-03 10:26:59 -08003887bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003888 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003889 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3890 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3891 return false;
3892 }
Ady Abraham8db10102021-03-15 17:19:23 -07003893
Ady Abraham9dada822022-02-03 10:26:59 -08003894 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3895 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3896 return true;
3897 }
3898
3899 // We only want to latch unsignaled when a single layer is updated in this
3900 // transaction (i.e. not a blast sync transaction).
3901 if (numStates != 1) {
3902 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3903 return false;
3904 }
3905
Ady Abraham2739e832022-02-14 17:42:00 -08003906 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3907 if (totalTXapplied > 0) {
3908 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3909 __func__, totalTXapplied);
3910 return false;
3911 }
3912
3913 // We don't want to latch unsignaled if are in early / client composition
3914 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3915 // or window animations being slow.
3916 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3917 if (!isDefaultVsyncConfig) {
3918 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3919 __func__);
3920 return false;
3921 }
Ady Abraham9dada822022-02-03 10:26:59 -08003922 }
3923
3924 if (!layer->simpleBufferUpdate(state)) {
3925 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3926 return false;
3927 }
3928
3929 ALOGV("%s: true", __func__);
3930 return true;
3931}
3932
3933auto SurfaceFlinger::transactionIsReadyToBeApplied(
Ady Abraham43752eb2021-03-04 16:24:25 -08003934 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003935 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003936 const std::unordered_map<
3937 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003938 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003939 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003940 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003941 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3942 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003943 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08003944 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003945 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003946 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003947 }
3948
Ady Abraham5690bda2021-03-12 15:01:18 -08003949 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
3950 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003951 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003952 }
3953
Ady Abraham8db10102021-03-15 17:19:23 -07003954 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3955 // present time of this transaction.
3956 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
3957 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08003958 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07003959 }
3960
Ady Abraham9dada822022-02-03 10:26:59 -08003961 bool fenceUnsignaled = false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003962 for (const ComposerState& state : states) {
3963 const layer_state_t& s = state.state;
Ady Abrahamf20c1922020-12-21 18:39:01 -08003964 sp<Layer> layer = nullptr;
3965 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07003966 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003967 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08003968 ALOGW("Transaction with buffer, but no Layer?");
3969 continue;
3970 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003971 if (!layer) {
3972 continue;
3973 }
Ady Abraham43752eb2021-03-04 16:24:25 -08003974
Robert Carr79dc06a2022-02-22 15:28:59 -08003975 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
3976 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
3977 const bool willApplyBarrierFrame =
3978 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
3979 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
3980 if (!willApplyBarrierFrame) {
3981 ATRACE_NAME("NotReadyBarrier");
3982 return TransactionReadiness::NotReadyBarrier;
3983 }
3984 }
3985
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003986 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08003987 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08003988 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
3989 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08003990
3991 const bool acquireFenceChanged = s.bufferData &&
3992 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
3993 s.bufferData->acquireFence;
3994 fenceUnsignaled = fenceUnsignaled ||
3995 (acquireFenceChanged &&
3996 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
3997
3998 if (fenceUnsignaled && !allowLatchUnsignaled) {
3999 ATRACE_NAME("fence unsignaled");
4000 return TransactionReadiness::NotReady;
4001 }
4002
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07004003 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08004004 // If backpressure is enabled and we already have a buffer to commit, keep the
4005 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004006 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4007 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004008 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004009 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004010 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004011 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004012 }
4013 }
Ady Abraham9dada822022-02-03 10:26:59 -08004014 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004015}
4016
arthurhungf1b7c7b2021-03-03 17:42:23 +08004017void SurfaceFlinger::queueTransaction(TransactionState& state) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004018 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004019
arthurhungf1b7c7b2021-03-03 17:42:23 +08004020 // Generate a CountDownLatch pending state if this is a synchronous transaction.
4021 if ((state.flags & eSynchronous) || state.inputWindowCommands.syncInputWindows) {
4022 state.transactionCommittedSignal = std::make_shared<CountDownLatch>(
Arthur Hung2274a312021-04-28 15:13:06 +00004023 (state.inputWindowCommands.syncInputWindows
4024 ? (CountDownLatch::eSyncInputWindows | CountDownLatch::eSyncTransaction)
4025 : CountDownLatch::eSyncTransaction));
arthurhungf1b7c7b2021-03-03 17:42:23 +08004026 }
4027
ramindani4d48f902021-09-20 21:07:45 +00004028 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004029 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4030
Ady Abrahame46243a2021-02-23 19:33:49 -08004031 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004032 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4033 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004034 return TransactionSchedule::Late;
4035 }(state.flags);
4036
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004037 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4038
4039 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004040}
4041
arthurhungf1b7c7b2021-03-03 17:42:23 +08004042void SurfaceFlinger::waitForSynchronousTransaction(
4043 const CountDownLatch& transactionCommittedSignal) {
4044 // applyTransactionState is called on the main SF thread. While a given process may wish
4045 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4046 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004047 if (!transactionCommittedSignal.wait_until(
4048 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004049 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004050 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004051}
Ady Abrahame46243a2021-02-23 19:33:49 -08004052
Arthur Hung2274a312021-04-28 15:13:06 +00004053void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004054 for (auto it = mTransactionCommittedSignals.begin();
4055 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004056 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004057 it = mTransactionCommittedSignals.erase(it);
4058 } else {
4059 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004060 }
4061 }
4062}
4063
chaviw308ddba2020-08-11 16:23:51 -07004064status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004065 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004066 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4067 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004068 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004069 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004070 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004071
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004072 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004073 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4074 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004075 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4076 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004077 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004078 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004079 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004080 }
4081
Leon Scroggins9a20f722021-12-28 14:43:12 +00004082 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004083 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004084 }
4085
Robert Carrde6d7b42022-01-07 18:23:06 -08004086 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004087 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4088 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4089 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004090 }
4091
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004092 const int64_t postTime = systemTime();
4093
4094 IPCThreadState* ipc = IPCThreadState::self();
4095 const int originPid = ipc->getCallingPid();
4096 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004097 TransactionState state{frameTimelineInfo, states,
4098 displays, flags,
4099 applyToken, inputWindowCommands,
4100 desiredPresentTime, isAutoTimestamp,
4101 uncacheBuffer, postTime,
4102 permissions, hasListenerCallbacks,
4103 listenerCallbacks, originPid,
4104 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004105
4106 // Check for incoming buffer updates and increment the pending buffer count.
4107 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4108 mBufferCountTracker.increment(state.surface->localBinder());
4109 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004110
Dominik Laskowski46471e62022-01-14 15:34:03 -08004111 if (mTransactionTracing) {
4112 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004113 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004114 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004115
arthurhungf1b7c7b2021-03-03 17:42:23 +08004116 // Check the pending state to make sure the transaction is synchronous.
4117 if (state.transactionCommittedSignal) {
4118 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004119 }
4120
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004121 return NO_ERROR;
4122}
Marissa Wall713b63f2018-10-17 15:42:43 -07004123
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004124bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004125 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004126 const Vector<DisplayState>& displays, uint32_t flags,
4127 const InputWindowCommands& inputWindowCommands,
4128 const int64_t desiredPresentTime, bool isAutoTimestamp,
4129 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004130 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004131 bool hasListenerCallbacks,
4132 const std::vector<ListenerCallbacks>& listenerCallbacks,
4133 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004134 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004135 for (const DisplayState& display : displays) {
4136 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004137 }
4138
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004139 // start and end registration for listeners w/ no surface so they can get their callback. Note
4140 // that listeners with SurfaceControls will start registration during setClientStateLocked
4141 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004142 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004143 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004144 }
4145
Marissa Walle2ffb422018-10-12 11:33:52 -07004146 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004147 for (int i = 0; i < states.size(); i++) {
4148 ComposerState& state = states.editItemAt(i);
4149 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004150 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004151 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004152 if (const auto layer = fromHandle(state.state.surface).promote()) {
4153 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004154 mScheduler->recordLayerHistory(layer.get(),
4155 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004156 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004157 }
4158 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004159 }
4160
Marissa Walle2ffb422018-10-12 11:33:52 -07004161 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004162
Robert Carrde6d7b42022-01-07 18:23:06 -08004163 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004164 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4165 } else if (!inputWindowCommands.empty()) {
4166 ALOGE("Only privileged callers are allowed to send input commands.");
4167 }
chaviw273171b2018-12-26 11:46:30 -08004168
Marissa Wall947d34e2019-03-29 14:03:53 -07004169 if (uncacheBuffer.isValid()) {
4170 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004171 }
4172
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004173 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4174 // anyway. This can be used as a flush mechanism for previous async transactions.
4175 // Empty animation transaction can be used to simulate back-pressure, so also force a
4176 // transaction for empty animation transactions.
4177 if (transactionFlags == 0 &&
4178 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004179 transactionFlags = eTransactionNeeded;
4180 }
4181
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004182 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004183 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004184 if (mInterceptor->isEnabled()) {
4185 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004186 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004187 }
4188
Arthur Hung58144272021-01-16 03:43:53 +00004189 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4190 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4191 if (transactionFlags & eTraversalNeeded) {
4192 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004193 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004194 }
Arthur Hung58144272021-01-16 03:43:53 +00004195 if (transactionFlags) {
4196 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004197 }
4198
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004199 if (flags & eAnimation) {
4200 mAnimTransactionPending = true;
4201 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004202 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004203
4204 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004205}
4206
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004207uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4208 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4209 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004210
Mathias Agopiane57f2922012-08-09 16:29:12 -07004211 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004212 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4213
4214 const uint32_t what = s.what;
4215 if (what & DisplayState::eSurfaceChanged) {
4216 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4217 state.surface = s.surface;
4218 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004219 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004220 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004221 if (what & DisplayState::eLayerStackChanged) {
4222 if (state.layerStack != s.layerStack) {
4223 state.layerStack = s.layerStack;
4224 flags |= eDisplayTransactionNeeded;
4225 }
4226 }
Evan Rosky2239b372021-05-20 13:43:47 -07004227 if (what & DisplayState::eFlagsChanged) {
4228 if (state.flags != s.flags) {
4229 state.flags = s.flags;
4230 flags |= eDisplayTransactionNeeded;
4231 }
4232 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004233 if (what & DisplayState::eDisplayProjectionChanged) {
4234 if (state.orientation != s.orientation) {
4235 state.orientation = s.orientation;
4236 flags |= eDisplayTransactionNeeded;
4237 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004238 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4239 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004240 flags |= eDisplayTransactionNeeded;
4241 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004242 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4243 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004244 flags |= eDisplayTransactionNeeded;
4245 }
4246 }
4247 if (what & DisplayState::eDisplaySizeChanged) {
4248 if (state.width != s.width) {
4249 state.width = s.width;
4250 flags |= eDisplayTransactionNeeded;
4251 }
4252 if (state.height != s.height) {
4253 state.height = s.height;
4254 flags |= eDisplayTransactionNeeded;
4255 }
4256 }
4257
Mathias Agopiane57f2922012-08-09 16:29:12 -07004258 return flags;
4259}
4260
Steven Thomasd4071902020-03-24 16:02:53 -07004261bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004262 IPCThreadState* ipc = IPCThreadState::self();
4263 const int pid = ipc->getCallingPid();
4264 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004265 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004266 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4267 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004268 return false;
4269 }
4270 return true;
4271}
4272
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004273uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004274 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004275 int64_t desiredPresentTime, bool isAutoTimestamp,
4276 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004277 layer_state_t& s = composerState.state;
4278 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004279
4280 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004281 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004282 // Starts a registration but separates the callback ids according to callback type. This
4283 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004284 // note that startRegistration will not re-register if the listener has
4285 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004286
4287 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4288 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004289 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004290 }
4291
4292 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4293 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004294 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004295 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004296 }
4297
arthurhungdba591c2021-02-08 17:28:49 +08004298 const uint64_t what = s.what;
4299 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004300 sp<Layer> layer = nullptr;
4301 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004302 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004303 } else {
4304 // The client may provide us a null handle. Treat it as if the layer was removed.
4305 ALOGW("Attempt to set client state with a null layer handle");
4306 }
chaviw8b3871a2017-11-01 17:41:01 -07004307 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004308 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004309 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004310 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004311 }
chaviw8b3871a2017-11-01 17:41:01 -07004312 return 0;
4313 }
4314
Valerie Hau871d6352020-01-29 08:44:02 -08004315 // Only set by BLAST adapter layers
4316 if (what & layer_state_t::eProducerDisconnect) {
4317 layer->onDisconnect();
4318 }
4319
chaviw8b3871a2017-11-01 17:41:01 -07004320 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004321 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004322 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004323 }
chaviw8b3871a2017-11-01 17:41:01 -07004324 }
4325 if (what & layer_state_t::eLayerChanged) {
4326 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004327 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004328 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004329 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004330 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004331 mCurrentState.layersSortedByZ.removeAt(idx);
4332 mCurrentState.layersSortedByZ.add(layer);
4333 // we need traversal (state changed)
4334 // AND transaction (list changed)
4335 flags |= eTransactionNeeded|eTraversalNeeded;
4336 }
chaviw8b3871a2017-11-01 17:41:01 -07004337 } else {
4338 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004339 flags |= eTransactionNeeded|eTraversalNeeded;
4340 }
4341 }
chaviw8b3871a2017-11-01 17:41:01 -07004342 }
4343 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004344 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004345 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004346 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4347 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004348 if (p == nullptr) {
4349 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004350 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004351 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004352 mCurrentState.layersSortedByZ.removeAt(idx);
4353 mCurrentState.layersSortedByZ.add(layer);
4354 // we need traversal (state changed)
4355 // AND transaction (list changed)
4356 flags |= eTransactionNeeded|eTraversalNeeded;
4357 }
4358 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004359 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004360 flags |= eTransactionNeeded|eTraversalNeeded;
4361 }
chaviw8b3871a2017-11-01 17:41:01 -07004362 }
4363 }
4364 if (what & layer_state_t::eSizeChanged) {
4365 if (layer->setSize(s.w, s.h)) {
4366 flags |= eTraversalNeeded;
4367 }
4368 }
4369 if (what & layer_state_t::eAlphaChanged) {
4370 if (layer->setAlpha(s.alpha))
4371 flags |= eTraversalNeeded;
4372 }
4373 if (what & layer_state_t::eColorChanged) {
4374 if (layer->setColor(s.color))
4375 flags |= eTraversalNeeded;
4376 }
Peiyong Lind3788632018-09-18 16:01:31 -07004377 if (what & layer_state_t::eColorTransformChanged) {
4378 if (layer->setColorTransform(s.colorTransform)) {
4379 flags |= eTraversalNeeded;
4380 }
4381 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004382 if (what & layer_state_t::eBackgroundColorChanged) {
4383 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4384 flags |= eTraversalNeeded;
4385 }
4386 }
chaviw8b3871a2017-11-01 17:41:01 -07004387 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004388 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004389 }
4390 if (what & layer_state_t::eTransparentRegionChanged) {
4391 if (layer->setTransparentRegionHint(s.transparentRegion))
4392 flags |= eTraversalNeeded;
4393 }
4394 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004395 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004396 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004397 if (what & layer_state_t::eCornerRadiusChanged) {
4398 if (layer->setCornerRadius(s.cornerRadius))
4399 flags |= eTraversalNeeded;
4400 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004401 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004402 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4403 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004404 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004405 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4406 }
chaviw8b3871a2017-11-01 17:41:01 -07004407 if (what & layer_state_t::eLayerStackChanged) {
4408 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4409 // We only allow setting layer stacks for top level layers,
4410 // everything else inherits layer stack from its parent.
4411 if (layer->hasParent()) {
4412 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004413 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004414 } else if (idx < 0) {
4415 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004416 "that also does not appear in the top level layer list. Something"
4417 " has gone wrong.",
4418 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004419 } else if (layer->setLayerStack(s.layerStack)) {
4420 mCurrentState.layersSortedByZ.removeAt(idx);
4421 mCurrentState.layersSortedByZ.add(layer);
4422 // we need traversal (state changed)
4423 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004424 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004425 }
4426 }
Marissa Wall61c58622018-07-18 10:12:20 -07004427 if (what & layer_state_t::eTransformChanged) {
4428 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4429 }
4430 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4431 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4432 flags |= eTraversalNeeded;
4433 }
4434 if (what & layer_state_t::eCropChanged) {
4435 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4436 }
Marissa Wall61c58622018-07-18 10:12:20 -07004437 if (what & layer_state_t::eDataspaceChanged) {
4438 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4439 }
4440 if (what & layer_state_t::eHdrMetadataChanged) {
4441 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4442 }
4443 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4444 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4445 }
4446 if (what & layer_state_t::eApiChanged) {
4447 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4448 }
4449 if (what & layer_state_t::eSidebandStreamChanged) {
4450 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4451 }
Robert Carr720e5062018-07-30 17:45:14 -07004452 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004453 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4454 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004455 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004456 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004457 if (what & layer_state_t::eMetadataChanged) {
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004458 dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004459
Huihong Luod3d8f8e2022-03-08 14:48:46 -08004460 if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4461 gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004462 // The transaction will be received on the Task layer and needs to be applied to all
4463 // child layers. Child layers that are added at a later point will obtain the game mode
4464 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004465 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004466 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004467
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004468 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4469 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004470 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4471 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4472 flags |= eTraversalNeeded;
4473 }
4474 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004475 if (what & layer_state_t::eShadowRadiusChanged) {
4476 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4477 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004478 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004479 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004480 flags |= eTraversalNeeded;
4481 }
4482 }
Steven Thomas3172e202020-01-06 19:25:30 -08004483 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004484 const auto compatibility =
4485 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4486 const auto strategy =
4487 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004488
Robert Carrde6d7b42022-01-07 18:23:06 -08004489 if (layer->setFrameRate(
4490 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4491 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004492 }
Steven Thomas3172e202020-01-06 19:25:30 -08004493 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004494 if (what & layer_state_t::eFixedTransformHintChanged) {
4495 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4496 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4497 }
4498 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004499 if (what & layer_state_t::eAutoRefreshChanged) {
4500 layer->setAutoRefresh(s.autoRefresh);
4501 }
Sally Qi421ffb02022-03-21 19:41:33 -07004502 if (what & layer_state_t::eDimmingEnabledChanged) {
4503 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4504 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004505 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004506 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4507 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004508 }
4509 }
John Reckcdb4ed72021-02-04 13:39:33 -05004510 if (what & layer_state_t::eStretchChanged) {
4511 if (layer->setStretchEffect(s.stretchEffect)) {
4512 flags |= eTraversalNeeded;
4513 }
4514 }
chaviwf3f40fe2021-04-27 15:54:02 -05004515 if (what & layer_state_t::eBufferCropChanged) {
4516 if (layer->setBufferCrop(s.bufferCrop)) {
4517 flags |= eTraversalNeeded;
4518 }
4519 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004520 if (what & layer_state_t::eDestinationFrameChanged) {
4521 if (layer->setDestinationFrame(s.destinationFrame)) {
4522 flags |= eTraversalNeeded;
4523 }
4524 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004525 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004526 if (layer->setDropInputMode(s.dropInputMode)) {
4527 flags |= eTraversalNeeded;
4528 mInputInfoChanged = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004529 }
4530 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004531 // This has to happen after we reparent children because when we reparent to null we remove
4532 // child layers from current state and remove its relative z. If the children are reparented in
4533 // the same transaction, then we have to make sure we reparent the children first so we do not
4534 // lose its relative z order.
4535 if (what & layer_state_t::eReparent) {
4536 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004537 auto parentHandle = (s.parentSurfaceControlForChild)
4538 ? s.parentSurfaceControlForChild->getHandle()
4539 : nullptr;
4540 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004541 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004542 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004543 mCurrentState.layersSortedByZ.remove(layer);
4544 }
4545 flags |= eTransactionNeeded | eTraversalNeeded;
4546 }
4547 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004548 std::vector<sp<CallbackHandle>> callbackHandles;
4549 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4550 for (auto& [listener, callbackIds] : filteredListeners) {
4551 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4552 }
4553 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004554
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004555 if (what & layer_state_t::eBufferChanged) {
4556 std::shared_ptr<renderengine::ExternalTexture> buffer =
4557 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4558 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4559 dequeueBufferTimestamp, frameTimelineInfo)) {
4560 flags |= eTraversalNeeded;
4561 }
Ady Abraham8db10102021-03-15 17:19:23 -07004562 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4563 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004564 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004565
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004566 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004567 // Do not put anything that updates layer state or modifies flags after
4568 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004569 return flags;
4570}
4571
chaviw273171b2018-12-26 11:46:30 -08004572uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004573 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004574 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004575}
4576
Vishnu Nair84125ac2021-12-02 08:47:48 -08004577status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4578 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4579 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004580 if (!mirrorFromHandle) {
4581 return NAME_NOT_FOUND;
4582 }
4583
4584 sp<Layer> mirrorLayer;
4585 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004586 {
4587 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004588 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004589 if (!mirrorFrom) {
4590 return NAME_NOT_FOUND;
4591 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004592 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004593 if (result != NO_ERROR) {
4594 return result;
4595 }
4596
Robert Carr6a0382d2021-07-01 15:57:17 -07004597 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004598 }
4599
Ady Abraham9f0a4002020-10-05 15:47:26 -07004600 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004601 if (mTransactionTracing) {
4602 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4603 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004604 }
4605 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004606 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004607}
4608
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004609status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004610 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4611 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004612 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4613 "Expected only one of parentLayer or parentHandle to be non-null. "
4614 "Programmer error?");
4615
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004616 status_t result = NO_ERROR;
4617
4618 sp<Layer> layer;
4619
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004620 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004621 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004622 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004623 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004624 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4625 if (pendingBufferCounter) {
4626 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004627 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004628 pendingBufferCounter);
4629 }
4630 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004631 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004632 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004633 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004634 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004635 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004636 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004637 default:
4638 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004639 break;
4640 }
4641
Dan Stoza7d89d062015-04-30 13:29:25 -07004642 if (result != NO_ERROR) {
4643 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004644 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004645
Vishnu Nair858a3b42022-01-12 20:42:28 -08004646 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004647 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4648 if (parentHandle != nullptr && parent == nullptr) {
4649 ALOGE("Invalid parent handle %p.", parentHandle.get());
4650 addToRoot = false;
4651 }
4652 if (parentLayer != nullptr) {
4653 addToRoot = false;
4654 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004655
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004656 int parentId = -1;
4657 // We can safely promote the layer in binder thread because we have a strong reference
4658 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4659 sp<Layer> parentSp = parent.promote();
4660 if (parentSp != nullptr) {
4661 parentId = parentSp->getSequence();
4662 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004663 if (mTransactionTracing) {
4664 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4665 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004666 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004667
Vishnu Nair047fb332021-12-09 09:54:36 -08004668 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4669 if (result != NO_ERROR) {
4670 return result;
4671 }
4672
Ady Abraham9f0a4002020-10-05 15:47:26 -07004673 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004674 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004675}
4676
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004677status_t SurfaceFlinger::createBufferQueueLayer(LayerCreationArgs& args, PixelFormat& format,
Evan Roskya1f1e152019-01-24 16:17:46 -08004678 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004679 sp<IGraphicBufferProducer>* gbp,
4680 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004681 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004682 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004683 case PIXEL_FORMAT_TRANSPARENT:
4684 case PIXEL_FORMAT_TRANSLUCENT:
4685 format = PIXEL_FORMAT_RGBA_8888;
4686 break;
4687 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004688 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004689 break;
4690 }
4691
chaviwb4c6e582019-08-16 14:35:07 -07004692 sp<BufferQueueLayer> layer;
chaviwb4c6e582019-08-16 14:35:07 -07004693 args.textureName = getNewTexture();
4694 {
4695 // Grab the SF state lock during this since it's the only safe way to access
4696 // RenderEngine when creating a BufferLayerConsumer
4697 // TODO: Check if this lock is still needed here
4698 Mutex::Autolock lock(mStateLock);
4699 layer = getFactory().createBufferQueueLayer(args);
4700 }
4701
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004702 status_t err = layer->setDefaultBufferProperties(0, 0, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004703 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004704 *handle = layer->getHandle();
4705 *gbp = layer->getProducer();
4706 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004707 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004708
Marissa Wallfd668622018-05-10 10:21:13 -07004709 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004710 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004711}
4712
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004713status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004714 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004715 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004716 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004717 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004718 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004719}
4720
Vishnu Nair84125ac2021-12-02 08:47:48 -08004721status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004722 sp<Layer>* outLayer) {
4723 *outLayer = getFactory().createEffectLayer(args);
4724 *handle = (*outLayer)->getHandle();
4725 return NO_ERROR;
4726}
4727
Vishnu Nair84125ac2021-12-02 08:47:48 -08004728status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004729 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004730 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004731 *handle = (*outLayer)->getHandle();
4732 return NO_ERROR;
4733}
4734
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004735void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004736 mLayersPendingRemoval.add(layer);
4737 mLayersRemoved = true;
4738 setTransactionFlags(eTransactionNeeded);
4739}
4740
Vishnu Nairf9096652021-07-20 18:49:42 -07004741void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004742 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004743 // If a layer has a parent, we allow it to out-live it's handle
4744 // with the idea that the parent holds a reference and will eventually
4745 // be cleaned up. However no one cleans up the top-level so we do so
4746 // here.
Vishnu Nair14d218b2021-07-13 13:57:39 -07004747 if (layer->isAtRoot()) {
4748 layer->setIsAtRoot(false);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004749 mCurrentState.layersSortedByZ.remove(layer);
4750 }
4751 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004752 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004753 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004754 if (mTransactionTracing) {
4755 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004756 }
Rob Carr4bba3702018-10-08 21:53:30 +00004757}
4758
Mathias Agopianb60314a2012-04-10 22:09:54 -07004759// ---------------------------------------------------------------------------
4760
Andy McFadden13a082e2012-08-24 10:16:42 -07004761void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004762 const auto display = getDefaultDisplayDeviceLocked();
4763 if (!display) return;
4764
4765 const sp<IBinder> token = display->getDisplayToken().promote();
4766 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004767
Jesse Hall01e29052013-02-19 16:13:35 -08004768 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004769 Vector<ComposerState> state;
4770 Vector<DisplayState> displays;
4771 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004772 d.what = DisplayState::eDisplayProjectionChanged |
4773 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004774 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004775 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004776 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004777 d.orientedDisplaySpaceRect.makeInvalid();
4778 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004779 d.width = 0;
4780 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004781 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004782
Vishnu Nair9a69a042021-06-18 13:19:49 -07004783 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004784
4785 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004786 // It should be on the main thread, apply it directly.
4787 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004788 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004789 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004790
Peiyong Lin65248e02020-04-18 21:15:07 -07004791 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004792 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004793 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004794 mActiveDisplayTransformHint = display->getTransformHint();
Brian Andersond0010582017-03-07 13:20:31 -08004795 // Use phase of 0 since phase is not known.
4796 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004797 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004798 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004799}
4800
4801void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004802 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004803 static_cast<void>(
4804 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004805}
4806
Peiyong Lin65248e02020-04-18 21:15:07 -07004807void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004808 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004809 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004810 return;
4811 }
4812
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004813 const auto displayId = display->getPhysicalId();
4814 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004815
Peiyong Lin65248e02020-04-18 21:15:07 -07004816 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004817 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004818 return;
4819 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004820
Ady Abraham4f960d12021-10-13 16:59:49 -07004821 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4822 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4823 activeDisplay->isPoweredOn()) {
4824 ALOGW("Trying to change power mode on non active display while the active display is ON");
4825 }
4826
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004827 display->setPowerMode(mode);
4828
Lloyd Pique4dccc412018-01-22 17:21:36 -08004829 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004830 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004831 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004832 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004833 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004834 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004835 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004836 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004837 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004838 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4839 // We can merge the syscall later.
4840 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4841 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4842 }
Martin Liu4a322352020-03-24 21:30:38 +08004843 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4844 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4845 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004846 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004847 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004848 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004849 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004850 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004851 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004852
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004853 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004854 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004855 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004856 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004857 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004858 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4859 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004860 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004861 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4862 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4863 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004864 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004865 mScheduler->disableHardwareVsync(true);
4866 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004867 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004868
Ady Abraham27c70212019-06-11 10:52:26 -07004869 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004870 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004871
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004872 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004873 mVisibleRegionsDirty = true;
4874 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004875 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004876 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004877 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004878 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004879 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004880 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004881 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004882 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004883 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004884 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004885 mScheduler->disableHardwareVsync(true);
4886 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004887 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004888 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004889 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004890 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004891 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004892 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004893
Ady Abrahamadc914c2021-10-13 17:04:27 -07004894 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004895 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004896 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004897 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004898 }
4899
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004900 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004901}
4902
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004903void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004904 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004905 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004906 if (!display) {
4907 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4908 displayToken.get());
4909 } else if (display->isVirtual()) {
4910 ALOGW("Attempt to set power mode %d for virtual display", mode);
4911 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004912 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004913 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004914 });
4915
4916 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004917}
4918
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004919status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004920 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004921
Mathias Agopianbd115332013-04-18 16:41:04 -07004922 IPCThreadState* ipc = IPCThreadState::self();
4923 const int pid = ipc->getCallingPid();
4924 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004925
Mathias Agopianbd115332013-04-18 16:41:04 -07004926 if ((uid != AID_SHELL) &&
4927 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004928 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4929 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004930 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004931 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004932 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004933 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004934 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004935 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4936 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4937 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4938 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004939 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004940 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4941 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004942 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004943 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004944 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004945 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004946
Dominik Laskowskic2867142019-01-21 11:33:38 -08004947 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004948
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004949 bool dumpLayers = true;
4950 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004951 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004952 if (!lock.locked()) {
4953 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4954 strerror(-lock.status), lock.status);
4955 }
4956
4957 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4958 (it->second)(args, asProto, result);
4959 dumpLayers = false;
4960 } else if (!asProto) {
4961 dumpAllLocked(args, result);
4962 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004963 }
4964
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004965 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004966 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05004967 LayersTraceProto* layersTrace = traceFileProto.add_entry();
4968 LayersProto layersProto = dumpProtoFromMainThread();
4969 layersTrace->mutable_layers()->Swap(&layersProto);
4970 dumpDisplayProto(*layersTrace);
4971
Dominik Laskowski46470112019-08-02 13:13:11 -07004972 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05004973 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07004974 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004975 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05004976 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07004977 result.append(LayerProtoParser::layerTreeToString(layerTree));
4978 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004979 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004980 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004981 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004982 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004983 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004984 return NO_ERROR;
4985}
4986
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004987status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08004988 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004989 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004990 if (mTransactionTracing) {
4991 mTransactionTracing->writeToFile();
4992 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004993 }
4994
4995 return doDump(fd, DumpArgs(), asProto);
4996}
4997
Dominik Laskowskic2867142019-01-21 11:33:38 -08004998void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004999 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005000 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005001}
5002
Dominik Laskowskic2867142019-01-21 11:33:38 -08005003void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07005004 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005005
Dominik Laskowskic2867142019-01-21 11:33:38 -08005006 if (args.size() > 1) {
5007 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08005008 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005009 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005010 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005011 }
Robert Carr2047fae2016-11-28 14:09:09 -08005012 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005013 } else {
5014 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005015 }
5016}
5017
Dominik Laskowskic2867142019-01-21 11:33:38 -08005018void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005019 const bool clearAll = args.size() < 2;
5020 const auto name = clearAll ? String8() : String8(args[1]);
5021
Edgar Arriaga844fa672020-01-16 14:21:42 -08005022 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005023 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005024 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005025 }
Robert Carr2047fae2016-11-28 14:09:09 -08005026 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005027
Svetoslavd85084b2014-03-20 10:28:31 -07005028 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005029}
5030
Dominik Laskowskic2867142019-01-21 11:33:38 -08005031void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5032 mTimeStats->parseArgs(asProto, args, result);
5033}
5034
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005035void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5036 mFrameTimeline->parseArgs(args, result);
5037}
5038
Jamie Gennis6547ff42013-07-16 20:12:42 -07005039void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005040 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005041 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005042 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005043
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005044 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005045}
5046
Yiwei Zhang5434a782018-12-05 18:06:32 -08005047void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005048 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005049
Yiwei Zhang5434a782018-12-05 18:06:32 -08005050 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5051 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005052 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5053 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005054 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5055 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5056 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005057 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005058}
5059
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005060void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005061 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005062
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005063 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005064 result.append("\n");
5065
Ady Abraham8287e852020-08-12 14:44:58 -07005066 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005067 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005068 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005069 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005070
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005071 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5072 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005073
Ana Krulecc2870422019-01-29 19:00:58 -08005074 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005075 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005076 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5077 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005078}
5079
Dan Stoza269dc4d2021-01-15 15:07:43 -08005080void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5081 for (const auto& [token, display] : mDisplays) {
5082 const auto compositionDisplay = display->getCompositionDisplay();
5083 compositionDisplay->dumpPlannerInfo(args, result);
5084 }
5085}
5086
Yiwei Zhang5434a782018-12-05 18:06:32 -08005087void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5088 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005089 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5090 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005091 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005092 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005093 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005094 }
David Sodman4a36e932017-11-07 14:29:47 -08005095 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005096 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005097 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005098 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5099 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005100}
5101
Yiwei Zhang5434a782018-12-05 18:06:32 -08005102void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
5103 result.append("Layer frame timestamps:\n");
Josh Chienedaa9132020-12-04 18:30:46 +08005104 // Traverse all layers to dump frame-events for each layer
5105 mCurrentState.traverseInZOrder(
5106 [&] (Layer* layer) { layer->dumpFrameEvents(result); });
Brian Andersond6927fb2016-07-23 23:37:30 -07005107}
5108
Yiwei Zhang5434a782018-12-05 18:06:32 -08005109void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005110 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005111 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005112 if (!displayId) {
5113 continue;
5114 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005115 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005116 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005117 continue;
5118 }
5119
Yiwei Zhang5434a782018-12-05 18:06:32 -08005120 StringAppendF(&result,
5121 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5122 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005123 uint8_t port;
5124 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005125 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005126 result.append("no identification data\n");
5127 continue;
5128 }
5129
5130 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005131 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005132 continue;
5133 }
5134
5135 const auto edid = parseEdid(data);
5136 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005137 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005138 continue;
5139 }
5140
Yiwei Zhang5434a782018-12-05 18:06:32 -08005141 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005142 result.append(edid->displayName.data(), edid->displayName.length());
5143 result.append("\"\n");
5144 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005145}
5146
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005147void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5148 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005149 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005150 uint8_t port;
5151 DisplayIdentificationData data;
5152
5153 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5154 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5155 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5156 }
5157}
5158
Yiwei Zhang5434a782018-12-05 18:06:32 -08005159void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005160 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005161 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5162 StringAppendF(&result, "DisplayColorSetting: %s\n",
5163 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005164
5165 // TODO: print out if wide-color mode is active or not
5166
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005167 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005168 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005169 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005170 continue;
5171 }
5172
Yiwei Zhang5434a782018-12-05 18:06:32 -08005173 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005174 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005175 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005176 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005177 }
5178
Lloyd Pique32cbe282018-10-19 13:09:22 -07005179 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005180 StringAppendF(&result, " Current color mode: %s (%d)\n",
5181 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005182 }
5183 result.append("\n");
5184}
5185
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005186LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005187 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005188 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005189 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005190 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005191
chaviw1d044282017-09-27 12:19:28 -07005192 return layersProto;
5193}
5194
chaviw0a398992021-08-13 10:13:01 -05005195void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005196 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005197 DisplayProto* displayProto = layersTraceProto.add_displays();
5198 displayProto->set_id(display->getId().value);
5199 displayProto->set_name(display->getDisplayName());
5200 displayProto->set_layer_stack(display->getLayerStack().id);
5201 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5202 [&]() { return displayProto->mutable_size(); });
5203 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5204 return displayProto->mutable_layer_stack_space_rect();
5205 });
5206 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5207 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005208 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005209 }
5210}
5211
Alec Mouri6b9e9912020-01-21 10:50:24 -08005212void SurfaceFlinger::dumpHwc(std::string& result) const {
5213 getHwComposer().dump(result);
5214}
5215
Vishnu Nair0f085c62019-08-30 08:49:12 -07005216void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5217 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5218 // it.
5219 LayerProto* rootProto = layersProto.add_layers();
5220 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5221 rootProto->set_id(offscreenRootLayerId);
5222 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005223 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005224
5225 for (Layer* offscreenLayer : mOffscreenLayers) {
5226 // Add layer as child of the fake root
5227 rootProto->add_children(offscreenLayer->sequence);
5228
5229 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005230 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005231 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005232 }
5233}
5234
Vishnu Nair8406fd72019-07-30 11:29:31 -07005235LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005236 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005237}
5238
Vishnu Nair0f085c62019-08-30 08:49:12 -07005239void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005240 auto future = mScheduler->schedule([this] {
5241 std::string result;
5242 for (Layer* offscreenLayer : mOffscreenLayers) {
5243 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5244 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5245 }
5246 return result;
5247 });
5248
Vishnu Nair0f085c62019-08-30 08:49:12 -07005249 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005250 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005251}
5252
Dominik Laskowskic2867142019-01-21 11:33:38 -08005253void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5254 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005255 Colorizer colorizer(colorize);
5256
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005257 // figure out if we're stuck somewhere
5258 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005259 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005260 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5261
5262 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005263 * Dump library configuration.
5264 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005265
5266 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005267 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005268 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005269 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005270 result.append("\n");
5271
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005272 result.append("\nDisplay identification data:\n");
5273 dumpDisplayIdentificationData(result);
5274
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005275 result.append("\nWide-Color information:\n");
5276 dumpWideColorInfo(result);
5277
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005278 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005279 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005280 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005281 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005282 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005283
Andy McFadden41d67d72014-04-25 16:58:34 -07005284 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005285 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005286 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005287 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005288 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005289
Dan Stozab90cf072015-03-05 11:05:59 -08005290 dumpStaticScreenStats(result);
5291 result.append("\n");
5292
Alec Mouri40189b02019-03-05 15:07:54 -08005293 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5294 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5295 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005296
Andy McFadden4803b742012-09-24 19:07:20 -07005297 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005298 * Dump the visible layer list
5299 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005300 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005301 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005302 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005303
Chia-I Wu2f884132018-09-13 15:17:58 -07005304 {
Lloyd Pique207def92019-02-28 16:09:52 -08005305 StringAppendF(&result, "Composition layers\n");
5306 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005307 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005308 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005309
5310 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5311 layer->getDebugName() ? layer->getDebugName()
5312 : "<unknown>");
5313 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005314 });
5315 }
5316
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005317 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005318 * Dump Display state
5319 */
5320
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005321 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005322 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005323 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005324 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005325 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005326 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005327 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005328
5329 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005330 * Dump CompositionEngine state
5331 */
5332
5333 mCompositionEngine->dump(result);
5334
5335 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005336 * Dump SurfaceFlinger global state
5337 */
5338
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005339 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005340 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005341 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005342
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005343 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005344
Robert Carrbeba6f02021-02-10 21:06:27 -08005345 result.append("ClientCache state:\n");
5346 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005347 DebugEGLImageTracker::getInstance()->dump(result);
5348
Dominik Laskowski075d3172018-05-24 15:50:06 -07005349 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005350 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5351 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005352 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5353 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005354 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005355 StringAppendF(&result,
5356 " transaction-flags : %08x\n"
5357 " gpu_to_cpu_unsupported : %d\n",
5358 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005359
Marin Shalamanov045b7002021-01-07 16:56:24 +01005360 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005361 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005362 if (const auto activeMode = display->getActiveMode()) {
5363 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005364
5365 const auto dpi = activeMode->getDpi();
5366 xDpi = base::StringPrintf("%.2f", dpi.x);
5367 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005368 } else {
5369 fps = "unknown";
5370 xDpi = "unknown";
5371 yDpi = "unknown";
5372 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005373 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005374 " refresh-rate : %s\n"
5375 " x-dpi : %s\n"
5376 " y-dpi : %s\n",
5377 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005378 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005379
Yiwei Zhang5434a782018-12-05 18:06:32 -08005380 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005381
Dan Stozae22aec72016-08-01 13:20:59 -07005382 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005383 * Tracing state
5384 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005385 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005386
5387 result.append("\nTransaction tracing: ");
5388 if (mTransactionTracing) {
5389 result.append("enabled\n");
5390 mTransactionTracing->dump(result);
5391 } else {
5392 result.append("disabled\n");
5393 }
5394 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005395
5396 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005397 * HWC layer minidump
5398 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005399 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005400 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005401 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005402 continue;
5403 }
5404
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005405 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5406 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005407 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005408
5409 const DisplayDevice& ref = *display;
5410 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005411 result.append("\n");
5412 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005413
Ady Abraham2790e9f2021-04-28 13:14:20 -07005414 {
5415 DumpArgs plannerArgs;
5416 plannerArgs.add(); // first argument is ignored
5417 plannerArgs.add(String16("--layers"));
5418 dumpPlannerInfo(plannerArgs, result);
5419 }
5420
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005421 /*
5422 * Dump HWComposer state
5423 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005424 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005425 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005426 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005427 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005428 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005429 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005430
5431 /*
5432 * Dump gralloc state
5433 */
5434 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5435 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005436
rnleea2ecd832021-07-29 13:58:30 -07005437 /*
5438 * Dump flag/property manager state
5439 */
Robert Carr9b623c32022-03-21 15:55:22 -07005440 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005441
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005442 result.append(mTimeStats->miniDump());
5443 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005444}
5445
chaviw17ac24b2021-01-28 18:50:05 -08005446mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5447 if (saturation == 1) {
5448 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005449 }
5450
chaviw17ac24b2021-01-28 18:50:05 -08005451 float3 luminance{0.213f, 0.715f, 0.072f};
5452 luminance *= 1.0f - saturation;
5453 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5454 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5455 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5456 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5457 return saturationMatrix;
5458}
5459
5460void SurfaceFlinger::updateColorMatrixLocked() {
5461 mat4 colorMatrix =
5462 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5463
Chia-I Wu28f320b2018-05-03 11:02:56 -07005464 if (mCurrentState.colorMatrix != colorMatrix) {
5465 mCurrentState.colorMatrix = colorMatrix;
5466 mCurrentState.colorMatrixChanged = true;
5467 setTransactionFlags(eTransactionNeeded);
5468 }
5469}
5470
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005471status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005472#pragma clang diagnostic push
5473#pragma clang diagnostic error "-Wswitch-enum"
5474 switch (static_cast<ISurfaceComposerTag>(code)) {
5475 // These methods should at minimum make sure that the client requested
5476 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005477 case BOOT_FINISHED:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005478 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005479 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005480 case GET_GAME_CONTENT_TYPE_SUPPORT:
Steven Thomasd4071902020-03-24 16:02:53 -07005481 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005482 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5483 // permission dynamically. Don't use the permission cache for this check.
5484 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005485 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005486 IPCThreadState* ipc = IPCThreadState::self();
5487 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5488 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005489 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005490 }
Robert Carr1db73f62016-12-21 12:58:51 -08005491 return OK;
5492 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005493 // Used by apps to hook Choreographer to SurfaceFlinger.
5494 case CREATE_DISPLAY_EVENT_CONNECTION:
5495 // The following calls are currently used by clients that do not
5496 // request necessary permissions. However, they do not expose any secret
5497 // information, so it is OK to pass them.
Peiyong Lind1fedb42019-03-11 17:48:41 -07005498 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005499 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005500 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005501 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005502 // Calling setTransactionState is safe, because you need to have been
5503 // granted a reference to Client* and Handle* to do anything with it.
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005504 case SET_TRANSACTION_STATE: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005505 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005506 return OK;
5507 }
Huihong Luod3d8f8e2022-03-08 14:48:46 -08005508 case CREATE_CONNECTION:
Huihong Luo07e72362022-02-14 14:26:04 -08005509 case CREATE_DISPLAY:
5510 case DESTROY_DISPLAY:
5511 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5512 case GET_PHYSICAL_DISPLAY_IDS:
5513 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo3bdef862022-03-03 11:57:19 -08005514 case AUTHENTICATE_SURFACE:
Huihong Luo37396db2022-02-15 10:43:00 -08005515 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005516 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005517 case GET_DISPLAY_STATE:
5518 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005519 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005520 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005521 case GET_DISPLAY_NATIVE_PRIMARIES:
5522 case SET_ACTIVE_COLOR_MODE:
5523 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005524 case CLEAR_BOOT_DISPLAY_MODE:
5525 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5526 case SET_AUTO_LOW_LATENCY_MODE:
5527 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005528 case CAPTURE_LAYERS:
5529 case CAPTURE_DISPLAY:
5530 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005531 case CLEAR_ANIMATION_FRAME_STATS:
5532 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005533 case OVERRIDE_HDR_TYPES:
5534 case ON_PULL_ATOM:
5535 case ENABLE_VSYNC_INJECTIONS:
5536 case INJECT_VSYNC:
5537 case GET_LAYER_DEBUG_INFO:
5538 case GET_COLOR_MANAGEMENT:
5539 case GET_COMPOSITION_PREFERENCE:
5540 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5541 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Huihong Luo3bdef862022-03-03 11:57:19 -08005542 case GET_DISPLAYED_CONTENT_SAMPLE:
Huihong Luo05539a12022-02-23 10:29:40 -08005543 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005544 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005545 case ADD_REGION_SAMPLING_LISTENER:
5546 case REMOVE_REGION_SAMPLING_LISTENER:
5547 case ADD_FPS_LISTENER:
5548 case REMOVE_FPS_LISTENER:
5549 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5550 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5551 case ADD_WINDOW_INFOS_LISTENER:
5552 case REMOVE_WINDOW_INFOS_LISTENER:
5553 case SET_DESIRED_DISPLAY_MODE_SPECS:
5554 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005555 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5556 case SET_DISPLAY_BRIGHTNESS:
5557 case ADD_HDR_LAYER_INFO_LISTENER:
5558 case REMOVE_HDR_LAYER_INFO_LISTENER:
5559 case NOTIFY_POWER_BOOST:
Huihong Luo3bdef862022-03-03 11:57:19 -08005560 case SET_GLOBAL_SHADOW_SETTINGS:
5561 case GET_DISPLAY_DECORATION_SUPPORT:
5562 case SET_FRAME_RATE:
5563 case SET_OVERRIDE_FRAME_RATE:
5564 case SET_FRAME_TIMELINE_INFO:
Huihong Luo02186fb2022-02-23 14:21:54 -08005565 case ADD_TRANSACTION_TRACE_LISTENER:
5566 case GET_GPU_CONTEXT_PRIORITY:
5567 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005568 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005569 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005570 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005571
5572 // These codes are used for the IBinder protocol to either interrogate the recipient
5573 // side of the transaction for its canonical interface descriptor or to dump its state.
5574 // We let them pass by default.
5575 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5576 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5577 code == IBinder::SYSPROPS_TRANSACTION) {
5578 return OK;
5579 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005580 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005581 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005582 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005583 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5584 return OK;
5585 }
5586 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5587 return PERMISSION_DENIED;
5588#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005589}
5590
Ana Krulec13be8ad2018-08-21 02:43:56 +00005591status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5592 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005593 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5594 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005595 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005596
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005597 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5598 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005599 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005600 IPCThreadState* ipc = IPCThreadState::self();
5601 const int uid = ipc->getCallingUid();
5602 if (CC_UNLIKELY(uid != AID_SYSTEM
5603 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005604 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005605 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005606 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005607 return PERMISSION_DENIED;
5608 }
5609 int n;
5610 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005611 case 1000: // Unused.
5612 case 1001:
5613 return NAME_NOT_FOUND;
5614 case 1002: // Toggle flashing on surface damage.
5615 if (const int delay = data.readInt32(); delay > 0) {
5616 mDebugFlashDelay = delay;
5617 } else {
5618 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5619 }
5620 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005621 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005622 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005623 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005624 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005625 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005626 case 1005: { // Force commit ahead of next VSYNC.
5627 Mutex::Autolock lock(mStateLock);
5628 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5629 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005630 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005631 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005632 case 1007: // Unused.
5633 return NAME_NOT_FOUND;
5634 case 1008: // Toggle forced GPU composition.
5635 mDebugDisableHWC = data.readInt32() != 0;
5636 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005637 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005638 case 1009: // Toggle use of transform hint.
5639 mDebugDisableTransformHint = data.readInt32() != 0;
5640 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005641 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005642 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005643 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005644 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005645 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005646 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005647 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005648 return NO_ERROR;
5649 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005650 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005651 if (!display) {
5652 return NAME_NOT_FOUND;
5653 }
5654
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005655 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005656 return NO_ERROR;
5657 }
5658 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005659 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005660 // daltonize
5661 n = data.readInt32();
5662 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005663 case 1:
5664 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5665 break;
5666 case 2:
5667 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5668 break;
5669 case 3:
5670 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5671 break;
5672 default:
5673 mDaltonizer.setType(ColorBlindnessType::None);
5674 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005675 }
5676 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005677 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005678 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005679 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005680 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005681
5682 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005683 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005684 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005685 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005686 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005687 // apply a color matrix
5688 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005689 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005690 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005691 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005692 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005693 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005694 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005695 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005696 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005697 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005698 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005699
5700 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5701 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005702 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005703 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5704 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5705 }
5706
Chia-I Wu28f320b2018-05-03 11:02:56 -07005707 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005708 return NO_ERROR;
5709 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005710 case 1016: { // Unused.
5711 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005712 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005713 case 1017: {
5714 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005715 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005716 return NO_ERROR;
5717 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005718 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005719 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005720 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005721 return NO_ERROR;
5722 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005723 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005724 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005725 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005726 return NO_ERROR;
5727 }
Irvel468051e2016-06-13 16:44:44 -07005728 case 1020: { // Layer updates interceptor
5729 n = data.readInt32();
5730 if (n) {
5731 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005732 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005733 }
5734 else{
5735 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005736 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005737 }
5738 return NO_ERROR;
5739 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005740 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005741 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005742 static_cast<void>(
5743 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005744 return NO_ERROR;
5745 }
Romain Guy0147a172017-06-01 13:53:56 -07005746 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005747 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005748 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005749
Chia-I Wu28f320b2018-05-03 11:02:56 -07005750 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005751 return NO_ERROR;
5752 }
Romain Guy54f154a2017-10-24 21:40:32 +01005753 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005754 int32_t colorMode;
5755
Chia-I Wu0d711262018-05-21 15:19:35 -07005756 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005757 if (data.readInt32(&colorMode) == NO_ERROR) {
5758 mForceColorMode = static_cast<ColorMode>(colorMode);
5759 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005760 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005761 return NO_ERROR;
5762 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005763 // Deprecate, use 1030 to check whether the device is color managed.
5764 case 1024: {
5765 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005766 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005767 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005768 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005769 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005770 if (n == 1) {
5771 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005772 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005773 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005774 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005775 int64_t startingTime =
5776 (fixedStartingTime) ? fixedStartingTime : systemTime();
5777 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005778 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005779 mLayerTracing.notify("start", startingTime);
5780 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005781 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005782 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005783 } else if (n == 2) {
5784 std::string filename = std::string(data.readCString());
5785 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5786 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005787 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005788 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005789 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005790 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005791 mTracingEnabledChanged = tracingEnabledChanged;
5792 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005793 return NO_ERROR;
5794 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005795 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005796 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005797 return NO_ERROR;
5798 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005799 // Is a DisplayColorSetting supported?
5800 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005801 const auto display = getDefaultDisplayDevice();
5802 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005803 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005804 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005805
5806 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5807 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005808 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005809 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005810 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005811 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005812 reply->writeBool(true);
5813 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005814 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005815 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005816 break;
5817 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005818 reply->writeBool(
5819 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005820 break;
5821 }
5822 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005823 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005824 case 1028: { // Unused.
5825 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005826 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005827 // Set buffer size for SF tracing (value in KB)
5828 case 1029: {
5829 n = data.readInt32();
5830 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5831 ALOGW("Invalid buffer size: %d KB", n);
5832 reply->writeInt32(BAD_VALUE);
5833 return BAD_VALUE;
5834 }
5835
5836 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005837 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005838 reply->writeInt32(NO_ERROR);
5839 return NO_ERROR;
5840 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005841 // Is device color managed?
5842 case 1030: {
5843 reply->writeBool(useColorManagement);
5844 return NO_ERROR;
5845 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005846 // Override default composition data space
5847 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5848 // && adb shell stop zygote && adb shell start zygote
5849 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5850 // adb shell stop zygote && adb shell start zygote
5851 case 1031: {
5852 Mutex::Autolock _l(mStateLock);
5853 n = data.readInt32();
5854 if (n) {
5855 n = data.readInt32();
5856 if (n) {
5857 Dataspace dataspace = static_cast<Dataspace>(n);
5858 if (!validateCompositionDataspace(dataspace)) {
5859 return BAD_VALUE;
5860 }
5861 mDefaultCompositionDataspace = dataspace;
5862 }
5863 n = data.readInt32();
5864 if (n) {
5865 Dataspace dataspace = static_cast<Dataspace>(n);
5866 if (!validateCompositionDataspace(dataspace)) {
5867 return BAD_VALUE;
5868 }
5869 mWideColorGamutCompositionDataspace = dataspace;
5870 }
5871 } else {
5872 // restore composition data space.
5873 mDefaultCompositionDataspace = defaultCompositionDataspace;
5874 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5875 }
5876 return NO_ERROR;
5877 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005878 // Set trace flags
5879 case 1033: {
5880 n = data.readUint32();
5881 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005882 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005883 reply->writeInt32(NO_ERROR);
5884 return NO_ERROR;
5885 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005886 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005887 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005888 switch (n = data.readInt32()) {
5889 case 0:
5890 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005891 FTL_FAKE_GUARD(mStateLock,
5892 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005893 break;
5894 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005895 reply->writeBool(
5896 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005897 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005898 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005899 });
5900
5901 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005902 return NO_ERROR;
5903 }
Ady Abraham34392f72019-04-10 11:29:27 -07005904 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005905 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005906
Dominik Laskowskif1833852021-03-23 15:06:50 -07005907 const auto display = [&]() -> sp<IBinder> {
5908 uint64_t value;
5909 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005910 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005911 }
5912
Dominik Laskowskif1833852021-03-23 15:06:50 -07005913 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5914 return getPhysicalDisplayToken(*id);
5915 }
5916
5917 ALOGE("Invalid physical display ID");
5918 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005919 }();
5920
Shiyong Li2bcece92021-08-30 20:38:50 +00005921 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005922 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005923 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5924 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005925 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005926 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5927 // manager frame rate policy a new policy which allows switching between all refresh
5928 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005929 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005930 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005931 return mScheduler
5932 ->schedule([this] {
5933 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005934 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005935
Dominik Laskowski756b7892021-08-04 12:53:59 -07005936 // This is a little racy, but not in a way that hurts anything. As
5937 // we grab the defaultMode from the display manager policy, we could
5938 // be setting a new display manager policy, leaving us using a stale
5939 // defaultMode. The defaultMode doesn't matter for the override
5940 // policy though, since we set allowGroupSwitching to true, so it's
5941 // not a problem.
5942 scheduler::RefreshRateConfigs::Policy overridePolicy;
5943 overridePolicy.defaultMode = display->refreshRateConfigs()
5944 .getDisplayManagerPolicy()
5945 .defaultMode;
5946 overridePolicy.allowGroupSwitching = true;
5947 constexpr bool kOverridePolicy = true;
5948 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5949 kOverridePolicy);
5950 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005951 .get();
5952 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07005953 return mScheduler
5954 ->schedule([this] {
5955 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005956 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07005957 constexpr bool kOverridePolicy = true;
5958 return setDesiredDisplayModeSpecsInternal(display, {},
5959 kOverridePolicy);
5960 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005961 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07005962 }
Ady Abraham07e54702020-04-16 15:05:37 -07005963 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02005964 // Inject a hotplug connected event for the primary display. This will deallocate and
5965 // reallocate the display state including framebuffers.
5966 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07005967 const hal::HWDisplayId hwcId =
5968 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
5969
5970 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02005971 return NO_ERROR;
5972 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07005973 // Modify the max number of display frames stored within FrameTimeline
5974 case 1038: {
5975 n = data.readInt32();
5976 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
5977 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
5978 return BAD_VALUE;
5979 }
5980 if (n == 0) {
5981 // restore to default
5982 mFrameTimeline->reset();
5983 return NO_ERROR;
5984 }
5985 mFrameTimeline->setMaxDisplayFrames(n);
5986 return NO_ERROR;
5987 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07005988 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07005989 PhysicalDisplayId displayId = [&]() {
5990 Mutex::Autolock lock(mStateLock);
5991 return getDefaultDisplayDeviceLocked()->getPhysicalId();
5992 }();
5993
5994 auto inUid = static_cast<uid_t>(data.readInt32());
5995 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08005996 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
5997 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07005998 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08005999 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006000 // Toggle caching feature
6001 // First argument is an int32 - nonzero enables caching and zero disables caching
6002 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6003 // caching to a particular physical display
6004 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006005 auto future = mScheduler->schedule([&] {
6006 n = data.readInt32();
6007 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6008 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6009 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6010 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6011 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6012 return NAME_NOT_FOUND;
6013 }
6014 }
6015 {
6016 Mutex::Autolock lock(mStateLock);
6017 mLayerCachingEnabled = n != 0;
6018 for (const auto& [_, display] : mDisplays) {
6019 if (!inputId || *inputId == display->getPhysicalId()) {
6020 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006021 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006022 }
6023 }
6024 return OK;
6025 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006026
Dominik Laskowski756b7892021-08-04 12:53:59 -07006027 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006028 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006029 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006030 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006031 return NO_ERROR;
6032 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006033 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006034 if (mTransactionTracing) {
6035 if (data.readInt32()) {
6036 // Transaction tracing is always running but allow the user to temporarily
6037 // increase the buffer when actively debugging.
6038 mTransactionTracing->setBufferSize(
6039 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6040 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006041 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006042 mTransactionTracing->setBufferSize(
6043 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006044 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006045 }
6046 reply->writeInt32(NO_ERROR);
6047 return NO_ERROR;
6048 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006049 case 1042: { // Write layers trace or transaction trace to file
6050 if (mTransactionTracing) {
6051 mTransactionTracing->writeToFile();
6052 }
6053 if (mLayerTracingEnabled) {
6054 mLayerTracing.writeToFile();
6055 }
6056 reply->writeInt32(NO_ERROR);
6057 return NO_ERROR;
6058 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006059 }
6060 }
6061 return err;
6062}
6063
Ady Abrahama09852a2020-02-20 14:23:42 -08006064void SurfaceFlinger::kernelTimerChanged(bool expired) {
6065 static bool updateOverlay =
6066 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006067 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006068
6069 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006070 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006071 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006072 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006073 if (!display) {
6074 ALOGW("%s: default display is null", __func__);
6075 return;
6076 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006077 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006078
6079 const auto desiredActiveMode = display->getDesiredActiveMode();
6080 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6081 ? std::make_optional(desiredActiveMode->mode->getId())
6082 : std::nullopt;
6083
6084 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6085
Ady Abraham1b11bc62021-06-03 19:51:19 -07006086 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006087 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006088 }
6089 }));
6090}
6091
ramindani32cf0602022-03-02 02:30:29 +00006092std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6093SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6094 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6095 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6096 const auto timeout = getIdleTimerTimeout(displayId);
6097 if (isKernelIdleTimerHwcSupported) {
6098 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6099 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6100 // In order to decide if we can use the HWC api for idle timer
6101 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6102 // without relying on hasDisplayCapability.
6103 // hasDisplayCapability relies on DisplayCapabilities
6104 // which are updated after we set the PowerMode::ON.
6105 // DISPLAY_IDLE_TIMER is a display driver property
6106 // and is available before the PowerMode::ON
6107 return {KernelIdleTimerController::HwcApi, timeout};
6108 }
6109 return {std::nullopt, timeout};
6110 }
6111 if (getKernelIdleTimerSyspropConfig(displayId)) {
6112 return {KernelIdleTimerController::Sysprop, timeout};
6113 }
6114
6115 return {std::nullopt, timeout};
6116}
6117
6118void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6119 KernelIdleTimerController controller,
6120 PhysicalDisplayId displayId) {
6121 switch (controller) {
6122 case KernelIdleTimerController::HwcApi: {
6123 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6124 break;
6125 }
6126 case KernelIdleTimerController::Sysprop: {
6127 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6128 break;
6129 }
6130 }
6131}
6132
Ana Krulecb9afd792020-06-11 13:16:15 -07006133void SurfaceFlinger::toggleKernelIdleTimer() {
6134 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6135
Ady Abraham3efa3942021-06-24 19:01:25 -07006136 const auto display = getDefaultDisplayDeviceLocked();
6137 if (!display) {
6138 ALOGW("%s: default display is null", __func__);
6139 return;
6140 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006141
Ady Abrahame9316b72021-09-24 17:04:36 -07006142 // If the support for kernel idle timer is disabled for the active display,
6143 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006144 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6145 display->refreshRateConfigs().kernelIdleTimerController();
6146 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006147 return;
6148 }
6149
Ady Abraham3efa3942021-06-24 19:01:25 -07006150 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006151
Ana Krulecb9afd792020-06-11 13:16:15 -07006152 switch (action) {
6153 case KernelIdleTimerAction::TurnOff:
6154 if (mKernelIdleTimerEnabled) {
6155 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006156 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6157 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6158 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006159 mKernelIdleTimerEnabled = false;
6160 }
6161 break;
6162 case KernelIdleTimerAction::TurnOn:
6163 if (!mKernelIdleTimerEnabled) {
6164 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006165 const std::chrono::milliseconds timeout =
6166 display->refreshRateConfigs().getIdleTimerTimeout();
6167 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6168 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006169 mKernelIdleTimerEnabled = true;
6170 }
6171 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006172 }
6173}
6174
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006175// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6176class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006177public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006178 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6179 ~WindowDisconnector() {
6180 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006181 }
6182
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006183private:
6184 ANativeWindow* mWindow;
6185 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006186};
6187
chaviw93df2ea2019-04-30 16:45:12 -07006188static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6189 switch (colorMode) {
6190 case ColorMode::DISPLAY_P3:
6191 case ColorMode::BT2100_PQ:
6192 case ColorMode::BT2100_HLG:
6193 case ColorMode::DISPLAY_BT2020:
6194 return Dataspace::DISPLAY_P3;
6195 default:
6196 return Dataspace::V0_SRGB;
6197 }
6198}
6199
chaviwf5bb97b2021-04-28 15:35:37 -05006200static bool hasCaptureBlackoutContentPermission() {
6201 IPCThreadState* ipc = IPCThreadState::self();
6202 const int pid = ipc->getCallingPid();
6203 const int uid = ipc->getCallingUid();
6204 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6205 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6206}
6207
chaviw4b9d5e12020-08-04 18:30:35 -07006208static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6209 IPCThreadState* ipc = IPCThreadState::self();
6210 const int pid = ipc->getCallingPid();
6211 const int uid = ipc->getCallingUid();
6212 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6213 return OK;
6214 }
6215
6216 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6217 // itself, we allow it to continue.
6218 if (captureArgs.uid == uid) {
6219 return OK;
6220 }
6221
6222 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6223 return PERMISSION_DENIED;
6224}
6225
Peiyong Lin05cc0112020-10-14 16:16:37 -07006226status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6227 static constexpr int kFifoPriority = 2;
6228 static constexpr int kOtherPriority = 0;
6229
6230 struct sched_param param = {0};
6231 int sched_policy;
6232 if (enabled) {
6233 sched_policy = SCHED_FIFO;
6234 param.sched_priority = kFifoPriority;
6235 } else {
6236 sched_policy = SCHED_OTHER;
6237 param.sched_priority = kOtherPriority;
6238 }
6239
6240 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6241 return -errno;
6242 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006243
6244 return NO_ERROR;
6245}
6246
6247status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6248 static const unsigned int kUclampMin =
6249 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6250
6251 if (!kUclampMin) {
6252 // uclamp.min set to 0 (default), skip setting
6253 return NO_ERROR;
6254 }
6255
6256 // Currently, there is no wrapper in bionic: b/183240349.
6257 struct sched_attr {
6258 uint32_t size;
6259 uint32_t sched_policy;
6260 uint64_t sched_flags;
6261 int32_t sched_nice;
6262 uint32_t sched_priority;
6263 uint64_t sched_runtime;
6264 uint64_t sched_deadline;
6265 uint64_t sched_period;
6266 uint32_t sched_util_min;
6267 uint32_t sched_util_max;
6268 };
6269
6270 sched_attr attr = {};
6271 attr.size = sizeof(attr);
6272
6273 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6274 attr.sched_util_min = enabled ? kUclampMin : 0;
6275 attr.sched_util_max = 1024;
6276
6277 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6278 return -errno;
6279 }
6280
Peiyong Lin05cc0112020-10-14 16:16:37 -07006281 return NO_ERROR;
6282}
6283
chaviwd2432892020-07-24 17:42:39 -07006284status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006285 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006286 ATRACE_CALL();
6287
chaviw4b9d5e12020-08-04 18:30:35 -07006288 status_t validate = validateScreenshotPermissions(args);
6289 if (validate != OK) {
6290 return validate;
6291 }
6292
chaviwd2432892020-07-24 17:42:39 -07006293 if (!args.displayToken) return BAD_VALUE;
6294
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006295 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006296 ui::LayerStack layerStack;
6297 ui::Size reqSize(args.width, args.height);
6298 ui::Dataspace dataspace;
6299 {
6300 Mutex::Autolock lock(mStateLock);
6301 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6302 if (!display) return NAME_NOT_FOUND;
6303 displayWeak = display;
6304 layerStack = display->getLayerStack();
6305
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006306 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006307 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006308 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006309 }
6310
arthurhung79e81aa2020-08-28 00:09:19 +08006311 // The dataspace is depended on the color mode of display, that could use non-native mode
6312 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6313 // and failed if display is not in native mode. This provide a way to force using native
6314 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006315 dataspace = args.dataspace;
6316 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006317 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6318 dataspace = pickDataspaceFromColorMode(colorMode);
6319 }
chaviwd2432892020-07-24 17:42:39 -07006320 }
6321
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006322 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006323 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006324 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006325 });
6326
chaviw4b9d5e12020-08-04 18:30:35 -07006327 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6328 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006329 };
chaviw03900772020-08-18 12:34:51 -07006330
Sally Qi59a9f502021-10-12 18:53:23 +00006331 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6332 reqSize, args.pixelFormat, args.allowProtected,
6333 args.grayscale, captureListener);
6334 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006335}
6336
Dominik Laskowskif1833852021-03-23 15:06:50 -07006337status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006338 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006339 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006340 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006341 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006342 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006343 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006344 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006345
Dominik Laskowskif1833852021-03-23 15:06:50 -07006346 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006347 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006348 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006349 }
6350
chaviw93df2ea2019-04-30 16:45:12 -07006351 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006352 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006353 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006354
chaviw426b5c02020-07-27 11:20:15 -07006355 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006356 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6357 }
6358
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006359 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006360 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006361 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006362 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006363 });
chaviw93df2ea2019-04-30 16:45:12 -07006364
Marin Shalamanov1c434292020-06-12 01:47:29 +02006365 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006366 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006367 };
6368
Sally Qi59a9f502021-10-12 18:53:23 +00006369 if (captureListener == nullptr) {
6370 ALOGE("capture screen must provide a capture listener callback");
6371 return BAD_VALUE;
6372 }
6373 auto captureResultFuture =
6374 captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6375 ui::PixelFormat::RGBA_8888, false /* allowProtected */,
6376 false /* grayscale */, captureListener);
6377 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006378}
6379
chaviw3efadb12020-07-27 10:07:15 -07006380status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006381 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006382 ATRACE_CALL();
6383
chaviw4b9d5e12020-08-04 18:30:35 -07006384 status_t validate = validateScreenshotPermissions(args);
6385 if (validate != OK) {
6386 return validate;
6387 }
6388
Marin Shalamanov1c434292020-06-12 01:47:29 +02006389 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006390 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006391 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006392 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006393 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006394
6395 // Call this before holding mStateLock to avoid any deadlocking.
6396 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6397
Robert Carrc0df3122019-04-11 13:18:21 -07006398 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006399 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006400
Vishnu Nairf9096652021-07-20 18:49:42 -07006401 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006402 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006403 ALOGE("captureLayers called with an invalid or removed parent");
6404 return NAME_NOT_FOUND;
6405 }
6406
chaviwf5bb97b2021-04-28 15:35:37 -05006407 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006408 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006409 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6410 return PERMISSION_DENIED;
6411 }
6412
Robert Carr6a160312021-05-17 12:08:20 -07006413 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006414 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006415 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006416 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006417 }
6418
chaviw3efadb12020-07-27 10:07:15 -07006419 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006420 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006421 crop.bottom = parentSourceBounds.getHeight();
6422 }
6423
chaviw17ac24b2021-01-28 18:50:05 -08006424 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006425 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6426 // crop was not specified, or an invalid frame scale was provided.
6427 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006428 }
chaviw17ac24b2021-01-28 18:50:05 -08006429 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006430
chaviw3efadb12020-07-27 10:07:15 -07006431 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006432 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006433 if (excludeLayer != nullptr) {
6434 excludeLayers.emplace(excludeLayer);
6435 } else {
6436 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6437 return NAME_NOT_FOUND;
6438 }
6439 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006440
arthurhung79e81aa2020-08-28 00:09:19 +08006441 // The dataspace is depended on the color mode of display, that could use non-native mode
6442 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6443 // and failed if display is not in native mode. This provide a way to force using native
6444 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006445 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006446 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006447
Chia-I Wu20261cb2018-08-23 12:55:44 -07006448 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006449 if (reqSize.width <= 0 || reqSize.height <= 0) {
6450 ALOGW("Failed to captureLayes: crop or scale too small");
6451 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006452 }
6453
chaviw79468ab2021-10-27 11:11:24 -05006454 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006455 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006456 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006457 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006458 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006459 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006460 });
6461
chaviw03900772020-08-18 12:34:51 -07006462 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006463 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6464 if (!layer->isVisible()) {
6465 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006466 } else if (args.childrenOnly && layer == parent.get()) {
6467 return;
6468 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006469 return;
chaviwa76b2712017-09-20 12:02:26 -07006470 }
Robert Carr866455f2019-04-02 16:28:26 -07006471
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006472 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006473 while (p != nullptr) {
6474 if (excludeLayers.count(p) != 0) {
6475 return;
6476 }
6477 p = p->getParent();
6478 }
6479
chaviwa76b2712017-09-20 12:02:26 -07006480 visitor(layer);
6481 });
6482 };
Robert Carr108b2c72019-04-02 16:32:58 -07006483
Sally Qi59a9f502021-10-12 18:53:23 +00006484 if (captureListener == nullptr) {
6485 ALOGE("capture screen must provide a capture listener callback");
6486 return BAD_VALUE;
6487 }
6488
6489 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6490 reqSize, args.pixelFormat, args.allowProtected,
6491 args.grayscale, captureListener);
6492 return captureResultFuture.get().status;
chaviwa76b2712017-09-20 12:02:26 -07006493}
6494
Sally Qi59a9f502021-10-12 18:53:23 +00006495std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
6496 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6497 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6498 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006499 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006500
Garfield Tan9c9c1912021-07-19 12:02:16 -07006501 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6502 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6503 ") that exceeds render target size limit.",
6504 bufferSize.getWidth(), bufferSize.getHeight());
Sally Qi59a9f502021-10-12 18:53:23 +00006505 return ftl::yield<renderengine::RenderEngineResult>({BAD_VALUE, base::unique_fd()}).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006506 }
6507
Peiyong Lin05cc0112020-10-14 16:16:37 -07006508 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6509 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6510 // A protected layer has no implication on whether it's secure, which is explicitly set by
6511 // application to avoid being screenshot or drawn via unsecure display.
6512 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6513 bool hasProtectedLayer = false;
6514 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006515 auto future = mScheduler->schedule([=]() {
6516 bool protectedLayerFound = false;
6517 traverseLayers([&](Layer* layer) {
6518 protectedLayerFound =
6519 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6520 });
6521 return protectedLayerFound;
6522 });
6523 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006524 }
6525
Richard Liucbcb8952020-04-08 10:51:55 +00006526 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6527 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006528 (hasProtectedLayer && allowProtected && supportsProtected
6529 ? GRALLOC_USAGE_PROTECTED
6530 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006531 sp<GraphicBuffer> buffer =
6532 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6533 static_cast<android_pixel_format>(reqPixelFormat),
6534 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006535
6536 const status_t bufferStatus = buffer->initCheck();
6537 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6538 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006539 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6540 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6541 renderengine::impl::ExternalTexture::Usage::
6542 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006543 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006544 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006545}
6546
Sally Qi59a9f502021-10-12 18:53:23 +00006547std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006548 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6549 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6550 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006551 ATRACE_CALL();
6552
chaviwf5bb97b2021-04-28 15:35:37 -05006553 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006554
Dominik Laskowski756b7892021-08-04 12:53:59 -07006555 auto scheduleResultFuture = mScheduler->schedule([=,
6556 renderAreaFuture =
6557 std::move(renderAreaFuture)]() mutable
6558 -> std::shared_future<
6559 renderengine::RenderEngineResult> {
chaviw03900772020-08-18 12:34:51 -07006560 ScreenCaptureResults captureResults;
6561 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6562 if (!renderArea) {
6563 ALOGW("Skipping screen capture because of invalid render area.");
6564 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006565 captureListener->onScreenCaptureCompleted(captureResults);
Sally Qi59a9f502021-10-12 18:53:23 +00006566 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()})
6567 .share();
chaviw03900772020-08-18 12:34:51 -07006568 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006569
Sally Qi59a9f502021-10-12 18:53:23 +00006570 std::shared_future<renderengine::RenderEngineResult> renderEngineResultFuture;
6571
chaviw03900772020-08-18 12:34:51 -07006572 renderArea->render([&] {
Sally Qi59a9f502021-10-12 18:53:23 +00006573 renderEngineResultFuture =
Robert Carr12a3b9b2022-03-10 09:55:29 -08006574 renderScreenImpl(*renderArea, traverseLayers, buffer,
Sally Qi59a9f502021-10-12 18:53:23 +00006575 canCaptureBlackoutContent, regionSampling, grayscale,
6576 captureResults);
chaviw03900772020-08-18 12:34:51 -07006577 });
Sally Qi59a9f502021-10-12 18:53:23 +00006578 // spring up a thread to unblock SF main thread and wait for
6579 // RenderEngineResult to be available
6580 if (captureListener != nullptr) {
6581 std::async([=]() mutable {
6582 ATRACE_NAME("captureListener is nonnull!");
6583 auto& [status, drawFence] = renderEngineResultFuture.get();
6584 captureResults.result = status;
6585 captureResults.fence = new Fence(dup(drawFence));
6586 captureListener->onScreenCaptureCompleted(captureResults);
6587 });
6588 }
6589 return renderEngineResultFuture;
6590 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006591
Sally Qi59a9f502021-10-12 18:53:23 +00006592 // flatten scheduleResultFuture object to single shared_future object
6593 if (captureListener == nullptr) {
6594 std::future<renderengine::RenderEngineResult> captureScreenResultFuture =
6595 ftl::chain(std::move(scheduleResultFuture))
6596 .then([=](std::shared_future<renderengine::RenderEngineResult> futureObject)
6597 -> renderengine::RenderEngineResult {
6598 auto& [status, drawFence] = futureObject.get();
6599 return {status, base::unique_fd(dup(drawFence))};
6600 });
6601 return captureScreenResultFuture.share();
6602 } else {
6603 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()}).share();
6604 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006605}
6606
Robert Carr12a3b9b2022-03-10 09:55:29 -08006607std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006608 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006609 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6610 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6611 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006612 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006613
chaviw426b5c02020-07-27 11:20:15 -07006614 traverseLayers([&](Layer* layer) {
6615 captureResults.capturedSecureLayers =
6616 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6617 });
6618
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006619 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006620
chaviw426b5c02020-07-27 11:20:15 -07006621 // We allow the system server to take screenshots of secure layers for
6622 // use in situations like the Screen-rotation animation and place
6623 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006624 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006625 ALOGW("FB is protected: PERMISSION_DENIED");
Sally Qi59a9f502021-10-12 18:53:23 +00006626 return ftl::yield<renderengine::RenderEngineResult>({PERMISSION_DENIED, base::unique_fd()})
6627 .share();
chaviw426b5c02020-07-27 11:20:15 -07006628 }
6629
Alec Mouria90a5702021-04-16 16:36:21 +00006630 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006631 auto dataspace = renderArea.getReqDataSpace();
6632 auto parent = renderArea.getParentLayer();
6633 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6634 Mutex::Autolock lock(mStateLock);
6635 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6636 return display.getLayerStack() == layerStack;
6637 });
6638 if (!display) {
6639 // If the layer is not on a display, use the dataspace for the default display.
6640 display = getDefaultDisplayDeviceLocked();
6641 }
6642
6643 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6644 dataspace = pickDataspaceFromColorMode(colorMode);
6645 }
6646 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006647
chaviwa76b2712017-09-20 12:02:26 -07006648 const auto reqWidth = renderArea.getReqWidth();
6649 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006650 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006651 const auto transform = renderArea.getTransform();
6652 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006653 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006654
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006655 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006656 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006657
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006658 // assume that bounds are never offset, and that they are the same as the
6659 // buffer bounds.
6660 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006661 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006662 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006663
Robert Carr12a3b9b2022-03-10 09:55:29 -08006664 clientCompositionDisplay.outputDataspace = dataspace;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006665 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006666
chaviw17ac24b2021-01-28 18:50:05 -08006667 const float colorSaturation = grayscale ? 0 : 1;
6668 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6669
chaviw50da5042018-04-09 13:49:37 -07006670 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006671
Vishnu Nair9b079a22020-01-21 14:36:08 -08006672 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006673 fillLayer.source.buffer.buffer = nullptr;
6674 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006675 fillLayer.geometry.boundaries =
6676 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006677 fillLayer.alpha = half(alpha);
6678 clientCompositionLayers.push_back(fillLayer);
6679
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006680 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006681 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006682 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006683 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006684 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006685
Lloyd Piquef16688f2019-02-19 17:47:57 -08006686 Region clip(renderArea.getBounds());
6687 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6688 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006689 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006690 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006691 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006692 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006693 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006694 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006695 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006696 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006697 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6698 BlurSetting::Disabled
6699 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6700 BlurSetting::Enabled,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006701 DisplayDevice::sDefaultMaxLumiance,
6702
Lloyd Piquef16688f2019-02-19 17:47:57 -08006703 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006704 std::vector<compositionengine::LayerFE::LayerSettings> results =
6705 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006706 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006707 for (auto& settings : results) {
6708 settings.geometry.positionTransform =
6709 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006710 // There's no need to process blurs when we're executing region sampling,
6711 // we're just trying to understand what we're drawing, and doing so without
6712 // blurs is already a pretty good approximation.
6713 if (regionSampling) {
6714 settings.backgroundBlurRadius = 0;
6715 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07006716 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006717
Yichi Chen40773d92020-04-01 10:10:18 +08006718 clientCompositionLayers.insert(clientCompositionLayers.end(),
6719 std::make_move_iterator(results.begin()),
6720 std::make_move_iterator(results.end()));
6721 renderedLayers.push_back(layer);
6722 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006723
chaviwa76b2712017-09-20 12:02:26 -07006724 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006725
Sally Qi59a9f502021-10-12 18:53:23 +00006726 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6727 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006728 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006729 std::back_inserter(clientRenderEngineLayers),
6730 [](compositionengine::LayerFE::LayerSettings& settings)
6731 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006732
Alec Mouri6338c9d2019-02-07 16:57:51 -08006733 // Use an empty fence for the buffer fence, since we just created the buffer so
6734 // there is no need for synchronization with the GPU.
6735 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006736 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006737
Alec Mouria90a5702021-04-16 16:36:21 +00006738 const constexpr bool kUseFramebufferCache = false;
Sally Qi59a9f502021-10-12 18:53:23 +00006739 std::future<renderengine::RenderEngineResult> drawLayersResult =
6740 getRenderEngine().drawLayers(clientCompositionDisplay, clientRenderEngineLayers, buffer,
6741 kUseFramebufferCache, std::move(bufferFence));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006742
Sally Qi59a9f502021-10-12 18:53:23 +00006743 std::shared_future<renderengine::RenderEngineResult> drawLayersResultFuture =
6744 drawLayersResult.share(); // drawLayersResult will be moved to shared one
6745
6746 for (auto* layer : renderedLayers) {
6747 // make a copy of shared_future object for each layer
6748 layer->onLayerDisplayed(drawLayersResultFuture);
Yichi Chen40773d92020-04-01 10:10:18 +08006749 }
Ady Abraham99599942021-01-27 20:27:23 -08006750
Peiyong Lin05cc0112020-10-14 16:16:37 -07006751 // Always switch back to unprotected context.
6752 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006753
Sally Qi59a9f502021-10-12 18:53:23 +00006754 return drawLayersResultFuture;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006755}
6756
chaviwbf023a62021-06-07 16:00:06 -05006757void SurfaceFlinger::windowInfosReported() {
chaviw95ef3c42019-02-14 10:55:09 -08006758 Mutex::Autolock _l(mStateLock);
Arthur Hung2274a312021-04-28 15:13:06 +00006759 signalSynchronousTransactions(CountDownLatch::eSyncInputWindows);
chaviw95ef3c42019-02-14 10:55:09 -08006760}
chaviw5f21a5e2019-02-14 10:00:34 -08006761
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006762// ---------------------------------------------------------------------------
6763
Edgar Arriaga844fa672020-01-16 14:21:42 -08006764void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6765 layersSortedByZ.traverse(visitor);
6766}
6767
Dan Stoza412903f2017-04-27 13:42:17 -07006768void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6769 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006770}
6771
Dan Stoza412903f2017-04-27 13:42:17 -07006772void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6773 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006774}
6775
chaviw4b9d5e12020-08-04 18:30:35 -07006776void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006777 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006778 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006779 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006780 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006781 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006782 continue;
6783 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006784 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006785 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006786 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006787 return;
6788 }
chaviwa76b2712017-09-20 12:02:26 -07006789 if (!layer->isVisible()) {
6790 return;
6791 }
chaviw4b9d5e12020-08-04 18:30:35 -07006792 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6793 return;
6794 }
chaviwa76b2712017-09-20 12:02:26 -07006795 visitor(layer);
6796 });
6797 }
6798}
6799
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006800status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006801 const sp<DisplayDevice>& display,
6802 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006803 Mutex::Autolock lock(mStateLock);
6804
Ady Abrahamfb853662021-04-09 11:46:40 -07006805 if (mDebugDisplayModeSetByBackdoor) {
6806 // ignore this request as mode is overridden by backdoor
6807 return NO_ERROR;
6808 }
6809
Ady Abraham3efa3942021-06-24 19:01:25 -07006810 status_t setPolicyResult = overridePolicy
6811 ? display->refreshRateConfigs().setOverridePolicy(policy)
6812 : display->refreshRateConfigs().setDisplayManagerPolicy(*policy);
6813 if (setPolicyResult < 0) {
6814 return BAD_VALUE;
6815 }
6816 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6817 return NO_ERROR;
6818 }
6819
Ady Abraham3efa3942021-06-24 19:01:25 -07006820 scheduler::RefreshRateConfigs::Policy currentPolicy =
6821 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006822
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006823 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006824
Ana Krulecb9afd792020-06-11 13:16:15 -07006825 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6826 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006827 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006828 if (isDisplayActiveLocked(display)) {
6829 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6830 toggleKernelIdleTimer();
6831 } else {
6832 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6833 }
Ady Abraham838de062019-02-04 10:24:03 -08006834
Ady Abraham690f4612021-07-01 23:24:03 -07006835 const DisplayModePtr preferredDisplayMode = [&] {
6836 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6837 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6838 return schedulerMode;
6839 }
6840
6841 return display->getMode(currentPolicy.defaultMode);
6842 }();
6843
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006844 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006845 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006846
Ady Abraham690f4612021-07-01 23:24:03 -07006847 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006848 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006849 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006850 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006851 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006852 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006853 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006854 }
6855
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006856 return NO_ERROR;
6857}
6858
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006859status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6860 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6861 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6862 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006863 ATRACE_CALL();
6864
6865 if (!displayToken) {
6866 return BAD_VALUE;
6867 }
6868
Dominik Laskowski756b7892021-08-04 12:53:59 -07006869 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006870 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006871 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006872 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006873 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006874 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006875 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006876 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006877 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006878 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006879 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006880 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006881 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006882 {Fps::fromValue(primaryRefreshRateMin),
6883 Fps::fromValue(primaryRefreshRateMax)},
6884 {Fps::fromValue(appRequestRefreshRateMin),
6885 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006886 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006887
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006888 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006889 }
6890 });
6891
6892 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006893}
6894
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006895status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6896 ui::DisplayModeId* outDefaultMode,
6897 bool* outAllowGroupSwitching,
6898 float* outPrimaryRefreshRateMin,
6899 float* outPrimaryRefreshRateMax,
6900 float* outAppRequestRefreshRateMin,
6901 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006902 ATRACE_CALL();
6903
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006904 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006905 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006906 return BAD_VALUE;
6907 }
6908
6909 Mutex::Autolock lock(mStateLock);
6910 const auto display = getDisplayDeviceLocked(displayToken);
6911 if (!display) {
6912 return NAME_NOT_FOUND;
6913 }
6914
Ady Abraham3efa3942021-06-24 19:01:25 -07006915 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006916 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006917 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006918
6919 scheduler::RefreshRateConfigs::Policy policy =
6920 display->refreshRateConfigs().getDisplayManagerPolicy();
6921 *outDefaultMode = policy.defaultMode.value();
6922 *outAllowGroupSwitching = policy.allowGroupSwitching;
6923 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6924 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6925 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6926 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6927 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006928}
6929
Vishnu Nairf9096652021-07-20 18:49:42 -07006930wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6931 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006932}
6933
Dominik Laskowski75848362019-11-11 17:57:20 -08006934void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006935 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006936 if (!layer->isRemovedFromCurrentState()) {
6937 mScheduler->registerLayer(layer);
6938 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006939}
6940
6941void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6942 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006943 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006944 if (!layer->isRemovedFromCurrentState()) {
6945 mScheduler->deregisterLayer(layer);
6946 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08006947 if (mTransactionTracing) {
6948 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08006949 }
Valerie Hauc5686802019-11-22 14:18:09 -08006950}
6951
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006952void SurfaceFlinger::onLayerUpdate() {
6953 scheduleCommit(FrameHint::kActive);
6954}
6955
Valerie Hauc5686802019-11-22 14:18:09 -08006956// WARNING: ONLY CALL THIS FROM LAYER DTOR
6957// Here we add children in the current state to offscreen layers and remove the
6958// layer itself from the offscreen layer list. Since
6959// this is the dtor, it is safe to access the current state. This keeps us
6960// from dangling children layers such that they are not reachable from the
6961// Drawing state nor the offscreen layer list
6962// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07006963void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08006964 for (auto& child : layer->getCurrentChildren()) {
6965 mOffscreenLayers.emplace(child.get());
6966 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006967 mOffscreenLayers.erase(layer);
6968}
6969
Robert Carr867be372021-06-29 17:36:02 -07006970void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6971 mOffscreenLayers.erase(layer);
6972}
6973
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006974status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6975 float lightPosY, float lightPosZ,
6976 float lightRadius) {
6977 Mutex::Autolock _l(mStateLock);
6978 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6979 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6980 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6981 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6982 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6983
6984 // these values are overridden when calculating the shadow settings for a layer.
6985 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6986 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006987 return NO_ERROR;
6988}
6989
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006990const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6991 const {
6992 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6993 // on the work to remove the table in that bug rather than adding more to
6994 // it.
6995 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Huihong Luod3d8f8e2022-03-08 14:48:46 -08006996 {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
6997 {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006998 };
6999 return genericLayerMetadataKeyMap;
7000}
7001
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007002status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7003 PhysicalDisplayId displayId = [&]() {
7004 Mutex::Autolock lock(mStateLock);
7005 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7006 }();
7007
7008 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7009 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7010 return NO_ERROR;
7011}
7012
Dominik Laskowski20134642020-04-20 22:36:44 -07007013void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007014 for (const auto& [ignored, display] : mDisplays) {
7015 if (display->isInternal()) {
7016 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007017 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007018 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007019}
7020
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007021status_t SurfaceFlinger::addTransactionTraceListener(
7022 const sp<gui::ITransactionTraceListener>& listener) {
7023 if (!listener) {
7024 return BAD_VALUE;
7025 }
7026
7027 mInterceptor->addTransactionTraceListener(listener);
7028
7029 return NO_ERROR;
7030}
7031
Huihong Luo02186fb2022-02-23 14:21:54 -08007032int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007033 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007034}
7035
Ady Abraham899dcdb2021-06-15 16:56:21 -07007036int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7037 std::chrono::nanoseconds presentLatency) {
7038 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7039 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007040 pipelineDepth++;
7041 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007042 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007043}
7044
Ady Abraham899dcdb2021-06-15 16:56:21 -07007045status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007046 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007047
7048 if (!getHwComposer().isHeadless()) {
7049 if (const auto display = getDefaultDisplayDevice()) {
7050 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007051 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007052 }
7053
7054 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007055 return NO_ERROR;
7056}
7057
rnleeed20fa42021-08-10 18:00:03 -07007058uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007059 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007060
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007061 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7062 refreshRate = *frameRateOverride;
7063 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007064 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007065 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007066 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007067 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007068
Ady Abraham899dcdb2021-06-15 16:56:21 -07007069 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7070}
7071
7072int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7073 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7074 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7075 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7076}
7077
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007078void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state) {
7079 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007080 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007081 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7082 return;
arthurhungdba591c2021-02-08 17:28:49 +08007083 }
7084
7085 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007086 bool addToRoot = state.addToRoot;
7087 if (state.initialParent != nullptr) {
7088 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007089 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007090 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007091 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007092 }
arthurhungdba591c2021-02-08 17:28:49 +08007093 }
7094
Garfield Tand712ad32021-10-27 13:44:22 -07007095 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007096 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007097 mCurrentState.layersSortedByZ.add(layer);
7098 } else if (parent == nullptr) {
7099 layer->onRemovedFromCurrentState();
7100 } else if (parent->isRemovedFromCurrentState()) {
7101 parent->addChild(layer);
7102 layer->onRemovedFromCurrentState();
7103 } else {
7104 parent->addChild(layer);
7105 }
7106
Ady Abraham1273ac12021-08-26 17:31:53 -07007107 layer->updateTransformHint(mActiveDisplayTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +08007108
Arthur Hung23e07502021-10-15 11:58:19 +00007109 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007110}
Ady Abraham562c2712021-05-07 15:10:42 -07007111
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007112void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007113 if (!mLumaSampling || !mRegionSamplingThread) {
7114 return;
7115 }
7116
Dominik Laskowski756b7892021-08-04 12:53:59 -07007117 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007118}
7119
Ady Abrahamed3290f2021-05-17 15:12:14 -07007120void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7121 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7122 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7123}
7124
7125void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7126 ATRACE_CALL();
7127
Ady Abrahamdb036a82021-07-16 14:18:34 -07007128 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7129 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7130 }
7131
Ady Abrahamed3290f2021-05-17 15:12:14 -07007132 if (!activeDisplay) {
7133 ALOGE("%s: activeDisplay is null", __func__);
7134 return;
7135 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007136 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007137 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007138 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007139 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007140 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007141 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007142 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007143
7144 // Update the kernel timer for the current active display, since the policy
7145 // for this display might have changed when it was not the active display.
7146 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007147}
7148
chaviw60c9d3e2021-06-04 12:52:17 -05007149status_t SurfaceFlinger::addWindowInfosListener(
7150 const sp<IWindowInfosListener>& windowInfosListener) const {
7151 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7152 return NO_ERROR;
7153}
7154
7155status_t SurfaceFlinger::removeWindowInfosListener(
7156 const sp<IWindowInfosListener>& windowInfosListener) const {
7157 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7158 return NO_ERROR;
7159}
7160
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007161std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7162 const BufferData& bufferData, const char* layerName) const {
7163 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7164 bool bufferSizeExceedsLimit = false;
7165 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7166 if (cacheIdChanged && bufferData.buffer != nullptr) {
7167 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7168 bufferData.buffer->getHeight());
7169 if (!bufferSizeExceedsLimit) {
7170 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7171 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7172 }
7173 } else if (cacheIdChanged) {
7174 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7175 } else if (bufferData.buffer != nullptr) {
7176 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7177 bufferData.buffer->getHeight());
7178 if (!bufferSizeExceedsLimit) {
7179 buffer = std::make_shared<
7180 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7181 renderengine::impl::ExternalTexture::
7182 Usage::READABLE);
7183 }
7184 }
7185 ALOGE_IF(bufferSizeExceedsLimit,
7186 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7187 "limit.",
7188 layerName);
7189 return buffer;
7190}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007191
7192bool SurfaceFlinger::commitCreatedLayers() {
7193 std::vector<LayerCreatedState> createdLayers;
7194 {
7195 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7196 createdLayers = std::move(mCreatedLayers);
7197 mCreatedLayers.clear();
7198 if (createdLayers.size() == 0) {
7199 return false;
7200 }
7201 }
7202
7203 Mutex::Autolock _l(mStateLock);
7204 for (const auto& createdLayer : createdLayers) {
7205 handleLayerCreatedLocked(createdLayer);
7206 }
7207 createdLayers.clear();
7208 mLayersAdded = true;
7209 return true;
7210}
Huihong Luof5029222021-12-16 14:33:46 -08007211
7212// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007213
Huihong Luod3d8f8e2022-03-08 14:48:46 -08007214binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
7215 const sp<Client> client = new Client(mFlinger);
7216 if (client->initCheck() == NO_ERROR) {
7217 *outClient = client;
7218 return binder::Status::ok();
7219 } else {
7220 *outClient = nullptr;
7221 return binderStatusFromStatusT(BAD_VALUE);
7222 }
7223}
7224
Huihong Luo07e72362022-02-14 14:26:04 -08007225binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7226 sp<IBinder>* outDisplay) {
7227 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007228 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007229 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007230 }
Huihong Luo37396db2022-02-15 10:43:00 -08007231 String8 displayName8 = String8::format("%s", displayName.c_str());
7232 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7233 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007234}
7235
7236binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7237 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007238 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007239 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007240 }
Huihong Luo37396db2022-02-15 10:43:00 -08007241 mFlinger->destroyDisplay(display);
7242 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007243}
7244
7245binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7246 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7247 std::vector<int64_t> displayIds;
7248 displayIds.reserve(physicalDisplayIds.size());
7249 for (auto item : physicalDisplayIds) {
7250 displayIds.push_back(static_cast<int64_t>(item.value));
7251 }
7252 *outDisplayIds = displayIds;
7253 return binder::Status::ok();
7254}
7255
7256binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7257 status_t status = checkAccessPermission();
7258 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007259 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007260 }
7261
7262 PhysicalDisplayId id;
7263 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7264 if (status == NO_ERROR) {
7265 *outDisplayId = id.value;
7266 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007267 return binderStatusFromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007268}
7269
7270binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7271 sp<IBinder>* outDisplay) {
7272 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7273 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7274 return binder::Status::ok();
7275}
7276
Huihong Luo37396db2022-02-15 10:43:00 -08007277binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7278 status_t status = checkAccessPermission();
7279 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007280 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007281 }
7282 mFlinger->setPowerMode(display, mode);
7283 return binder::Status::ok();
7284}
7285
Huihong Luo0a81aa32022-02-22 16:02:36 -08007286binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7287 std::vector<FrameEvent>* outSupported) {
7288 status_t status;
7289 if (!outSupported) {
7290 status = UNEXPECTED_NULL;
7291 } else {
7292 outSupported->clear();
7293 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7294 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007295 return binderStatusFromStatusT(status);
Huihong Luo0a81aa32022-02-22 16:02:36 -08007296}
7297
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007298binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7299 gui::DisplayStatInfo* outStatInfo) {
7300 DisplayStatInfo statInfo;
7301 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7302 if (status == NO_ERROR) {
7303 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7304 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7305 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007306 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007307}
7308
7309binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7310 gui::DisplayState* outState) {
7311 ui::DisplayState state;
7312 status_t status = mFlinger->getDisplayState(display, &state);
7313 if (status == NO_ERROR) {
7314 outState->layerStack = state.layerStack.id;
7315 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7316 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7317 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7318 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007319 return binderStatusFromStatusT(status);
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007320}
7321
Huihong Luoa79ddf42022-02-17 00:01:38 -08007322binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7323 gui::StaticDisplayInfo* outInfo) {
7324 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7325 ui::StaticDisplayInfo info;
7326 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7327 if (status == NO_ERROR) {
7328 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7329 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7330 outInfo->density = info.density;
7331 outInfo->secure = info.secure;
7332 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7333
7334 gui::DeviceProductInfo dinfo;
7335 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7336 dinfo.name = std::move(dpi->name);
7337 dinfo.manufacturerPnpId =
7338 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7339 dinfo.productId = dpi->productId;
7340 if (const auto* model =
7341 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7342 gui::DeviceProductInfo::ModelYear modelYear;
7343 modelYear.year = model->year;
7344 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7345 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7346 &dpi->manufactureOrModelDate)) {
7347 gui::DeviceProductInfo::ManufactureYear date;
7348 date.modelYear.year = manufacture->year;
7349 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7350 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7351 &dpi->manufactureOrModelDate)) {
7352 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7353 date.manufactureYear.modelYear.year = manufacture->year;
7354 date.week = manufacture->week;
7355 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7356 }
7357
7358 outInfo->deviceProductInfo = dinfo;
7359 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007360 return binderStatusFromStatusT(status);
Huihong Luoa79ddf42022-02-17 00:01:38 -08007361}
7362
Huihong Luo38603fd2022-02-21 14:32:54 -08007363binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7364 gui::DynamicDisplayInfo* outInfo) {
7365 ui::DynamicDisplayInfo info;
7366 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7367 if (status == NO_ERROR) {
7368 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7369 outInfo->supportedDisplayModes.clear();
7370 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7371 for (const auto& mode : info.supportedDisplayModes) {
7372 gui::DisplayMode outMode;
7373 outMode.id = mode.id;
7374 outMode.resolution.width = mode.resolution.width;
7375 outMode.resolution.height = mode.resolution.height;
7376 outMode.xDpi = mode.xDpi;
7377 outMode.yDpi = mode.yDpi;
7378 outMode.refreshRate = mode.refreshRate;
7379 outMode.appVsyncOffset = mode.appVsyncOffset;
7380 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7381 outMode.presentationDeadline = mode.presentationDeadline;
7382 outMode.group = mode.group;
7383 outInfo->supportedDisplayModes.push_back(outMode);
7384 }
7385
7386 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7387
7388 outInfo->supportedColorModes.clear();
7389 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7390 for (const auto& cmode : info.supportedColorModes) {
7391 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7392 }
7393
7394 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7395
7396 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7397 hdrCapabilities.supportedHdrTypes.clear();
7398 hdrCapabilities.supportedHdrTypes.reserve(
7399 info.hdrCapabilities.getSupportedHdrTypes().size());
7400 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7401 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7402 }
7403 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7404 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7405 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7406
7407 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7408 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7409 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7410 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007411 return binderStatusFromStatusT(status);
Huihong Luo38603fd2022-02-21 14:32:54 -08007412}
7413
Huihong Luoca3d9a42022-02-22 11:07:34 -08007414binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7415 gui::DisplayPrimaries* outPrimaries) {
7416 ui::DisplayPrimaries primaries;
7417 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7418 if (status == NO_ERROR) {
7419 outPrimaries->red.X = primaries.red.X;
7420 outPrimaries->red.Y = primaries.red.Y;
7421 outPrimaries->red.Z = primaries.red.Z;
7422
7423 outPrimaries->green.X = primaries.green.X;
7424 outPrimaries->green.Y = primaries.green.Y;
7425 outPrimaries->green.Z = primaries.green.Z;
7426
7427 outPrimaries->blue.X = primaries.blue.X;
7428 outPrimaries->blue.Y = primaries.blue.Y;
7429 outPrimaries->blue.Z = primaries.blue.Z;
7430
7431 outPrimaries->white.X = primaries.white.X;
7432 outPrimaries->white.Y = primaries.white.Y;
7433 outPrimaries->white.Z = primaries.white.Z;
7434 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007435 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007436}
7437
7438binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7439 status_t status = checkAccessPermission();
7440 if (status == OK) {
7441 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7442 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007443 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007444}
7445
7446binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7447 int displayModeId) {
7448 status_t status = checkAccessPermission();
7449 if (status == OK) {
7450 status = mFlinger->setBootDisplayMode(display,
7451 static_cast<ui::DisplayModeId>(displayModeId));
7452 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007453 return binderStatusFromStatusT(status);
Huihong Luoca3d9a42022-02-22 11:07:34 -08007454}
7455
Huihong Luo37396db2022-02-15 10:43:00 -08007456binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7457 status_t status = checkAccessPermission();
7458 if (status == OK) {
7459 status = mFlinger->clearBootDisplayMode(display);
7460 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007461 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007462}
7463
7464binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7465 status_t status = checkAccessPermission();
7466 if (status == OK) {
7467 status = mFlinger->getBootDisplayModeSupport(outMode);
7468 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007469 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007470}
7471
7472binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7473 status_t status = checkAccessPermission();
7474 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007475 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007476 }
7477 mFlinger->setAutoLowLatencyMode(display, on);
7478 return binder::Status::ok();
7479}
7480
7481binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7482 status_t status = checkAccessPermission();
7483 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007484 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007485 }
7486 mFlinger->setGameContentType(display, on);
7487 return binder::Status::ok();
7488}
7489
Huihong Luof5029222021-12-16 14:33:46 -08007490binder::Status SurfaceComposerAIDL::captureDisplay(
7491 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7492 status_t status = mFlinger->captureDisplay(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007493 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007494}
7495
7496binder::Status SurfaceComposerAIDL::captureDisplayById(
7497 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7498 status_t status;
7499 IPCThreadState* ipc = IPCThreadState::self();
7500 const int uid = ipc->getCallingUid();
7501 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7502 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7503 status = mFlinger->captureDisplay(*id, captureListener);
7504 } else {
7505 status = PERMISSION_DENIED;
7506 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007507 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007508}
7509
7510binder::Status SurfaceComposerAIDL::captureLayers(
7511 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7512 status_t status = mFlinger->captureLayers(args, captureListener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007513 return binderStatusFromStatusT(status);
Huihong Luof5029222021-12-16 14:33:46 -08007514}
7515
Huihong Luo4ed1c912022-02-22 14:30:01 -08007516binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7517 status_t status = checkAccessPermission();
7518 if (status == OK) {
7519 status = mFlinger->clearAnimationFrameStats();
7520 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007521 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007522}
7523
7524binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7525 status_t status = checkAccessPermission();
7526 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007527 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007528 }
7529
7530 FrameStats stats;
7531 status = mFlinger->getAnimationFrameStats(&stats);
7532 if (status == NO_ERROR) {
7533 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7534 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7535 for (const auto& t : stats.desiredPresentTimesNano) {
7536 outStats->desiredPresentTimesNano.push_back(t);
7537 }
7538 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7539 for (const auto& t : stats.actualPresentTimesNano) {
7540 outStats->actualPresentTimesNano.push_back(t);
7541 }
7542 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7543 for (const auto& t : stats.frameReadyTimesNano) {
7544 outStats->frameReadyTimesNano.push_back(t);
7545 }
7546 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007547 return binderStatusFromStatusT(status);
Huihong Luo4ed1c912022-02-22 14:30:01 -08007548}
7549
Huihong Luo05539a12022-02-23 10:29:40 -08007550binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7551 const std::vector<int32_t>& hdrTypes) {
7552 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7553 // permission dynamically. Don't use the permission cache for this check.
7554 status_t status = checkAccessPermission(false);
7555 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007556 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007557 }
7558
7559 std::vector<ui::Hdr> hdrTypesVector;
7560 for (int32_t i : hdrTypes) {
7561 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7562 }
7563 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
Huihong Luo3bdef862022-03-03 11:57:19 -08007564 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007565}
7566
7567binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7568 status_t status;
7569 const int uid = IPCThreadState::self()->getCallingUid();
7570 if (uid != AID_SYSTEM) {
7571 status = PERMISSION_DENIED;
7572 } else {
7573 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7574 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007575 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007576}
7577
7578binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7579 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007580 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007581 }
7582
7583 status_t status = checkAccessPermission();
7584 if (status == OK) {
7585 status = mFlinger->enableVSyncInjections(enable);
7586 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007587 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007588}
7589
7590binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7591 if (!mFlinger->hasMockHwc()) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007592 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007593 }
7594
7595 status_t status = checkAccessPermission();
7596 if (status == OK) {
7597 status = mFlinger->injectVSync(when);
7598 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007599 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007600}
7601
7602binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7603 if (!outLayers) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007604 return binderStatusFromStatusT(UNEXPECTED_NULL);
Huihong Luo05539a12022-02-23 10:29:40 -08007605 }
7606
7607 IPCThreadState* ipc = IPCThreadState::self();
7608 const int pid = ipc->getCallingPid();
7609 const int uid = ipc->getCallingUid();
7610 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7611 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Huihong Luo3bdef862022-03-03 11:57:19 -08007612 return binderStatusFromStatusT(PERMISSION_DENIED);
Huihong Luo05539a12022-02-23 10:29:40 -08007613 }
7614 status_t status = mFlinger->getLayerDebugInfo(outLayers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007615 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007616}
7617
7618binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7619 status_t status = mFlinger->getColorManagement(outGetColorManagement);
Huihong Luo3bdef862022-03-03 11:57:19 -08007620 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007621}
7622
7623binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7624 ui::Dataspace dataspace;
7625 ui::PixelFormat pixelFormat;
7626 ui::Dataspace wideColorGamutDataspace;
7627 ui::PixelFormat wideColorGamutPixelFormat;
7628 status_t status =
7629 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7630 &wideColorGamutPixelFormat);
7631 if (status == NO_ERROR) {
7632 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7633 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7634 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7635 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7636 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007637 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007638}
7639
7640binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7641 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7642 status_t status = checkAccessPermission();
7643 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007644 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007645 }
7646
7647 ui::PixelFormat format;
7648 ui::Dataspace dataspace;
7649 uint8_t componentMask;
7650 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7651 &componentMask);
7652 if (status == NO_ERROR) {
7653 outAttrs->format = static_cast<int32_t>(format);
7654 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7655 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7656 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007657 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007658}
7659
7660binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7661 bool enable,
7662 int8_t componentMask,
7663 int64_t maxFrames) {
7664 status_t status = checkAccessPermission();
7665 if (status == OK) {
7666 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7667 static_cast<uint8_t>(componentMask),
7668 static_cast<uint64_t>(maxFrames));
7669 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007670 return binderStatusFromStatusT(status);
7671}
7672
7673binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
7674 int64_t maxFrames, int64_t timestamp,
7675 gui::DisplayedFrameStats* outStats) {
7676 if (!outStats) {
7677 return binderStatusFromStatusT(BAD_VALUE);
7678 }
7679
7680 status_t status = checkAccessPermission();
7681 if (status != OK) {
7682 return binderStatusFromStatusT(status);
7683 }
7684
7685 DisplayedFrameStats stats;
7686 status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
7687 static_cast<uint64_t>(timestamp), &stats);
7688 if (status == NO_ERROR) {
7689 // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
7690 outStats->numFrames = static_cast<int64_t>(stats.numFrames);
7691 outStats->component_0_sample.reserve(stats.component_0_sample.size());
7692 for (const auto& s : stats.component_0_sample) {
7693 outStats->component_0_sample.push_back(static_cast<int64_t>(s));
7694 }
7695 outStats->component_1_sample.reserve(stats.component_1_sample.size());
7696 for (const auto& s : stats.component_1_sample) {
7697 outStats->component_1_sample.push_back(static_cast<int64_t>(s));
7698 }
7699 outStats->component_2_sample.reserve(stats.component_2_sample.size());
7700 for (const auto& s : stats.component_2_sample) {
7701 outStats->component_2_sample.push_back(static_cast<int64_t>(s));
7702 }
7703 outStats->component_3_sample.reserve(stats.component_3_sample.size());
7704 for (const auto& s : stats.component_3_sample) {
7705 outStats->component_3_sample.push_back(static_cast<int64_t>(s));
7706 }
7707 }
7708 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007709}
7710
7711binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7712 status_t status = mFlinger->getProtectedContentSupport(outSupported);
Huihong Luo3bdef862022-03-03 11:57:19 -08007713 return binderStatusFromStatusT(status);
Huihong Luo05539a12022-02-23 10:29:40 -08007714}
7715
Huihong Luo37396db2022-02-15 10:43:00 -08007716binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7717 bool* outIsWideColorDisplay) {
7718 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
Huihong Luo3bdef862022-03-03 11:57:19 -08007719 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007720}
7721
Huihong Luo02186fb2022-02-23 14:21:54 -08007722binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7723 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7724 const sp<gui::IRegionSamplingListener>& listener) {
7725 status_t status = checkReadFrameBufferPermission();
7726 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007727 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007728 }
7729 android::Rect rect;
7730 rect.left = samplingArea.left;
7731 rect.top = samplingArea.top;
7732 rect.right = samplingArea.right;
7733 rect.bottom = samplingArea.bottom;
7734 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
Huihong Luo3bdef862022-03-03 11:57:19 -08007735 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007736}
7737
7738binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7739 const sp<gui::IRegionSamplingListener>& listener) {
7740 status_t status = checkReadFrameBufferPermission();
7741 if (status == OK) {
7742 status = mFlinger->removeRegionSamplingListener(listener);
7743 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007744 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007745}
7746
7747binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7748 const sp<gui::IFpsListener>& listener) {
7749 status_t status = checkReadFrameBufferPermission();
7750 if (status == OK) {
7751 status = mFlinger->addFpsListener(taskId, listener);
7752 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007753 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007754}
7755
7756binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7757 status_t status = checkReadFrameBufferPermission();
7758 if (status == OK) {
7759 status = mFlinger->removeFpsListener(listener);
7760 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007761 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007762}
7763
7764binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7765 const sp<gui::ITunnelModeEnabledListener>& listener) {
7766 status_t status = checkAccessPermission();
7767 if (status == OK) {
7768 status = mFlinger->addTunnelModeEnabledListener(listener);
7769 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007770 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007771}
7772
7773binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7774 const sp<gui::ITunnelModeEnabledListener>& listener) {
7775 status_t status = checkAccessPermission();
7776 if (status == OK) {
7777 status = mFlinger->removeTunnelModeEnabledListener(listener);
7778 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007779 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007780}
7781
7782binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7783 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7784 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7785 float appRequestRefreshRateMax) {
7786 status_t status = checkAccessPermission();
7787 if (status == OK) {
7788 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7789 static_cast<ui::DisplayModeId>(defaultMode),
7790 allowGroupSwitching, primaryRefreshRateMin,
7791 primaryRefreshRateMax,
7792 appRequestRefreshRateMin,
7793 appRequestRefreshRateMax);
7794 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007795 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007796}
7797
7798binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7799 gui::DisplayModeSpecs* outSpecs) {
7800 if (!outSpecs) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007801 return binderStatusFromStatusT(BAD_VALUE);
Huihong Luo02186fb2022-02-23 14:21:54 -08007802 }
7803
7804 status_t status = checkAccessPermission();
7805 if (status != OK) {
Huihong Luo3bdef862022-03-03 11:57:19 -08007806 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007807 }
7808
7809 ui::DisplayModeId displayModeId;
7810 bool allowGroupSwitching;
7811 float primaryRefreshRateMin;
7812 float primaryRefreshRateMax;
7813 float appRequestRefreshRateMin;
7814 float appRequestRefreshRateMax;
7815 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7816 &allowGroupSwitching, &primaryRefreshRateMin,
7817 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7818 &appRequestRefreshRateMax);
7819 if (status == NO_ERROR) {
7820 outSpecs->defaultMode = displayModeId;
7821 outSpecs->allowGroupSwitching = allowGroupSwitching;
7822 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7823 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7824 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7825 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7826 }
7827
Huihong Luo3bdef862022-03-03 11:57:19 -08007828 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007829}
7830
Huihong Luo37396db2022-02-15 10:43:00 -08007831binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7832 bool* outSupport) {
7833 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
Huihong Luo3bdef862022-03-03 11:57:19 -08007834 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007835}
7836
7837binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7838 const gui::DisplayBrightness& brightness) {
7839 status_t status = checkControlDisplayBrightnessPermission();
7840 if (status == OK) {
7841 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7842 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007843 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007844}
7845
7846binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7847 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7848 status_t status = checkControlDisplayBrightnessPermission();
7849 if (status == OK) {
7850 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7851 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007852 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007853}
7854
7855binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7856 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7857 status_t status = checkControlDisplayBrightnessPermission();
7858 if (status == OK) {
7859 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7860 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007861 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007862}
7863
7864binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7865 status_t status = checkAccessPermission();
7866 if (status == OK) {
7867 status = mFlinger->notifyPowerBoost(boostId);
7868 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007869 return binderStatusFromStatusT(status);
7870}
7871
7872binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
7873 const gui::Color& spotColor,
7874 float lightPosY, float lightPosZ,
7875 float lightRadius) {
7876 status_t status = checkAccessPermission();
7877 if (status != OK) {
7878 return binderStatusFromStatusT(status);
7879 }
7880
7881 half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
7882 half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
7883 status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
7884 lightPosZ, lightRadius);
7885 return binderStatusFromStatusT(status);
7886}
7887
7888binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
7889 const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
7890 std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
7891 status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
7892 if (status != NO_ERROR) {
7893 ALOGE("getDisplayDecorationSupport failed with error %d", status);
7894 return binderStatusFromStatusT(status);
7895 }
7896
7897 if (!support || !support.has_value()) {
7898 outSupport->reset();
7899 } else {
7900 outSupport->emplace();
7901 outSupport->value().format = static_cast<int32_t>(support->format);
7902 outSupport->value().alphaInterpretation =
7903 static_cast<int32_t>(support->alphaInterpretation);
7904 }
7905
7906 return binder::Status::ok();
7907}
7908
7909binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
7910 status_t status;
7911 const int c_uid = IPCThreadState::self()->getCallingUid();
7912 if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
7913 status = mFlinger->setOverrideFrameRate(uid, frameRate);
7914 } else {
7915 ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
7916 status = PERMISSION_DENIED;
7917 }
7918 return binderStatusFromStatusT(status);
Huihong Luo37396db2022-02-15 10:43:00 -08007919}
7920
Huihong Luo02186fb2022-02-23 14:21:54 -08007921binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
7922 const sp<gui::ITransactionTraceListener>& listener) {
7923 status_t status;
7924 IPCThreadState* ipc = IPCThreadState::self();
7925 const int uid = ipc->getCallingUid();
7926 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7927 status = mFlinger->addTransactionTraceListener(listener);
7928 } else {
7929 status = PERMISSION_DENIED;
7930 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007931 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007932}
7933
7934binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
7935 *outPriority = mFlinger->getGpuContextPriority();
7936 return binder::Status::ok();
7937}
7938
7939binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
7940 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
Huihong Luo3bdef862022-03-03 11:57:19 -08007941 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007942}
7943
7944binder::Status SurfaceComposerAIDL::addWindowInfosListener(
7945 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7946 status_t status;
7947 const int uid = IPCThreadState::self()->getCallingUid();
7948 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7949 status = mFlinger->addWindowInfosListener(windowInfosListener);
7950 } else {
7951 status = PERMISSION_DENIED;
7952 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007953 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007954}
7955
7956binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
7957 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7958 status_t status;
7959 const int uid = IPCThreadState::self()->getCallingUid();
7960 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7961 status = mFlinger->removeWindowInfosListener(windowInfosListener);
7962 } else {
7963 status = PERMISSION_DENIED;
7964 }
Huihong Luo3bdef862022-03-03 11:57:19 -08007965 return binderStatusFromStatusT(status);
Huihong Luo02186fb2022-02-23 14:21:54 -08007966}
7967
Huihong Luo07e72362022-02-14 14:26:04 -08007968status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
7969 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
7970 IPCThreadState* ipc = IPCThreadState::self();
7971 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
7972 ipc->getCallingUid());
7973 return PERMISSION_DENIED;
7974 }
7975 return OK;
7976}
7977
Huihong Luo37396db2022-02-15 10:43:00 -08007978status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
7979 IPCThreadState* ipc = IPCThreadState::self();
7980 const int pid = ipc->getCallingPid();
7981 const int uid = ipc->getCallingUid();
7982 if ((uid != AID_GRAPHICS) &&
7983 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
7984 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
7985 return PERMISSION_DENIED;
7986 }
7987 return OK;
7988}
7989
Huihong Luo02186fb2022-02-23 14:21:54 -08007990status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
7991 IPCThreadState* ipc = IPCThreadState::self();
7992 const int pid = ipc->getCallingPid();
7993 const int uid = ipc->getCallingUid();
7994 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
7995 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
7996 return PERMISSION_DENIED;
7997 }
7998 return OK;
7999}
8000
Dominik Laskowski9dab3432019-03-27 13:21:10 -07008001} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07008002
Mathias Agopian3f844832013-08-07 21:24:32 -07008003#if defined(__gl_h_)
8004#error "don't include gl/gl.h in this file"
8005#endif
8006
8007#if defined(__gl2_h_)
8008#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08008009#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08008010
8011// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01008012#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"