blob: 2cd1393085759ccd654e4f84ae580c00c9718b53 [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>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070059#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070060#include <gui/DebugEGLImageTracker.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080061#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080062#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080063#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080064#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080065#include <gui/Surface.h>
rnlee60f46b52021-05-21 15:14:07 -070066#include <gui/TraceUtils.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000067#include <hidl/ServiceManagement.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080068#include <layerproto/LayerProtoParser.h>
69#include <log/log.h>
70#include <private/android_filesystem_config.h>
71#include <private/gui/SyncFeatures.h>
Wei Wang976a6452021-06-11 15:26:00 -070072#include <processgroup/processgroup.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070073#include <renderengine/RenderEngine.h>
Vishnu Nairdbbe3852022-01-12 20:22:11 -080074#include <renderengine/impl/ExternalTexture.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080075#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070076#include <ui/ColorSpace.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070077#include <ui/DataspaceUtils.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070078#include <ui/DebugUtils.h>
Marin Shalamanov045b7002021-01-07 16:56:24 +010079#include <ui/DisplayId.h>
Marin Shalamanova7fe3042021-01-29 21:02:08 +010080#include <ui/DisplayMode.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080082#include <ui/DisplayState.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010083#include <ui/DynamicDisplayInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070084#include <ui/GraphicBufferAllocator.h>
85#include <ui/PixelFormat.h>
Marin Shalamanov228f46b2021-01-28 21:11:45 +010086#include <ui/StaticDisplayInfo.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070088#include <utils/String16.h>
89#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070090#include <utils/Timers.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070091#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092
Alec Mouri5f487d42020-02-06 09:26:19 -080093#include <algorithm>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080094#include <cerrno>
Alec Mouri5f487d42020-02-06 09:26:19 -080095#include <cinttypes>
96#include <cmath>
97#include <cstdint>
98#include <functional>
99#include <mutex>
100#include <optional>
Michael Wright44753b12020-07-08 13:48:11 +0100101#include <type_traits>
Alec Mouri5f487d42020-02-06 09:26:19 -0800102#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103
Alec Mouriff793872022-01-13 17:45:06 -0800104#include <ui/DisplayIdentification.h>
Vishnu Nair03ccbd62021-12-01 17:21:16 -0800105#include "BackgroundExecutor.h"
Robert Carr578038f2018-03-09 12:25:24 -0800106#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -0700107#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -0700108#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200109#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +0200110#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800111#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800112#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700113#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700114#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700115#include "DisplayHardware/HWComposer.h"
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +0100116#include "DisplayHardware/Hal.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700117#include "DisplayHardware/VirtualDisplaySurface.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200118#include "DisplayRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800119#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700120#include "Effects/Daltonizer.h"
rnleea2ecd832021-07-29 13:58:30 -0700121#include "FlagManager.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -0800122#include "FpsReporter.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700123#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700124#include "FrameTracer/FrameTracer.h"
John Reck88270902021-03-18 11:27:35 -0400125#include "HdrLayerInfoReporter.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800126#include "Layer.h"
chaviw0a398992021-08-13 10:13:01 -0500127#include "LayerProtoHelper.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200128#include "LayerRenderArea.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800129#include "LayerVector.h"
130#include "MonitoredProducer.h"
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800131#include "MutexUtils.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800132#include "NativeWindowSurface.h"
133#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700134#include "RegionSamplingThread.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700135#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700136#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700137#include "Scheduler/LayerHistory.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700138#include "Scheduler/Scheduler.h"
Ady Abrahamc581d3c2020-08-06 17:34:27 -0700139#include "Scheduler/VsyncConfiguration.h"
Ady Abraham8cb21882020-08-26 18:22:05 -0700140#include "Scheduler/VsyncController.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800141#include "StartPropertySetThread.h"
142#include "SurfaceFlingerProperties.h"
143#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800144#include "TimeStats/TimeStats.h"
Galia Peycheva8f04b302021-04-27 13:25:38 +0200145#include "TunnelModeEnabledReporter.h"
chaviw60c9d3e2021-06-04 12:52:17 -0500146#include "WindowInfosListenerInvoker.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800147
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -0500148#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500149#include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
150
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700151#undef NO_THREAD_SAFETY_ANALYSIS
152#define NO_THREAD_SAFETY_ANALYSIS \
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800153 _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
Leon Scroggins III5967aec2021-12-29 11:14:22 -0500154
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700156
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700157using namespace std::string_literals;
158
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800159using namespace hardware::configstore;
160using namespace hardware::configstore::V1_0;
161using namespace sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800162
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800163using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
164using aidl::android::hardware::graphics::composer3::Capability;
165using aidl::android::hardware::graphics::composer3::DisplayCapability;
166
Yiwei Zhang5434a782018-12-05 18:06:32 -0800167using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700168using gui::DisplayInfo;
Huihong Luo6fac5232021-11-22 16:05:23 -0800169using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500170using gui::IWindowInfosListener;
chaviw98318de2021-05-19 16:45:23 -0500171using gui::WindowInfo;
Peiyong Lin9f034472018-03-28 15:29:00 -0700172using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700173using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800174using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700175using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900176
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800177using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
178
Peiyong Line9d809e2020-04-14 13:10:48 -0700179namespace hal = android::hardware::graphics::composer::hal;
180
Steven Thomasb02664d2017-07-26 18:48:28 -0700181namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700182
183#pragma clang diagnostic push
184#pragma clang diagnostic error "-Wswitch-enum"
185
186bool isWideColorMode(const ColorMode colorMode) {
187 switch (colorMode) {
188 case ColorMode::DISPLAY_P3:
189 case ColorMode::ADOBE_RGB:
190 case ColorMode::DCI_P3:
191 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700192 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700193 case ColorMode::BT2100_PQ:
194 case ColorMode::BT2100_HLG:
195 return true;
196 case ColorMode::NATIVE:
197 case ColorMode::STANDARD_BT601_625:
198 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
199 case ColorMode::STANDARD_BT601_525:
200 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
201 case ColorMode::STANDARD_BT709:
202 case ColorMode::SRGB:
203 return false;
204 }
205 return false;
206}
207
208#pragma clang diagnostic pop
209
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100210// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700211constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800212
213float getDensityFromProperty(const char* property, bool required) {
214 char value[PROPERTY_VALUE_MAX];
215 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
216 if (!density && required) {
217 ALOGE("%s must be defined as a build property", property);
218 return FALLBACK_DENSITY;
219 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700220 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800221}
222
Peiyong Lin9d846a52018-11-05 13:18:20 -0800223// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
224bool validateCompositionDataspace(Dataspace dataspace) {
225 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
226}
227
ramindani32cf0602022-03-02 02:30:29 +0000228std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700229 const auto displayIdleTimerMsKey = [displayId] {
230 std::stringstream ss;
231 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
232 return ss.str();
233 }();
234
ramindani32cf0602022-03-02 02:30:29 +0000235 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
236 if (displayIdleTimerMs > 0) {
237 return std::chrono::milliseconds(displayIdleTimerMs);
238 }
239
240 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
241 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
242 return std::chrono::milliseconds(millis);
243}
244
245bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700246 const auto displaySupportKernelIdleTimerKey = [displayId] {
247 std::stringstream ss;
248 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
249 return ss.str();
250 }();
251
Ady Abraham6d885932021-09-03 18:05:48 -0700252 const auto displaySupportKernelIdleTimer =
253 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000254 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700255}
256
Steven Thomasb02664d2017-07-26 18:48:28 -0700257} // namespace anonymous
258
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259// ---------------------------------------------------------------------------
260
Mathias Agopian99b49842011-06-27 16:05:52 -0700261const String16 sHardwareTest("android.permission.HARDWARE_TEST");
262const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800263const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700264const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400265const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700266const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500267const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000268const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500269
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800270const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700271
272// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700273int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700274bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800275bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800276int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100277uint32_t SurfaceFlinger::maxGraphicsWidth;
278uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600279bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700280bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700281Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
282ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
283Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
284ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000285LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700286
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800287std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
288 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800289 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700290 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800291 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700292 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800293 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700294 return std::string("Enhanced");
295 default:
296 return std::string("Unknown ") +
297 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800298 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800299}
300
Hongwei Wang46213ea2020-12-04 17:17:31 -0800301bool callingThreadHasRotateSurfaceFlingerAccess() {
302 IPCThreadState* ipc = IPCThreadState::self();
303 const int pid = ipc->getCallingPid();
304 const int uid = ipc->getCallingUid();
305 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
306 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
307}
308
Leon Scroggins9a20f722021-12-28 14:43:12 +0000309bool callingThreadHasInternalSystemWindowAccess() {
310 IPCThreadState* ipc = IPCThreadState::self();
311 const int pid = ipc->getCallingPid();
312 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500313 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
314 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000315}
316
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700317SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
318 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800319 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000320 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700321 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800322 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800323 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700324 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700325 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700326 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800327 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700328 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
chaviw60c9d3e2021-06-04 12:52:17 -0500329 mPowerAdvisor(*this),
Dominik Laskowski91f635e2022-01-08 05:46:09 -0800330 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make(*this)) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700331 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700332}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800333
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700334SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800335 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800336
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900337 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900339 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700340
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900341 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700342
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900343 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800344
Brian Lindahla13f2d52020-03-05 11:54:17 +0100345 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
346 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
347
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900348 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900349 mDefaultCompositionDataspace =
350 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700351 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
352 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900353 defaultCompositionDataspace = mDefaultCompositionDataspace;
354 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
355 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
356 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
357 wideColorGamutCompositionPixelFormat =
358 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700359
Yichi Chenda901bf2019-06-28 14:58:27 +0800360 mColorSpaceAgnosticDataspace =
361 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
362
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700363 mLayerCachingEnabled = [] {
364 const bool enable =
365 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
366 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
367 }();
368
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900369 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800370
Sundong Ahn85131bd2019-02-18 15:51:53 +0900371 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800372
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800373 // debugging stuff...
374 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700375
Mathias Agopianb4b17302013-03-20 18:36:41 -0700376 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700377 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700378
Alec Mouri5f487d42020-02-06 09:26:19 -0800379 property_get("ro.build.type", value, "user");
380 mIsUserBuild = strcmp(value, "user") == 0;
381
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700382 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000383
384 // DDMS debugging deprecated (b/120782499)
385 property_get("debug.sf.ddms", value, "0");
386 int debugDdms = atoi(value);
387 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700388
Ady Abrahamadb9a992019-09-19 21:21:55 +0000389 property_get("debug.sf.enable_gl_backpressure", value, "0");
390 mPropagateBackpressureClientComposition = atoi(value);
391 ALOGI_IF(mPropagateBackpressureClientComposition,
392 "Enabling backpressure propagation for Client Composition");
393
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800394 property_get("ro.surface_flinger.supports_background_blur", value, "0");
395 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700396 mSupportsBlur = supportsBlurs;
397 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800398 property_get("ro.sf.blurs_are_expensive", value, "0");
399 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800400
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800401 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700402 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
403 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800404 mGraphicBufferProducerListSizeLogThreshold =
405 std::max(static_cast<int>(0.95 *
406 static_cast<double>(mMaxGraphicBufferProducerListSize)),
407 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700408
Dan Stozaec460082018-12-17 15:35:09 -0800409 property_get("debug.sf.luma_sampling", value, "1");
410 mLumaSampling = atoi(value);
411
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800412 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800413 mDisableClientCompositionCache = atoi(value);
414
Vishnu Naira3140382022-02-24 14:07:11 -0800415 property_get("debug.sf.predict_hwc_composition_strategy", value, "0");
416 mPredictCompositionStrategy = atoi(value);
417
Romain Guy11d63f42017-07-20 12:47:14 -0700418 // We should be reading 'persist.sys.sf.color_saturation' here
419 // but since /data may be encrypted, we need to wait until after vold
420 // comes online to attempt to read the property. The property is
421 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800422
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700423 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800424 // Without the override SurfaceFlinger cannot connect to HIDL
425 // services that are not listed in the manifests. Considered
426 // deriving the setting from the set service name, but it
427 // would be brittle if the name that's not 'default' is used
428 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700429 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000430 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800431 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800432
Ady Abraham29d0da32020-07-16 18:39:33 -0700433 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400434
Dominik Laskowski46471e62022-01-14 15:34:03 -0800435 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
436 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800437 }
John Reck49d9ad32022-02-23 19:03:31 -0500438
439 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
ramindani4d48f902021-09-20 21:07:45 +0000440}
441
442LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
443 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
444 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000445 }
Ady Abraham9dada822022-02-03 10:26:59 -0800446
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000447 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800448 return LatchUnsignaledConfig::AutoSingleLayer;
449 }
450
451 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452}
453
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700454SurfaceFlinger::~SurfaceFlinger() = default;
455
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700456void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800457 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700458 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800459
Dominik Laskowski756b7892021-08-04 12:53:59 -0700460 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000461 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800462
Andy McFadden13a082e2012-08-24 10:16:42 -0700463 // restore initial conditions (default device unblank, etc)
464 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800465
466 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700467 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800468}
469
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700470void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700471 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800472}
473
474sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700475 const sp<Client> client = new Client(this);
476 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800477}
478
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700479sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700480 // onTransact already checks for some permissions, but adding an additional check here.
481 // This is to ensure that only system and graphics can request to create a secure
482 // display. Secure displays can show secure content so we add an additional restriction on it.
483 const int uid = IPCThreadState::self()->getCallingUid();
484 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
485 ALOGE("Only privileged processes can create a secure display");
486 return nullptr;
487 }
488
Mathias Agopiane57f2922012-08-09 16:29:12 -0700489 class DisplayToken : public BBinder {
490 sp<SurfaceFlinger> flinger;
491 virtual ~DisplayToken() {
492 // no more references, this display must be terminated
493 Mutex::Autolock _l(flinger->mStateLock);
494 flinger->mCurrentState.displays.removeItem(this);
495 flinger->setTransactionFlags(eDisplayTransactionNeeded);
496 }
497 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700498 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499 : flinger(flinger) {
500 }
501 };
502
503 sp<BBinder> token = new DisplayToken(this);
504
505 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506 // Display ID is assigned when virtual display is allocated by HWC.
507 DisplayDeviceState state;
508 state.isSecure = secure;
509 state.displayName = displayName;
510 mCurrentState.displays.add(token, state);
511 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700512 return token;
513}
514
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700515void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700516 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700517
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700518 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700519 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800520 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700521 return;
522 }
523
Dominik Laskowski075d3172018-05-24 15:50:06 -0700524 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700525 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800526 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700527 return;
528 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700529 mInterceptor->saveDisplayDeletion(state.sequenceId);
530 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700531 setTransactionFlags(eDisplayTransactionNeeded);
532}
533
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800534void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
535 auto& generator = mVirtualDisplayIdGenerators.hal;
536 if (!generator && enable) {
537 ALOGI("Enabling HAL virtual displays");
538 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
539 } else if (generator && !enable) {
540 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
541 generator.reset();
542 }
543}
544
Dominik Laskowski263eec42021-07-21 23:13:24 -0700545VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
546 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800547 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
548 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700549 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800550 return *id;
551 }
552
553 generator->releaseId(*id);
554 } else {
555 ALOGW("%s: Exhausted HAL virtual displays", __func__);
556 }
557
558 ALOGW("%s: Falling back to GPU virtual display", __func__);
559 }
560
561 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
562 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
563 return *id;
564}
565
566void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
567 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
568 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
569 generator->releaseId(*id);
570 }
571 return;
572 }
573
574 const auto id = GpuVirtualDisplayId::tryCast(displayId);
575 LOG_ALWAYS_FATAL_IF(!id);
576 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
577}
578
Ady Abrahamed3290f2021-05-17 15:12:14 -0700579std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800580 std::vector<PhysicalDisplayId> displayIds;
581 displayIds.reserve(mPhysicalDisplayTokens.size());
Ady Abraham2a0066d2021-07-15 20:16:58 -0700582 const auto defaultDisplayId = [this]() REQUIRES(mStateLock) {
583 if (const auto display = getDefaultDisplayDeviceLocked()) {
584 return display->getPhysicalId();
585 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700586
Ady Abraham2a0066d2021-07-15 20:16:58 -0700587 // fallback to the internal display id if the active display is unknown
588 return getInternalDisplayIdLocked();
589 }();
590 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800591
592 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700593 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200594 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800595 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700596 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700597
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800598 return displayIds;
599}
600
Vishnu Nair8c8db542021-09-17 19:51:45 -0700601status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
602 Mutex::Autolock lock(mStateLock);
603 *id = getInternalDisplayIdLocked();
604 return NO_ERROR;
605}
606
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800607sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
608 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200609 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700610}
611
Ady Abraham37965d42018-11-01 13:43:32 -0700612status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
613 if (!outGetColorManagement) {
614 return BAD_VALUE;
615 }
616 *outGetColorManagement = useColorManagement;
617 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700618}
619
Lloyd Pique441d5042018-10-18 16:49:51 -0700620HWComposer& SurfaceFlinger::getHwComposer() const {
621 return mCompositionEngine->getHwComposer();
622}
623
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700624renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
625 return mCompositionEngine->getRenderEngine();
626}
627
Lloyd Pique70d91362018-10-18 16:02:55 -0700628compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
629 return *mCompositionEngine.get();
630}
631
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100632void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700633 if (mBootFinished == true) {
634 ALOGE("Extra call to bootFinished");
635 return;
636 }
637 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700638 if (mStartPropertySetThread->join() != NO_ERROR) {
639 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800640 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700641
642 if (mRenderEnginePrimeCacheFuture.valid()) {
643 mRenderEnginePrimeCacheFuture.get();
644 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800645 const nsecs_t now = systemTime();
646 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000647 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700648
Mikael Pessa90092f42019-08-26 17:22:04 -0700649 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700650 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700651 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700652
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700653 // wait patiently for the window manager death
654 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700655 mWindowManager = defaultServiceManager()->getService(name);
656 if (mWindowManager != 0) {
657 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700658 }
659
660 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700661 // formerly we would just kill the process, but we now ask it to exit so it
662 // can choose where to stop the animation.
663 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700664
665 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
666 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
667 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700668
Denis Hsue70cc6c2020-06-17 10:17:30 +0800669 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
670
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000671 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800672 if (input == nullptr) {
673 ALOGE("Failed to link to input service");
674 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700675 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800676 }
677
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800678 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700679 mPowerAdvisor.onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700680 mPowerAdvisor.enablePowerHint(mFlagManager.use_adpf_cpu_hint());
Matt Buckleyef51fba2021-10-12 19:30:12 +0000681 if (mPowerAdvisor.usePowerHintSession()) {
Xiang Wang76236e12022-03-22 17:25:30 +0000682 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
683 std::vector<int32_t> tidList;
684 tidList.emplace_back(gettid());
685 if (renderEngineTid.has_value()) {
686 tidList.emplace_back(*renderEngineTid);
687 }
Xiang Wange12b4fa2022-03-25 23:48:40 +0000688 if (!mPowerAdvisor.startPowerHintSession(tidList)) {
689 ALOGW("Cannot start power hint session");
690 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000691 }
692
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800693 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800694
Ady Abraham8a82ba62020-01-17 12:43:17 -0800695 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800696 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800697 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800698 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800699}
700
Dan Stoza436ccf32018-06-21 12:10:12 -0700701uint32_t SurfaceFlinger::getNewTexture() {
702 {
703 std::lock_guard lock(mTexturePoolMutex);
704 if (!mTexturePool.empty()) {
705 uint32_t name = mTexturePool.back();
706 mTexturePool.pop_back();
707 ATRACE_INT("TexturePoolSize", mTexturePool.size());
708 return name;
709 }
710
711 // The pool was too small, so increase it for the future
712 ++mTexturePoolSize;
713 }
714
715 // The pool was empty, so we need to get a new texture name directly using a
716 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700717 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700718 uint32_t name = 0;
719 getRenderEngine().genTextures(1, &name);
720 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700721 };
722 if (std::this_thread::get_id() == mMainThreadId) {
723 return genTextures();
724 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700725 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700726 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700727}
728
Mathias Agopian3f844832013-08-07 21:24:32 -0700729void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700730 std::lock_guard lock(mTexturePoolMutex);
731 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
732 // to actually delete this or not based on mTexturePoolSize
733 mTexturePool.push_back(texture);
734 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700735}
736
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500737static std::optional<renderengine::RenderEngine::RenderEngineType>
738chooseRenderEngineTypeViaSysProp() {
739 char prop[PROPERTY_VALUE_MAX];
740 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
741
742 if (strcmp(prop, "gles") == 0) {
743 return renderengine::RenderEngine::RenderEngineType::GLES;
744 } else if (strcmp(prop, "threaded") == 0) {
745 return renderengine::RenderEngine::RenderEngineType::THREADED;
746 } else if (strcmp(prop, "skiagl") == 0) {
747 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
748 } else if (strcmp(prop, "skiaglthreaded") == 0) {
749 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
750 } else {
751 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
752 return {};
753 }
754}
755
Wei Wangf9b05ee2017-07-19 20:59:39 -0700756// Do not call property_set on main thread which will be blocked by init
757// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700758void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700759 ALOGI( "SurfaceFlinger's main thread ready to run. "
760 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700761 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800762
Steven Thomasb02664d2017-07-26 18:48:28 -0700763 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700764 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800765 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500766 auto builder = renderengine::RenderEngineCreationArgs::Builder()
767 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
768 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
769 .setUseColorManagerment(useColorManagement)
770 .setEnableProtectedContext(enable_protected_contents(false))
771 .setPrecacheToneMapperShaderOnly(false)
772 .setSupportsBackgroundBlur(mSupportsBlur)
773 .setContextPriority(
774 useContextPriority
775 ? renderengine::RenderEngine::ContextPriority::REALTIME
776 : renderengine::RenderEngine::ContextPriority::MEDIUM);
777 if (auto type = chooseRenderEngineTypeViaSysProp()) {
778 builder.setRenderEngineType(type.value());
779 }
780 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700781 mMaxRenderTargetSize =
782 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700783
784 // Set SF main policy after initializing RenderEngine which has its own policy.
785 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
786 ALOGW("Failed to set main task profile");
787 }
788
Alec Mourie4034bb2019-11-19 12:45:54 -0800789 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700790 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800791 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000792 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800793
Ady Abraham9dada822022-02-03 10:26:59 -0800794 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
795
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800796 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
797 enableHalVirtualDisplays(true);
798 }
799
Lloyd Piqueba04e622017-12-14 17:11:26 -0800800 // Process any initial hotplug and resulting display changes.
801 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700802 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700803 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200804 const auto displayId = display->getPhysicalId();
805 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700806 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800807
Mathias Agopian92a979a2012-08-02 18:32:23 -0700808 // initialize our drawing state
809 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700810
Andy McFadden13a082e2012-08-24 10:16:42 -0700811 // set initial conditions (e.g. unblank default device)
812 initializeDisplays();
813
Alec Mouridea1ac52021-06-23 18:12:18 -0700814 mPowerAdvisor.init();
815
Steven Thomas137d4bc2019-07-25 16:55:14 -0700816 char primeShaderCache[PROPERTY_VALUE_MAX];
817 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
818 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700819 if (setSchedFifo(false) != NO_ERROR) {
820 ALOGW("Can't set SCHED_OTHER for primeCache");
821 }
822
823 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
824
825 if (setSchedFifo(true) != NO_ERROR) {
826 ALOGW("Can't set SCHED_OTHER for primeCache");
827 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700828 }
Dan Stoza4e637772016-07-28 13:31:51 -0700829
Ady Abrahamed3290f2021-05-17 15:12:14 -0700830 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400831
Wei Wangf9b05ee2017-07-19 20:59:39 -0700832 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700833
834 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800835 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700836 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700837
838 if (mStartPropertySetThread->Start() != NO_ERROR) {
839 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800840 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800841
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700843}
844
Romain Guy11d63f42017-07-20 12:47:14 -0700845void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700846 Mutex::Autolock _l(mStateLock);
847
Romain Guy11d63f42017-07-20 12:47:14 -0700848 char value[PROPERTY_VALUE_MAX];
849
850 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800851 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700852 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800853 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100854
855 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700856 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800857
858 property_get("persist.sys.sf.color_mode", value, "0");
859 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700860}
861
Mathias Agopiana67e4182012-06-19 17:26:12 -0700862void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800863 // Start boot animation service by setting a property mailbox
864 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700865 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800866 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700867 if (mStartPropertySetThread->join() != NO_ERROR) {
868 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800869 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700870}
871
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800872// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800873
Jamie Gennis582270d2011-08-17 18:19:00 -0700874bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800875 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800876 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800877 return authenticateSurfaceTextureLocked(bufferProducer);
878}
879
880bool SurfaceFlinger::authenticateSurfaceTextureLocked(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800881 const sp<IGraphicBufferProducer>& /* bufferProducer */) const {
882 return false;
Jamie Gennis134f0422011-03-08 12:18:54 -0800883}
884
Brian Anderson6b376712017-04-04 10:51:39 -0700885status_t SurfaceFlinger::getSupportedFrameTimestamps(
886 std::vector<FrameEvent>* outSupported) const {
887 *outSupported = {
888 FrameEvent::REQUESTED_PRESENT,
889 FrameEvent::ACQUIRE,
890 FrameEvent::LATCH,
891 FrameEvent::FIRST_REFRESH_START,
892 FrameEvent::LAST_REFRESH_START,
893 FrameEvent::GPU_COMPOSITION_DONE,
894 FrameEvent::DEQUEUE_READY,
895 FrameEvent::RELEASE,
896 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800897
898 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
899
Ady Abrahamde549d42022-01-26 19:19:17 -0800900 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700901 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
902 }
903 return NO_ERROR;
904}
905
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800906status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
907 if (!displayToken || !state) {
908 return BAD_VALUE;
909 }
910
911 Mutex::Autolock lock(mStateLock);
912
913 const auto display = getDisplayDeviceLocked(displayToken);
914 if (!display) {
915 return NAME_NOT_FOUND;
916 }
917
918 state->layerStack = display->getLayerStack();
919 state->orientation = display->getOrientation();
920
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200921 const Rect layerStackRect = display->getLayerStackSpaceRect();
922 state->layerStackSpaceRect =
923 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800924
925 return NO_ERROR;
926}
927
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100928status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
929 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800930 if (!displayToken || !info) {
931 return BAD_VALUE;
932 }
933
934 Mutex::Autolock lock(mStateLock);
935
936 const auto display = getDisplayDeviceLocked(displayToken);
937 if (!display) {
938 return NAME_NOT_FOUND;
939 }
940
Dominik Laskowski55c85402020-01-21 16:25:47 -0800941 if (const auto connectionType = display->getConnectionType())
942 info->connectionType = *connectionType;
943 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800944 return INVALID_OPERATION;
945 }
946
947 if (mEmulatedDisplayDensity) {
948 info->density = mEmulatedDisplayDensity;
949 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100950 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800951 ? mInternalDisplayDensity
952 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800953 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700954 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800955
956 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200957 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000958 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800959
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800960 return NO_ERROR;
961}
962
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100963status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
964 ui::DynamicDisplayInfo* info) {
965 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700966 return BAD_VALUE;
967 }
968
Dominik Laskowski22488f62019-03-28 09:53:04 -0700969 Mutex::Autolock lock(mStateLock);
970
Marin Shalamanov5801c942020-12-17 17:00:13 +0100971 const auto display = getDisplayDeviceLocked(displayToken);
972 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700973 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700974 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700975
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700976 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
977 if (!displayId) {
978 return INVALID_OPERATION;
979 }
980
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800981 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700982
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100983 const auto& supportedModes = display->getSupportedModes();
984 info->supportedDisplayModes.clear();
985 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800986
987 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100988 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800989 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700990
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800991 auto [width, height] = mode->getResolution();
992 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700993
ramindani06e518e2022-03-14 18:47:53 +0000994 if (const auto physicalOrientation = display->getPhysicalOrientation();
995 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800996 std::swap(width, height);
997 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700998 }
999
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001000 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -08001001
Huan Songf7eeb102022-03-28 11:02:38 -07001002 outMode.xDpi = xDpi;
1003 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001004
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001005 const nsecs_t period = mode->getVsyncPeriod();
1006 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001007
Ady Abraham8287e852020-08-12 14:44:58 -07001008 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001009 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001010 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1011 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1012 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001013
Andy McFadden91b2ca82014-06-13 14:04:23 -07001014 // This is how far in advance a buffer must be queued for
1015 // presentation at a given time. If you want a buffer to appear
1016 // on the screen at time N, you must submit the buffer before
1017 // (N - presentationDeadline).
1018 //
1019 // Normally it's one full refresh period (to give SF a chance to
1020 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001021 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001022 // composer or panel must be accounted for here.
1023 //
1024 // We add an additional 1ms to allow for processing time and
1025 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001026 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001027
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001028 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001029 }
1030
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001031 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001032 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001033 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001034
Marin Shalamanovb173f752021-02-16 19:38:36 +01001035 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001036 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001037 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001038 info->gameContentTypeSupported =
1039 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001040
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001041 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001042
1043 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001044 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1045 if (const auto modeId = display->translateModeId(*hwcId)) {
1046 info->preferredBootDisplayMode = modeId->value();
1047 }
1048 }
1049 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001050
Dan Stoza7f7da322014-05-02 15:26:25 -07001051 return NO_ERROR;
1052}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001053
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001054status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
1055 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001056 return BAD_VALUE;
1057 }
1058
Ady Abrahame90dd522020-12-29 12:08:45 -08001059 *stats = mScheduler->getDisplayStatInfo(systemTime());
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001060 return NO_ERROR;
1061}
1062
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001063void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001064 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001065
1066 if (!info.mode) {
1067 ALOGW("requested display mode is null");
1068 return;
1069 }
1070 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001071 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001072 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001073 return;
1074 }
1075
Ady Abraham690f4612021-07-01 23:24:03 -07001076 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001077 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001078
Alec Mouri754c98a2019-03-18 18:53:42 -07001079 // Start receiving vsync samples now, so that we can detect a period
1080 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001081 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001082 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001083 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001084 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001085
Ady Abraham690f4612021-07-01 23:24:03 -07001086 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001087 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001088 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001089}
1090
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001091status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001092 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001093
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001094 if (!displayToken) {
1095 return BAD_VALUE;
1096 }
Ady Abraham838de062019-02-04 10:24:03 -08001097
Dominik Laskowski756b7892021-08-04 12:53:59 -07001098 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001099 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001100 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001101 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001102 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001103 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001104 }
1105
1106 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001107 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001108 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001109 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001110
1111 const auto mode = display->getMode(DisplayModeId{modeId});
1112 if (!mode) {
1113 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1114 return BAD_VALUE;
1115 }
1116
1117 const auto fps = mode->getFps();
1118 // Keep the old switching type.
1119 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001120 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001121 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1122 allowGroupSwitching,
1123 {fps, fps}};
1124 constexpr bool kOverridePolicy = false;
1125
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001126 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001127 });
1128
1129 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001130}
1131
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001132void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001133 ATRACE_CALL();
1134
Dominik Laskowski22488f62019-03-28 09:53:04 -07001135 const auto display = getDefaultDisplayDeviceLocked();
1136 if (!display) {
1137 return;
1138 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001139
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001140 const auto upcomingModeInfo =
1141 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1142
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001143 if (!upcomingModeInfo.mode) {
1144 // There is no pending mode change. This can happen if the active
1145 // display changed and the mode change happened on a different display.
1146 return;
1147 }
1148
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001149 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001150 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1151 // We need to generate new sequenceId in order to recreate the display (and this
1152 // way the framebuffer).
1153 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001154 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001155 processDisplayChangesLocked();
1156
1157 // processDisplayChangesLocked will update all necessary components so we're done here.
1158 return;
1159 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001160
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001161 // We just created this display so we can call even if we are not on the main thread.
1162 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001163 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001164
Ady Abraham690f4612021-07-01 23:24:03 -07001165 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001166 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001167 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001168
Dominik Laskowski068173d2021-08-11 17:22:59 -07001169 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001170 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001171 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001172}
1173
Ady Abraham690f4612021-07-01 23:24:03 -07001174void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1175 display->clearDesiredActiveModeState();
1176 if (isDisplayActiveLocked(display)) {
1177 mScheduler->setModeChangePending(false);
1178 }
Ady Abraham53852a52019-05-28 18:07:44 -07001179}
1180
Ady Abraham690f4612021-07-01 23:24:03 -07001181void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1182 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1183 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001184 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001185 updatePhaseConfiguration(refreshRate);
1186}
1187
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001188void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001189 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001190
Marin Shalamanovdd594312021-11-09 16:37:37 +01001191 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1192
Ady Abraham690f4612021-07-01 23:24:03 -07001193 for (const auto& iter : mDisplays) {
1194 const auto& display = iter.second;
1195 if (!display || !display->isInternal()) {
1196 continue;
1197 }
1198
1199 // Store the local variable to release the lock.
1200 const auto desiredActiveMode = display->getDesiredActiveMode();
1201 if (!desiredActiveMode) {
1202 // No desired active mode pending to be applied
1203 continue;
1204 }
1205
1206 if (!isDisplayActiveLocked(display)) {
1207 // display is no longer the active display, so abort the mode change
1208 clearDesiredActiveModeState(display);
1209 continue;
1210 }
1211
1212 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1213 if (!desiredMode) {
1214 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1215 desiredActiveMode->mode->getId().value());
1216 clearDesiredActiveModeState(display);
1217 continue;
1218 }
1219
1220 const auto refreshRate = desiredMode->getFps();
1221 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1222 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1223 to_string(display->getId()).c_str());
1224
1225 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001226 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001227 desiredActiveModeChangeDone(display);
1228 continue;
1229 }
1230
1231 // Desired active mode was set, it is different than the mode currently in use, however
1232 // allowed modes might have changed by the time we process the refresh.
1233 // Make sure the desired mode is still allowed
1234 const auto displayModeAllowed =
1235 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1236 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001237 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001238 continue;
1239 }
1240
1241 // TODO(b/142753666) use constrains
1242 hal::VsyncPeriodChangeConstraints constraints;
1243 constraints.desiredTimeNanos = systemTime();
1244 constraints.seamlessRequired = false;
1245 hal::VsyncPeriodChangeTimeline outTimeline;
1246
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001247 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1248 display->initiateModeChange(*desiredActiveMode,
1249 constraints, &outTimeline));
1250
Ady Abraham690f4612021-07-01 23:24:03 -07001251 if (status != NO_ERROR) {
1252 // initiateModeChange may fail if a hotplug event is just about
1253 // to be sent. We just log the error in this case.
1254 ALOGW("initiateModeChange failed: %d", status);
1255 continue;
1256 }
1257 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1258
Marin Shalamanovdd594312021-11-09 16:37:37 +01001259 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001260 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001261 mSetActiveModePending = true;
1262 } else {
1263 // Updating the internal state should be done outside the loop,
1264 // because it can recreate a DisplayDevice and modify mDisplays
1265 // which will invalidate the iterator.
1266 displayToUpdateImmediately = display->getPhysicalId();
1267 }
1268 }
1269
1270 if (displayToUpdateImmediately) {
1271 updateInternalStateWithChangedMode();
1272
1273 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1274 const auto desiredActiveMode = display->getDesiredActiveMode();
1275 if (desiredActiveMode &&
1276 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1277 desiredActiveModeChangeDone(display);
1278 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001279 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001280}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001281
Alec Mouridea1ac52021-06-23 18:12:18 -07001282void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001283 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001284 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001285 ATRACE_NAME(whence);
Alec Mouridea1ac52021-06-23 18:12:18 -07001286 if (mPowerAdvisor.isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001287 for (const auto& [_, display] : mDisplays) {
1288 constexpr bool kDisable = false;
Alec Mouridea1ac52021-06-23 18:12:18 -07001289 mPowerAdvisor.setExpensiveRenderingExpected(display->getId(), kDisable);
1290 }
1291 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001292 });
1293
1294 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001295}
1296
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001297std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1298 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001299
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001300 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001301 // filter out all wide color modes. The typical reason why this happens is that the
1302 // hardware is not good enough to support GPU composition of wide color, and thus the
1303 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001304 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1305 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001306 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1307 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001308 }
Michael Wright28f24d02016-07-12 13:30:53 -07001309
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001310 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001311}
1312
Daniel Solomon42d04562019-01-20 21:03:19 -08001313status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1314 ui::DisplayPrimaries &primaries) {
1315 if (!displayToken) {
1316 return BAD_VALUE;
1317 }
1318
1319 // Currently we only support this API for a single internal display.
1320 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001321 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001322 }
1323
1324 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1325 return NO_ERROR;
1326}
1327
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001328status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001329 if (!displayToken) {
1330 return BAD_VALUE;
1331 }
1332
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001333 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001334 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001335 if (!display) {
1336 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1337 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001338 return NAME_NOT_FOUND;
1339 }
1340
1341 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001342 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1343 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001344 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001345 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001346
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001347 const auto modes = getDisplayColorModes(*display);
1348 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1349
1350 if (mode < ColorMode::NATIVE || !exists) {
1351 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1352 decodeColorMode(mode).c_str(), mode, displayToken.get());
1353 return BAD_VALUE;
1354 }
1355
1356 display->getCompositionDisplay()->setColorProfile(
1357 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1358
1359 return NO_ERROR;
1360 });
1361
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001362 // TODO(b/195698395): Propagate error.
1363 future.wait();
1364 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001365}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001366
Kriti Dang7defaf32021-11-15 11:55:43 +01001367status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001368 auto future = mScheduler->schedule(
1369 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1370
1371 *outSupport = future.get();
1372 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001373}
1374
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001375status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1376 ui::DisplayModeId modeId) {
1377 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001378 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001379 const auto display = getDisplayDeviceLocked(displayToken);
1380 if (!display) {
1381 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1382 return NAME_NOT_FOUND;
1383 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001384
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001385 if (display->isVirtual()) {
1386 ALOGE("%s: Invalid operation on virtual display", whence);
1387 return INVALID_OPERATION;
1388 }
1389
1390 const auto displayId = display->getPhysicalId();
1391 const auto mode = display->getMode(DisplayModeId{modeId});
1392 if (!mode) {
1393 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1394 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001395 return BAD_VALUE;
1396 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001397
1398 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001399 });
1400 return future.get();
1401}
1402
1403status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001404 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001405 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001406 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1407 return getHwComposer().clearBootDisplayMode(*displayId);
1408 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001409 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001410 return BAD_VALUE;
1411 }
1412 });
1413 return future.get();
1414}
1415
Galia Peycheva5492cb52019-10-30 14:13:16 +01001416void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001417 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001418 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001419 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1420 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1421 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001422 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001423 }
1424 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001425}
1426
Galia Peycheva5492cb52019-10-30 14:13:16 +01001427void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001428 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001429 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001430 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001431 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001432 getHwComposer().setContentType(*displayId, type);
1433 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001434 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001435 }
1436 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001437}
1438
Svetoslavd85084b2014-03-20 10:28:31 -07001439status_t SurfaceFlinger::clearAnimationFrameStats() {
1440 Mutex::Autolock _l(mStateLock);
1441 mAnimFrameTracker.clearStats();
1442 return NO_ERROR;
1443}
1444
1445status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1446 Mutex::Autolock _l(mStateLock);
1447 mAnimFrameTracker.getStats(outStats);
1448 return NO_ERROR;
1449}
1450
Kriti Dang49ad4132021-01-08 11:49:56 +01001451status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1452 const std::vector<ui::Hdr>& hdrTypes) {
1453 Mutex::Autolock lock(mStateLock);
1454
1455 auto display = getDisplayDeviceLocked(displayToken);
1456 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001457 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001458 return NAME_NOT_FOUND;
1459 }
1460
1461 display->overrideHdrTypes(hdrTypes);
1462 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1463 return NO_ERROR;
1464}
1465
Tej Singhe2751772021-04-06 22:05:29 -07001466status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1467 *success = mTimeStats->onPullAtom(atomId, pulledData);
1468 return NO_ERROR;
1469}
1470
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001471status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1472 ui::PixelFormat* outFormat,
1473 ui::Dataspace* outDataspace,
1474 uint8_t* outComponentMask) const {
1475 if (!outFormat || !outDataspace || !outComponentMask) {
1476 return BAD_VALUE;
1477 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001478
1479 Mutex::Autolock lock(mStateLock);
1480
1481 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1482 if (!displayId) {
1483 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001484 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001485
1486 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001487 outDataspace, outComponentMask);
1488}
1489
Kevin DuBois74e53772018-11-19 10:52:38 -08001490status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1491 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001492 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001493 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001494 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001495 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1496 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1497 componentMask, maxFrames);
1498 } else {
1499 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1500 return NAME_NOT_FOUND;
1501 }
1502 });
1503
1504 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001505}
1506
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001507status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1508 uint64_t maxFrames, uint64_t timestamp,
1509 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001510 Mutex::Autolock lock(mStateLock);
1511
1512 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1513 if (!displayId) {
1514 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001515 }
1516
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001517 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001518}
1519
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001520status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1521 if (!outSupported) {
1522 return BAD_VALUE;
1523 }
1524 *outSupported = getRenderEngine().supportsProtectedContent();
1525 return NO_ERROR;
1526}
1527
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001528status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1529 bool* outIsWideColorDisplay) const {
1530 if (!displayToken || !outIsWideColorDisplay) {
1531 return BAD_VALUE;
1532 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001533
1534 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001535 const auto display = getDisplayDeviceLocked(displayToken);
1536 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001537 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001538 }
Peiyong Linff84a152019-05-17 18:36:19 -07001539
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001540 *outIsWideColorDisplay =
1541 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001542 return NO_ERROR;
1543}
1544
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001545status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001546 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001547 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001548
Dominik Laskowski6505f792019-09-18 11:10:05 -07001549 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001550 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001551 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001552 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001553
Dominik Laskowski756b7892021-08-04 12:53:59 -07001554 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001555 return NO_ERROR;
1556}
1557
1558status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001559 Mutex::Autolock lock(mStateLock);
Ady Abrahame90dd522020-12-29 12:08:45 -08001560 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(when);
Ady Abraham56b42a42020-12-28 16:48:48 -08001561 const auto expectedPresent = calculateExpectedPresentTime(stats);
Ady Abraham9c53ee72020-07-22 21:16:18 -07001562 return mScheduler->injectVSync(when, /*expectedVSyncTime=*/expectedPresent,
1563 /*deadlineTimestamp=*/expectedPresent)
1564 ? NO_ERROR
1565 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001566}
1567
Huihong Luo05539a12022-02-23 10:29:40 -08001568status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001569 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001570 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001571 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001572 mDrawingState.traverseInZOrder([&](Layer* layer) {
1573 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1574 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001575 });
1576
1577 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001578 return NO_ERROR;
1579}
1580
Peiyong Linc6780972018-10-28 15:24:08 -07001581status_t SurfaceFlinger::getCompositionPreference(
1582 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1583 Dataspace* outWideColorGamutDataspace,
1584 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001585 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001586 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001587 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001588 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001589 return NO_ERROR;
1590}
1591
Dan Stozaec460082018-12-17 15:35:09 -08001592status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1593 const sp<IBinder>& stopLayerHandle,
1594 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001595 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001596 return BAD_VALUE;
1597 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001598
1599 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1600 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001601 return NO_ERROR;
1602}
1603
Dan Stozaec460082018-12-17 15:35:09 -08001604status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001605 if (!listener) {
1606 return BAD_VALUE;
1607 }
Dan Stozaec460082018-12-17 15:35:09 -08001608 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001609 return NO_ERROR;
1610}
Dan Gittik57e63c52019-01-18 16:37:54 +00001611
Alec Mouria9a68a62021-03-04 19:14:50 -08001612status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001613 if (!listener) {
1614 return BAD_VALUE;
1615 }
1616
Alec Mouria9a68a62021-03-04 19:14:50 -08001617 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001618 return NO_ERROR;
1619}
1620
1621status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1622 if (!listener) {
1623 return BAD_VALUE;
1624 }
1625 mFpsReporter->removeListener(listener);
1626 return NO_ERROR;
1627}
1628
Galia Peycheva8f04b302021-04-27 13:25:38 +02001629status_t SurfaceFlinger::addTunnelModeEnabledListener(
1630 const sp<gui::ITunnelModeEnabledListener>& listener) {
1631 if (!listener) {
1632 return BAD_VALUE;
1633 }
1634
1635 mTunnelModeEnabledReporter->addListener(listener);
1636 return NO_ERROR;
1637}
1638
1639status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1640 const sp<gui::ITunnelModeEnabledListener>& listener) {
1641 if (!listener) {
1642 return BAD_VALUE;
1643 }
1644
1645 mTunnelModeEnabledReporter->removeListener(listener);
1646 return NO_ERROR;
1647}
1648
Dan Gittik57e63c52019-01-18 16:37:54 +00001649status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1650 bool* outSupport) const {
1651 if (!displayToken || !outSupport) {
1652 return BAD_VALUE;
1653 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001654
1655 Mutex::Autolock lock(mStateLock);
1656
Dan Gittik57e63c52019-01-18 16:37:54 +00001657 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1658 if (!displayId) {
1659 return NAME_NOT_FOUND;
1660 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001661 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001662 return NO_ERROR;
1663}
1664
Alec Mouricdf16792021-12-10 13:16:06 -08001665bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1666 bool hasHdrLayers = false;
1667 mDrawingState.traverse([&,
1668 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1669 hasHdrLayers |= (layer->isVisible() &&
1670 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1671 isHdrDataspace(layer->getDataSpace()));
1672 });
1673 return hasHdrLayers;
1674}
1675
John Reck22be6962021-03-10 12:59:54 -05001676status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1677 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001678 if (!displayToken) {
1679 return BAD_VALUE;
1680 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001681
Dominik Laskowski756b7892021-08-04 12:53:59 -07001682 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001683 return ftl::chain(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001684 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001685 const bool supportsDisplayBrightnessCommand =
1686 getHwComposer().getComposer()->isSupported(
1687 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1688 // If we support applying display brightness as a command, then we also support
1689 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001690 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001691 auto compositionDisplay = display->getCompositionDisplay();
1692 float currentDimmingRatio =
1693 compositionDisplay->editState().sdrWhitePointNits /
1694 compositionDisplay->editState().displayBrightnessNits;
1695 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1696 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001697 FTL_FAKE_GUARD(kMainThreadContext,
1698 display->stageBrightness(brightness.displayBrightness));
1699
Alec Mouri6da0e272022-02-07 12:45:57 -08001700 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1701 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001702 scheduleComposite(FrameHint::kNone);
1703 } else {
1704 scheduleCommit(FrameHint::kNone);
1705 }
1706 return ftl::yield<status_t>(OK);
1707 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001708 return getHwComposer()
1709 .setDisplayBrightness(display->getPhysicalId(),
1710 brightness.displayBrightness,
1711 Hwc2::Composer::DisplayBrightnessOptions{
1712 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001713 }
Alec Mouricdf16792021-12-10 13:16:06 -08001714
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001715 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001716 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001717 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001718 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001719 }))
1720 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001721 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001722}
1723
John Reck88270902021-03-18 11:27:35 -04001724status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1725 const sp<gui::IHdrLayerInfoListener>& listener) {
1726 if (!displayToken) {
1727 return BAD_VALUE;
1728 }
1729
1730 Mutex::Autolock lock(mStateLock);
1731
1732 const auto display = getDisplayDeviceLocked(displayToken);
1733 if (!display) {
1734 return NAME_NOT_FOUND;
1735 }
1736 const auto displayId = display->getId();
1737 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1738 if (!hdrInfoReporter) {
1739 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1740 }
1741 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001742
1743
1744 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001745 return OK;
1746}
1747
1748status_t SurfaceFlinger::removeHdrLayerInfoListener(
1749 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1750 if (!displayToken) {
1751 return BAD_VALUE;
1752 }
1753
1754 Mutex::Autolock lock(mStateLock);
1755
1756 const auto display = getDisplayDeviceLocked(displayToken);
1757 if (!display) {
1758 return NAME_NOT_FOUND;
1759 }
1760 const auto displayId = display->getId();
1761 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1762 if (hdrInfoReporter) {
1763 hdrInfoReporter->removeListener(listener);
1764 }
1765 return OK;
1766}
1767
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001768status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001769 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001770 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001771
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001772 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001773 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001774 }
1775
1776 return NO_ERROR;
1777}
1778
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001779status_t SurfaceFlinger::getDisplayDecorationSupport(
1780 const sp<IBinder>& displayToken,
1781 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001782 if (!displayToken || !outSupport) {
1783 return BAD_VALUE;
1784 }
1785
1786 Mutex::Autolock lock(mStateLock);
1787
1788 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1789 if (!displayId) {
1790 return NAME_NOT_FOUND;
1791 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001792 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001793 return NO_ERROR;
1794}
1795
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001796// ----------------------------------------------------------------------------
1797
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001798sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham62f216c2020-10-13 19:07:23 -07001799 ISurfaceComposer::VsyncSource vsyncSource,
1800 ISurfaceComposer::EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001801 const auto& handle =
1802 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001803
Ady Abraham62f216c2020-10-13 19:07:23 -07001804 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001805}
1806
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001807void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001808 if (hint == FrameHint::kActive) {
1809 mScheduler->resetIdleTimer();
1810 }
Dan Stoza030fbc12020-02-19 15:32:01 -08001811 mPowerAdvisor.notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001812 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001813}
1814
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001815void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1816 mMustComposite = true;
1817 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001818}
1819
1820void SurfaceFlinger::scheduleRepaint() {
1821 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001822 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001823}
1824
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001825void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001826 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001827}
1828
Ady Abraham2492a022020-07-24 11:09:55 -07001829nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001830 if (const auto display = getDefaultDisplayDeviceLocked()) {
1831 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001832 }
1833
Marin Shalamanov045b7002021-01-07 16:56:24 +01001834 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001835}
1836
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001837void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1838 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001839 const std::string tracePeriod = [vsyncPeriod]() {
1840 if (ATRACE_ENABLED() && vsyncPeriod) {
1841 std::stringstream ss;
1842 ss << "(" << *vsyncPeriod << ")";
1843 return ss.str();
1844 }
1845 return std::string();
1846 }();
1847 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001848
Steven Thomas3cfac282017-02-06 12:29:30 -08001849 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001850 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1851 if (displayId) {
1852 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1853 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001854 display->onVsync(timestamp);
1855 }
1856
Dominik Laskowski075d3172018-05-24 15:50:06 -07001857 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001858 return;
1859 }
1860
Ady Abrahame1166472021-07-15 10:56:06 -07001861 const bool isActiveDisplay =
1862 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1863 if (!isActiveDisplay) {
1864 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001865 return;
1866 }
1867
Alec Mourif8e689c2019-05-20 18:32:22 -07001868 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001869 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001870 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001871 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001872 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001873}
1874
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001875void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001876 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1877 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001878}
1879
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001880void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1881 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001882 const bool connected = connection == hal::Connection::CONNECTED;
1883 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001884
Steven Thomasb02664d2017-07-26 18:48:28 -07001885 // Only lock if we're not on the main thread. This function is normally
1886 // called on a hwbinder thread, but for the primary display it's called on
1887 // the main thread with the state lock already held, so don't attempt to
1888 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001889 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001890
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001891 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001892
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001893 if (std::this_thread::get_id() == mMainThreadId) {
1894 // Process all pending hot plug events immediately if we are on the main thread.
1895 processDisplayHotplugEventsLocked();
1896 }
1897
Lloyd Piqueba04e622017-12-14 17:11:26 -08001898 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001899}
1900
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001901void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1902 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001903 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001904 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001905
1906 if (timeline.refreshRequired) {
1907 scheduleComposite(FrameHint::kNone);
1908 }
Ady Abraham7159f572019-10-11 11:10:18 -07001909}
1910
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001911void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001912 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001913 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1914}
1915
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001916void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001917 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001918 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001919}
1920
Yichi Chen3401b562022-01-17 15:42:35 +08001921void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001922 ATRACE_CALL();
1923 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001924}
1925
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001926void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001927 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001928
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001929 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001930 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001931 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001932
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001933 if (const auto display = getDefaultDisplayDeviceLocked();
1934 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001935 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001936 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001937 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001938}
1939
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001940SurfaceFlinger::FenceWithFenceTime SurfaceFlinger::previousFrameFence() {
Ady Abrahamccf4b472021-05-11 19:53:01 -07001941 const auto now = systemTime();
1942 const auto vsyncPeriod = mScheduler->getDisplayStatInfo(now).vsyncPeriod;
1943 const bool expectedPresentTimeIsTheNextVsync = mExpectedPresentTime - now <= vsyncPeriod;
1944 return expectedPresentTimeIsTheNextVsync ? mPreviousPresentFences[0]
1945 : mPreviousPresentFences[1];
Alec Mouri6d414b52020-03-17 11:18:05 -07001946}
1947
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001948bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001949 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001950 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001951
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001952 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001953 return false;
1954 }
1955
Dan Stoza59083052020-04-28 10:13:20 -07001956 const status_t status = fence->wait(graceTimeMs);
1957 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1958 // which calls wait(0) again internally
1959 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001960}
1961
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001962nsecs_t SurfaceFlinger::previousFramePresentTime() {
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001963 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001964
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001965 if (fence == FenceTime::NO_FENCE) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001966 return Fence::SIGNAL_TIME_INVALID;
1967 }
1968
1969 return fence->getSignalTime();
1970}
1971
Ady Abraham56b42a42020-12-28 16:48:48 -08001972nsecs_t SurfaceFlinger::calculateExpectedPresentTime(DisplayStatInfo stats) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001973 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham8cb21882020-08-26 18:22:05 -07001974 return mVsyncModulator->getVsyncConfig().sfOffset > 0 ? stats.vsyncTime
1975 : stats.vsyncTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001976}
1977
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001978bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1979 FTL_FAKE_GUARD(kMainThreadContext) {
Matt Buckleyef51fba2021-10-12 19:30:12 +00001980 // we set this once at the beginning of commit to ensure consistency throughout the whole frame
1981 mPowerHintSessionData.sessionEnabled = mPowerAdvisor.usePowerHintSession();
1982 if (mPowerHintSessionData.sessionEnabled) {
1983 mPowerHintSessionData.commitStart = systemTime();
1984 }
1985
Dan Stoza28d46a52020-04-28 09:54:54 -07001986 // calculate the expected present time once and use the cached
1987 // value throughout this frame to make sure all layers are
1988 // seeing this same value.
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001989 if (expectedVsyncTime >= frameTime) {
1990 mExpectedPresentTime = expectedVsyncTime;
Snild Dolkow819636c2021-01-22 14:42:08 +01001991 } else {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001992 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(frameTime);
Snild Dolkow819636c2021-01-22 14:42:08 +01001993 mExpectedPresentTime = calculateExpectedPresentTime(stats);
1994 }
1995
1996 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001997 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07001998
Matt Buckleyef51fba2021-10-12 19:30:12 +00001999 if (mPowerHintSessionData.sessionEnabled) {
2000 mPowerAdvisor.setTargetWorkDuration(mExpectedPresentTime -
2001 mPowerHintSessionData.commitStart);
2002 }
Ady Abraham893c99d2021-04-30 16:00:23 -07002003 const auto vsyncIn = [&] {
2004 if (!ATRACE_ENABLED()) return 0.f;
2005 return (mExpectedPresentTime - systemTime()) / 1e6f;
2006 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002007 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
2008 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002009
Dan Stoza28d46a52020-04-28 09:54:54 -07002010 // When Backpressure propagation is enabled we want to give a small grace period
2011 // for the present fence to fire instead of just giving up on this frame to handle cases
2012 // where present fence is just about to get signaled.
2013 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002014 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002015
2016 // Pending frames may trigger backpressure propagation.
2017 const TracedOrdinal<bool> framePending = {"PrevFramePending",
2018 previousFramePending(graceTimeForPresentFenceMs)};
2019
2020 // Frame missed counts for metrics tracking.
2021 // A frame is missed if the prior frame is still pending. If no longer pending,
2022 // then we still count the frame as missed if the predicted present time
2023 // was further in the past than when the fence actually fired.
2024
2025 // Add some slop to correct for drift. This should generally be
2026 // smaller than a typical frame duration, but should not be so small
2027 // that it reports reasonable drift as a missed frame.
Ady Abrahame90dd522020-12-29 12:08:45 -08002028 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(systemTime());
Dan Stoza28d46a52020-04-28 09:54:54 -07002029 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
2030 const nsecs_t previousPresentTime = previousFramePresentTime();
2031 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2032 framePending ||
2033 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002034 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002035 previousPresentTime - frameMissedSlop))};
2036 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2037 mHadDeviceComposition && frameMissed};
2038 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2039 mHadClientComposition && frameMissed};
2040
2041 if (frameMissed) {
2042 mFrameMissedCount++;
2043 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002044 }
2045
2046 if (hwcFrameMissed) {
2047 mHwcFrameMissedCount++;
2048 }
2049
2050 if (gpuFrameMissed) {
2051 mGpuFrameMissedCount++;
2052 }
2053
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002054 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002055 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002056 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002057 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002058 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002059 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002060 }
2061
2062 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002063 // the mode, hence we update SF.
2064 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002065 {
2066 Mutex::Autolock lock(mStateLock);
2067 updateInternalStateWithChangedMode();
2068 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002069 }
2070
John Reck2ec53912020-07-07 16:53:55 -07002071 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002072 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002073 scheduleCommit(FrameHint::kNone);
2074 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002075 }
2076 }
2077
Dan Stoza28d46a52020-04-28 09:54:54 -07002078 if (mTracingEnabledChanged) {
Vishnu Nair7891e962021-11-11 12:07:21 -08002079 mLayerTracingEnabled = mLayerTracing.isEnabled();
Dan Stoza28d46a52020-04-28 09:54:54 -07002080 mTracingEnabledChanged = false;
2081 }
2082
Ady Abraham29d0da32020-07-16 18:39:33 -07002083 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002084 Mutex::Autolock lock(mStateLock);
2085 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002086 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002087 }
2088 }
2089
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002090 // Composite if transactions were committed, or if requested by HWC.
2091 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002092 {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002093 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(stats.vsyncPeriod));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002094
chaviw6b9ffea2021-11-08 09:25:48 -06002095 bool needsTraversal = false;
2096 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002097 needsTraversal |= commitCreatedLayers();
2098 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002099 }
2100
2101 const bool shouldCommit =
2102 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2103 if (shouldCommit) {
2104 commitTransactions();
2105 }
2106
2107 if (transactionFlushNeeded()) {
2108 setTransactionFlags(eTransactionFlushNeeded);
2109 }
2110
2111 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002112 mustComposite |= latchBuffers();
2113
chaviw6b9ffea2021-11-08 09:25:48 -06002114 // This has to be called after latchBuffers because we want to include the layers that have
2115 // been latched in the commit callback
2116 if (!needsTraversal) {
2117 // Invoke empty transaction callbacks early.
2118 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2119 } else {
2120 // Invoke OnCommit callbacks.
2121 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2122 }
2123
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002124 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002125 }
2126
2127 // Layers need to get updated (in the previous line) before we can use them for
2128 // choosing the refresh rate.
2129 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2130 // and may eventually call to ~Layer() if it holds the last reference
2131 {
2132 Mutex::Autolock _l(mStateLock);
2133 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002134 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002135 }
2136
Dan Stoza28d46a52020-04-28 09:54:54 -07002137 updateCursorAsync();
2138 updateInputFlinger();
2139
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002140 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2141 // This will block and tracing should only be enabled for debugging.
2142 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
2143 }
2144
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002145 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002146
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002147 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002148}
2149
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002150void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2151 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002152 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002153
Matt Buckleyef51fba2021-10-12 19:30:12 +00002154 if (mPowerHintSessionData.sessionEnabled) {
2155 mPowerHintSessionData.compositeStart = systemTime();
2156 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07002157
Lloyd Piqueab039b52019-02-13 14:22:42 -08002158 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002159 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002160 refreshArgs.outputs.reserve(displays.size());
2161 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002162 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2163 }
2164 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002165 if (auto layerFE = layer->getCompositionEngineLayerFE())
2166 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002167 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002168 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002169 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002170 if (auto layerFE = layer->getCompositionEngineLayerFE())
2171 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002172 }
2173
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002174 refreshArgs.outputColorSetting = useColorManagement
2175 ? mDisplayColorSetting
2176 : compositionengine::OutputColorSetting::kUnmanaged;
2177 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2178 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002179
2180 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002181 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002182 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002183 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002184
2185 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2186 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2187 mDrawingState.colorMatrixChanged = false;
2188 }
2189
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002190 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002191
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002192 if (mDebugFlashDelay != 0) {
2193 refreshArgs.devOptForceClientComposition = true;
2194 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002195 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002196
Ady Abraham43065bd2021-12-10 17:22:15 -08002197 const auto expectedPresentTime = mExpectedPresentTime.load();
2198 const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
Ady Abrahamcaba2982021-06-16 16:45:04 -07002199 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2200 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002201 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002202 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002203 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002204
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002205 // Store the present time just before calling to the composition engine so we could notify
2206 // the scheduler.
2207 const auto presentTime = systemTime();
2208
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002209 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002210
2211 if (mPowerHintSessionData.sessionEnabled) {
2212 mPowerHintSessionData.presentEnd = systemTime();
2213 }
2214
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002215 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002216
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002217 if (mScheduler->onPostComposition(presentTime)) {
2218 scheduleComposite(FrameHint::kNone);
2219 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002220
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002221 postFrame();
2222 postComposition();
2223
Midas Chien50f52e22020-09-26 17:57:42 +08002224 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002225
Robert Carra00eb142022-03-09 13:49:30 -08002226 mHadClientComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2227 const auto& state = pair.second->getCompositionDisplay()->getState();
2228 return state.usesClientComposition && !state.reusedClientComposition;
2229 });
2230 mHadDeviceComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2231 const auto& state = pair.second->getCompositionDisplay()->getState();
2232 return state.usesDeviceComposition;
2233 });
2234 mReusedClientComposition =
2235 std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2236 const auto& state = pair.second->getCompositionDisplay()->getState();
2237 return state.reusedClientComposition;
2238 });
2239 // Only report a strategy change if we move in and out of client composition
2240 if (prevFrameHadClientComposition != mHadClientComposition) {
2241 mTimeStats->incrementCompositionStrategyChanges();
Alec Mouri8f7a0102020-04-15 12:11:10 -07002242 }
2243
Yichi Chen28dee2c2020-07-06 21:24:14 +08002244 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002245 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2246 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002247
David Sodman7e4ae112018-02-09 15:02:28 -08002248 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002249 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002250 // This will block and should only be used for debugging.
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002251 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
Vishnu Nairdf529052019-06-07 14:53:14 -07002252 }
Robert Carr167bdde2021-07-28 11:26:51 -07002253
2254 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002255 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002256
2257 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002258 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002259 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002260
2261 // calculate total render time for performance hinting if adpf cpu hint is enabled,
2262 if (mPowerHintSessionData.sessionEnabled) {
2263 const nsecs_t flingerDuration =
2264 (mPowerHintSessionData.presentEnd - mPowerHintSessionData.commitStart);
2265 mPowerAdvisor.sendActualWorkDuration(flingerDuration, mPowerHintSessionData.presentEnd);
2266 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002267}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002268
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002269void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002270 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002271
Vishnu Nair4351ad52019-02-11 14:13:02 -08002272 if (mVisibleRegionsDirty) {
2273 computeLayerBounds();
2274 }
2275
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002276 for (auto& layer : mLayersPendingRefresh) {
2277 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002278 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002279 invalidateLayerStack(layer, visibleReg);
2280 }
2281 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002282}
2283
Ana Krulece588e312018-09-18 12:32:24 -07002284void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2285 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002286 // Update queue of past composite+present times and determine the
2287 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002288 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002289 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002290 while (!getBE().mCompositePresentTimes.empty()) {
2291 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002292 // Cached values should have been updated before calling this method,
2293 // which helps avoid duplicate syscalls.
2294 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2295 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2296 break;
2297 }
2298 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002299 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002300 }
2301
2302 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002303 while (getBE().mCompositePresentTimes.size() > 16) {
2304 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002305 }
2306
Ana Krulece588e312018-09-18 12:32:24 -07002307 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002308}
2309
Ana Krulece588e312018-09-18 12:32:24 -07002310void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2311 nsecs_t compositeToPresentLatency) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002312 // Avoid division by 0 by defaulting to 60Hz
2313 const auto vsyncPeriod = stats.vsyncPeriod ?: (60_Hz).getPeriodNsecs();
2314
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002315 // Integer division and modulo round toward 0 not -inf, so we need to
2316 // treat negative and positive offsets differently.
Ady Abraham8287e852020-08-12 14:44:58 -07002317 nsecs_t idealLatency = (mVsyncConfiguration->getCurrentConfigs().late.sfOffset > 0)
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002318 ? (vsyncPeriod -
2319 (mVsyncConfiguration->getCurrentConfigs().late.sfOffset % vsyncPeriod))
2320 : ((-mVsyncConfiguration->getCurrentConfigs().late.sfOffset) % vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002321
Ady Abraham8287e852020-08-12 14:44:58 -07002322 // Just in case mVsyncConfiguration->getCurrentConfigs().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002323 if (idealLatency <= 0) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002324 idealLatency = vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002325 }
2326
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002327 // Snap the latency to a value that removes scheduling jitter from the
2328 // composition and present times, which often have >1ms of jitter.
2329 // Reducing jitter is important if an app attempts to extrapolate
2330 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002331 // Snapping also allows an app to precisely calculate
Ady Abraham8287e852020-08-12 14:44:58 -07002332 // mVsyncConfiguration->getCurrentConfigs().late.sf with (presentLatency % interval).
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002333 const nsecs_t bias = vsyncPeriod / 2;
2334 const int64_t extraVsyncs = ((compositeToPresentLatency - idealLatency + bias) / vsyncPeriod);
Ady Abraham8d7e7842022-02-03 01:42:45 +00002335 const nsecs_t snappedCompositeToPresentLatency =
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002336 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002337
David Sodman99974d22017-11-28 12:04:33 -08002338 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002339 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002340 getBE().mCompositorTiming.interval = vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002341 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002342}
2343
John Reck49d9ad32022-02-23 19:03:31 -05002344bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
2345 if (!isHdrDataspace(layer->getDataSpace())) {
2346 return false;
2347 }
2348 if (mIgnoreHdrCameraLayers) {
2349 auto buffer = layer->getBuffer();
2350 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2351 return false;
2352 }
2353 }
2354 return true;
2355}
2356
ramindani06e518e2022-03-14 18:47:53 +00002357ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2358 bool isPrimary) const {
2359 const auto id = PhysicalDisplayId::tryCast(displayId);
2360 if (!id) {
2361 return ui::ROTATION_0;
2362 }
2363 if (getHwComposer().getComposer()->isSupported(
2364 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2365 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2366 case Hwc2::AidlTransform::ROT_90:
2367 return ui::ROTATION_90;
2368 case Hwc2::AidlTransform::ROT_180:
2369 return ui::ROTATION_180;
2370 case Hwc2::AidlTransform::ROT_270:
2371 return ui::ROTATION_270;
2372 default:
2373 return ui::ROTATION_0;
2374 }
2375 }
2376
2377 if (isPrimary) {
2378 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2379 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2380 case Values::ORIENTATION_90:
2381 return ui::ROTATION_90;
2382 case Values::ORIENTATION_180:
2383 return ui::ROTATION_180;
2384 case Values::ORIENTATION_270:
2385 return ui::ROTATION_270;
2386 default:
2387 break;
2388 }
2389 }
2390 return ui::ROTATION_0;
2391}
2392
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002393void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002394 ATRACE_CALL();
2395 ALOGV("postComposition");
2396
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002397 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002398
David Sodman73beded2017-11-15 11:56:06 -08002399 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002400 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002401 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002402 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002403 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002404 ->getRenderSurface()
2405 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002406 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002407 } else {
2408 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2409 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002410
David Sodman73beded2017-11-15 11:56:06 -08002411 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002412 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002413 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002414 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002415 mPreviousPresentFences[0].fenceTime =
2416 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2417
2418 getBE().mDisplayTimeline.push(mPreviousPresentFences[0].fenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002419
Vishnu Nair9a69a042021-06-18 13:19:49 -07002420 nsecs_t now = systemTime();
2421
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002422 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2423 // information from previous' frame classification is already available when sending jank info
2424 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002425 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002426 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002427
Vishnu Nair9a69a042021-06-18 13:19:49 -07002428 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002429
Lloyd Piqueab039b52019-02-13 14:22:42 -08002430 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2431 // be sampled a little later than when we started doing work for this frame,
2432 // but that should be okay since updateCompositorTiming has snapping logic.
2433 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002434 mPreviousPresentFences[0].fenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002435 CompositorTiming compositorTiming;
2436 {
David Sodman99974d22017-11-28 12:04:33 -08002437 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2438 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002439 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002440
Robert Carrc747ad02021-06-11 14:01:24 -07002441 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002442 layer->onPostComposition(display, glCompositionDoneFenceTime,
2443 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002444 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002445 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002446
John Reck88270902021-03-18 11:27:35 -04002447 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2448 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002449 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002450 {
2451 Mutex::Autolock lock(mStateLock);
2452 if (mFpsReporter) {
2453 mFpsReporter->dispatchLayerFps();
2454 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002455
2456 if (mTunnelModeEnabledReporter) {
2457 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2458 }
John Reck88270902021-03-18 11:27:35 -04002459 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002460 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2461 if (reporter && reporter->hasListeners()) {
2462 if (const auto display = getDisplayDeviceLocked(displayId)) {
2463 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002464 }
2465 }
2466 }
Robert Carr167bdde2021-07-28 11:26:51 -07002467 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2468 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002469 }
2470
Robert Carr167bdde2021-07-28 11:26:51 -07002471 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2472 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2473 HdrLayerInfoReporter::HdrLayerInfo info;
2474 int32_t maxArea = 0;
2475 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2476 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002477 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002478 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002479 const auto* outputLayer =
2480 compositionDisplay->getOutputLayerForLayer(layerFe);
2481 if (outputLayer) {
2482 info.numberOfHdrLayers++;
2483 const auto displayFrame = outputLayer->getState().displayFrame;
2484 const int32_t area = displayFrame.width() * displayFrame.height();
2485 if (area > maxArea) {
2486 maxArea = area;
2487 info.maxW = displayFrame.width();
2488 info.maxH = displayFrame.height();
2489 }
John Reckdb1a16b2021-07-09 13:05:52 -04002490 }
John Reck88270902021-03-18 11:27:35 -04002491 }
2492 }
Robert Carr167bdde2021-07-28 11:26:51 -07002493 });
2494 listener->dispatchHdrLayerInfo(info);
2495 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002496 }
2497
Robert Carr167bdde2021-07-28 11:26:51 -07002498 mSomeDataspaceChanged = false;
2499 mVisibleRegionsWereDirtyThisFrame = false;
2500
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002501 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002502 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002503 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002504
Ady Abrahamed3290f2021-05-17 15:12:14 -07002505 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002506 mPreviousPresentFences[0].fenceTime->isValid()) {
2507 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002508 }
2509
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002510 const bool isDisplayConnected =
2511 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002512
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002513 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002514 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002515 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002516 }
2517 }
2518
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002519 if (mAnimCompositionPending) {
2520 mAnimCompositionPending = false;
2521
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002522 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2523 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002524 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002525 // The HWC doesn't support present fences, so use the refresh
2526 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002527 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002528 mAnimFrameTracker.setActualPresentTime(presentTime);
2529 }
2530 mAnimFrameTracker.advanceFrame();
2531 }
Dan Stozab90cf072015-03-05 11:05:59 -08002532
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002533 mTimeStats->incrementTotalFrames();
Robert Carra00eb142022-03-09 13:49:30 -08002534 if (mHadClientComposition) {
2535 mTimeStats->incrementClientCompositionFrames();
2536 }
2537
2538 if (mReusedClientComposition) {
2539 mTimeStats->incrementClientCompositionReusedFrames();
2540 }
Vishnu Nair9b079a22020-01-21 14:36:08 -08002541
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002542 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002543
Alec Mouri717bcb62020-02-10 17:07:19 -08002544 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2545 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2546 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2547
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002548 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002549 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002550 return;
2551 }
2552
2553 nsecs_t currentTime = systemTime();
2554 if (mHasPoweredOff) {
2555 mHasPoweredOff = false;
2556 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002557 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002558 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002559 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2560 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002561 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002562 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002563 }
David Sodman4a36e932017-11-07 14:29:47 -08002564 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002565 }
David Sodman4a36e932017-11-07 14:29:47 -08002566 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002567
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002568 // Cleanup any outstanding resources due to rendering a prior frame.
2569 getRenderEngine().cleanupPostRender();
2570
Dan Stoza436ccf32018-06-21 12:10:12 -07002571 {
2572 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002573 if (mTexturePool.size() < mTexturePoolSize) {
2574 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002575 const size_t offset = mTexturePool.size();
2576 mTexturePool.resize(mTexturePoolSize);
2577 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2578 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002579 } else if (mTexturePool.size() > mTexturePoolSize) {
2580 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2581 const size_t offset = mTexturePoolSize;
2582 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2583 mTexturePool.resize(mTexturePoolSize);
2584 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002585 }
2586 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002587
Dan Stoza45de5ba2019-04-25 14:12:09 -07002588 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2589 // side-effect of getTotalSize(), so we check that again here
2590 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002591 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002592 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2593 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002594}
2595
chaviw79468ab2021-10-27 11:11:24 -05002596FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002597 const ui::Size maxSize = [this] {
2598 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002599
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002600 // The LayerTraceGenerator tool runs without displays.
2601 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002602
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002603 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2604 [](ui::Size size, const auto& pair) -> ui::Size {
2605 const auto& display = pair.second;
2606 return {std::max(size.getWidth(), display->getWidth()),
2607 std::max(size.getHeight(), display->getHeight())};
2608 });
2609 }();
chaviwb09c6552021-08-12 17:20:43 -05002610
2611 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2612 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002613 const float xMax = maxSize.getWidth() * 10.f;
2614 const float yMax = maxSize.getHeight() * 10.f;
2615
2616 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002617}
2618
2619void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002620 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002621 for (const auto& layer : mDrawingState.layersSortedByZ) {
2622 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002623 }
2624}
2625
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002626void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002627 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002628 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002629 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002630 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2631 logFrameStats();
2632 }
2633 }
2634}
2635
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002636void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002637 ATRACE_CALL();
2638
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002639 // Keep a copy of the drawing state (that is going to be overwritten
2640 // by commitTransactionsLocked) outside of mStateLock so that the side
2641 // effects of the State assignment don't happen with mStateLock held,
2642 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002643 State drawingState(mDrawingState);
2644
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002645 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002646 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647
Mathias Agopianca4d3602011-05-19 15:38:14 -07002648 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002649 // so we can call commitTransactionsLocked unconditionally.
2650 // We clear the flags with mStateLock held to guarantee that
2651 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002652 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002653 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002654
Mathias Agopianca4d3602011-05-19 15:38:14 -07002655 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002656}
2657
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002658std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2659 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002660 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2661 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002662
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002663 int attempt = 0;
2664 constexpr int kMaxAttempts = 3;
2665 do {
2666 hwcModes = getHwComposer().getModes(displayId);
2667 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2668 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2669
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002670 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2671 return mode.hwcId == *activeModeHwcId;
2672 };
2673
2674 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2675 break;
2676 }
2677 } while (++attempt < kMaxAttempts);
2678
2679 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002680 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002681 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002682 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002683
2684 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002685 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2686 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002687 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002688
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002689 ui::DisplayModeId nextModeId = 1 +
2690 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2691 [](ui::DisplayModeId max, const auto& pair) {
2692 return std::max(max, pair.first.value());
2693 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002694
2695 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002696 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002697 const DisplayModeId id{nextModeId++};
2698 newModes.try_emplace(id,
2699 DisplayMode::Builder(hwcMode.hwcId)
2700 .setId(id)
2701 .setPhysicalDisplayId(displayId)
2702 .setResolution({hwcMode.width, hwcMode.height})
2703 .setVsyncPeriod(hwcMode.vsyncPeriod)
2704 .setDpiX(hwcMode.dpiX)
2705 .setDpiY(hwcMode.dpiY)
2706 .setGroup(hwcMode.configGroup)
2707 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002708 }
2709
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002710 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002711 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002712 [](const auto& lhs, const auto& rhs) {
2713 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002714 });
2715
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002716 // Keep IDs if modes have not changed.
2717 const auto& modes = sameModes ? oldModes : newModes;
2718 const DisplayModePtr activeMode =
2719 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2720 return pair.second->getHwcId() == activeModeHwcId;
2721 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002722
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002723 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002724}
2725
Lloyd Piqueba04e622017-12-14 17:11:26 -08002726void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2727 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002728 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002729 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002730
Dominik Laskowski075d3172018-05-24 15:50:06 -07002731 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002732 continue;
2733 }
2734
Marin Shalamanova524a092020-07-27 21:39:55 +02002735 const auto displayId = info->id;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002736 const auto it = mPhysicalDisplayTokens.find(displayId);
2737
Peiyong Line9d809e2020-04-14 13:10:48 -07002738 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002739 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002740
Dominik Laskowski55c85402020-01-21 16:25:47 -08002741 if (it == mPhysicalDisplayTokens.end()) {
2742 ALOGV("Creating display %s", to_string(displayId).c_str());
2743
Dominik Laskowski075d3172018-05-24 15:50:06 -07002744 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002745 state.physical = {.id = displayId,
2746 .type = getHwComposer().getDisplayConnectionType(displayId),
2747 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002748 .deviceProductInfo = std::move(info->deviceProductInfo),
2749 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002750 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002751 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002752 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002753
2754 sp<IBinder> token = new BBinder();
2755 mCurrentState.displays.add(token, state);
2756 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002757 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002758 } else {
2759 ALOGV("Recreating display %s", to_string(displayId).c_str());
2760
2761 const auto token = it->second;
2762 auto& state = mCurrentState.displays.editValueFor(token);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002763 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId
Marin Shalamanova903d032020-12-29 20:35:13 +01002764 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002765 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002766 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2767 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2768 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002769 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002770 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002771 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002772
Dominik Laskowski55c85402020-01-21 16:25:47 -08002773 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002774 if (index >= 0) {
2775 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2776 mInterceptor->saveDisplayDeletion(state.sequenceId);
2777 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002778 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002779 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002780 }
2781
2782 processDisplayChangesLocked();
2783 }
2784
2785 mPendingHotplugEvents.clear();
2786}
2787
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002788void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002789 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2790 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002791 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2792 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002793}
2794
Lloyd Pique99d3da52018-01-22 17:48:03 -08002795sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002796 const wp<IBinder>& displayToken,
2797 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002798 const DisplayDeviceState& state,
2799 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002800 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002801 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002802 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002803 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002804 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002805 creationArgs.hasWideColorGamut = false;
2806 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002807
Dominik Laskowski55c85402020-01-21 16:25:47 -08002808 if (const auto& physical = state.physical) {
2809 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002810 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002811 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002812 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2813 getKernelIdleTimerProperties(compositionDisplay->getId());
2814
Ady Abraham3efa3942021-06-24 19:01:25 -07002815 scheduler::RefreshRateConfigs::Config config =
2816 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2817 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002818 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002819 .idleTimerTimeout = idleTimerTimeoutMs,
2820 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002821 creationArgs.refreshRateConfigs =
2822 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2823 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002824 }
2825
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002826 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
2827 creationArgs.isPrimary = id == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002828
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002829 if (useColorManagement) {
2830 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2831 for (ColorMode colorMode : modes) {
2832 if (isWideColorMode(colorMode)) {
2833 creationArgs.hasWideColorGamut = true;
2834 }
2835
2836 std::vector<RenderIntent> renderIntents =
2837 getHwComposer().getRenderIntents(*id, colorMode);
2838 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002839 }
2840 }
tangrobin6753a022018-08-10 10:58:54 +08002841 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002842
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002843 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2844 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2845 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002846 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002847
Lloyd Pique90c115d2018-09-18 21:39:42 -07002848 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002849 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002850 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002851
Lloyd Pique99d3da52018-01-22 17:48:03 -08002852 // Make sure that composition can never be stalled by a virtual display
2853 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002854 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002855 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002856 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2857 }
2858
Dominik Laskowski718f9602019-11-09 20:01:35 -08002859 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002860 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2861 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002862
Lloyd Pique99d3da52018-01-22 17:48:03 -08002863 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002864 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002865
Lloyd Pique9370a482019-10-03 17:58:30 -07002866 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002867
Ady Abraham8565ad22021-06-22 17:45:44 -07002868 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002869
2870 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002871 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002872 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002873 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002874 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002875 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002876 display->getCompositionDisplay()->setColorProfile(
2877 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2878 RenderIntent::COLORIMETRIC,
2879 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002880 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002881 FTL_FAKE_GUARD(kMainThreadContext,
2882 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002883 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002884 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002885
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002886 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002887 display->setProjection(state.orientation, state.layerStackSpaceRect,
2888 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002889 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002890 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002891
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002892 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002893}
2894
Marin Shalamanovae685592020-02-12 17:12:22 +01002895void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2896 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002897 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002898 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2899 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002900 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002901 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2902 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002903 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002904 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002905 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002906 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002907 int format;
2908 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002909 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002910 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002911 } else {
2912 // Virtual displays without a surface are dormant:
2913 // they have external state (layer stack, projection,
2914 // etc.) but no internal state (i.e. a DisplayDevice).
2915 return;
2916 }
2917
2918 compositionengine::DisplayCreationArgsBuilder builder;
2919 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002920 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002921 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002922 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002923 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002924
Marin Shalamanov045b7002021-01-07 16:56:24 +01002925 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002926 builder.setIsSecure(state.isSecure);
Marin Shalamanovae685592020-02-12 17:12:22 +01002927 builder.setPowerAdvisor(&mPowerAdvisor);
Marin Shalamanovae685592020-02-12 17:12:22 +01002928 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002929 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002930 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002931
2932 sp<compositionengine::DisplaySurface> displaySurface;
2933 sp<IGraphicBufferProducer> producer;
2934 sp<IGraphicBufferProducer> bqProducer;
2935 sp<IGraphicBufferConsumer> bqConsumer;
2936 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2937
Marin Shalamanovae685592020-02-12 17:12:22 +01002938 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002939 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2940 LOG_FATAL_IF(!displayId);
2941 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2942 bqProducer, bqConsumer, state.displayName);
2943 displaySurface = surface;
2944 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002945 } else {
2946 ALOGE_IF(state.surface != nullptr,
2947 "adding a supported display, but rendering "
2948 "surface is provided (%p), ignoring it",
2949 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002950 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2951 LOG_FATAL_IF(!displayId);
2952 displaySurface =
2953 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002954 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002955 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002956 producer = bqProducer;
2957 }
2958
Marin Shalamanov700e6392020-02-12 20:22:26 +01002959 LOG_FATAL_IF(!displaySurface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002960 const auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay),
2961 state, displaySurface, producer);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002962 mDisplays.emplace(displayToken, display);
Ady Abraham3efa3942021-06-24 19:01:25 -07002963 if (display->isPrimary()) {
2964 initScheduler(display);
2965 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002966 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002967 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002968 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002969}
2970
2971void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002972 auto display = getDisplayDeviceLocked(displayToken);
2973 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002974 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002975
2976 if (display->isVirtual()) {
2977 releaseVirtualDisplay(display->getVirtualId());
2978 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002979 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01002980 }
2981 }
2982
2983 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08002984
2985 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002986 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002987 // Destroy the display without holding the mStateLock.
2988 // This is a temporary solution until we can manage transaction queues without
2989 // holding the mStateLock.
2990 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
2991 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
2992 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
2993 // ends up running on the main thread causing a deadlock since setTransactionstate
2994 // will try to acquire the mStateLock. Instead we extend the lifetime of
2995 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
2996 // The display will be disconnected and removed from the mDisplays list so it will
2997 // not be accessible.
2998 }));
2999 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003000}
3001
3002void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
3003 const DisplayDeviceState& currentState,
3004 const DisplayDeviceState& drawingState) {
3005 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3006 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003007
3008 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01003009 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02003010 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003011
Marin Shalamanovae685592020-02-12 17:12:22 +01003012 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3013 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003014 if (display->isVirtual()) {
3015 releaseVirtualDisplay(display->getVirtualId());
3016 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003017 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003018
Marin Shalamanovae685592020-02-12 17:12:22 +01003019 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003020
Marin Shalamanov700e6392020-02-12 20:22:26 +01003021 if (const auto& physical = currentState.physical) {
3022 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3023 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003024
Marin Shalamanovae685592020-02-12 17:12:22 +01003025 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003026
Marin Shalamanov700e6392020-02-12 20:22:26 +01003027 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003028 const auto display = getDisplayDeviceLocked(displayToken);
3029 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003030
3031 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003032 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003033 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003034 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003035 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003036 return;
3037 }
3038
3039 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3040 if (currentState.layerStack != drawingState.layerStack) {
3041 display->setLayerStack(currentState.layerStack);
3042 }
Evan Rosky2239b372021-05-20 13:43:47 -07003043 if (currentState.flags != drawingState.flags) {
3044 display->setFlags(currentState.flags);
3045 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003046 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003047 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3048 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3049 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3050 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003051 if (isDisplayActiveLocked(display)) {
3052 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003053 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003054 }
3055 if (currentState.width != drawingState.width ||
3056 currentState.height != drawingState.height) {
3057 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003058
Ady Abrahamed3290f2021-05-17 15:12:14 -07003059 if (isDisplayActiveLocked(display)) {
3060 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003061 }
3062 }
3063 }
3064}
Ady Abraham3efa3942021-06-24 19:01:25 -07003065void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003066 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003067 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003068 updatePhaseConfiguration(refreshRate);
3069 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003070}
Marin Shalamanovae685592020-02-12 17:12:22 +01003071
Lloyd Pique347200f2017-12-14 17:00:15 -08003072void SurfaceFlinger::processDisplayChangesLocked() {
3073 // here we take advantage of Vector's copy-on-write semantics to
3074 // improve performance by skipping the transaction entirely when
3075 // know that the lists are identical
3076 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3077 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3078 if (!curr.isIdenticalTo(draw)) {
3079 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003080
3081 // find the displays that were removed
3082 // (ie: in drawing state but not in current state)
3083 // also handle displays that changed
3084 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003085 for (size_t i = 0; i < draw.size(); i++) {
3086 const wp<IBinder>& displayToken = draw.keyAt(i);
3087 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003088 if (j < 0) {
3089 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003090 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003091 } else {
3092 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003093 const DisplayDeviceState& currentState = curr[j];
3094 const DisplayDeviceState& drawingState = draw[i];
3095 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003096 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003097 }
3098
3099 // find displays that were added
3100 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003101 for (size_t i = 0; i < curr.size(); i++) {
3102 const wp<IBinder>& displayToken = curr.keyAt(i);
3103 if (draw.indexOfKey(displayToken) < 0) {
3104 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003105 }
3106 }
3107 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003108
3109 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003110}
3111
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003112void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3113 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003114 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3115 if (displayTransactionNeeded) {
3116 processDisplayChangesLocked();
3117 processDisplayHotplugEventsLocked();
3118 }
Robert Carrb552ff52021-06-11 13:35:54 -07003119 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120
Robert Carre450fb52021-06-11 13:21:09 -07003121 if (mSomeChildrenChanged) {
3122 mVisibleRegionsDirty = true;
3123 mSomeChildrenChanged = false;
3124 }
3125
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003126 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003127 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003128 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003129 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003130 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003131 // the hint is set before we acquire a buffer from the surface texture.
3132 //
3133 // NOTE: layer transactions have taken place already, so we use their
3134 // drawing state. However, SurfaceFlinger's own transaction has not
3135 // happened yet, so we must use the current state layer list
3136 // (soon to become the drawing state list).
3137 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003138 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003139 ui::LayerStack layerStack;
3140
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003141 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003142 // NOTE: we rely on the fact that layers are sorted by
3143 // layerStack first (so we don't have to traverse the list
3144 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003145 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3146 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003147 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003148
3149 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003150 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003151 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3152 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003153 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003154
3155 // Pick the primary display if another display mirrors the layer.
3156 if (hintDisplay) {
3157 hintDisplay = nullptr;
3158 break;
3159 }
3160
3161 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003162 }
3163 }
Chet Haase91d25932013-04-11 15:24:55 -07003164
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003165 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003166 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3167 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003168
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003169 // could be null when this layer is using a layerStack
3170 // that is not visible on any display. Also can occur at
3171 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003172 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003173 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003174
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003175 layer->updateTransformHint(hintDisplay->getTransformHint());
Robert Carr2047fae2016-11-28 14:09:09 -08003176 });
Mathias Agopian84300952012-11-21 16:02:13 -08003177 }
3178
Robert Carr1f0a16a2016-10-24 16:27:39 -07003179 if (mLayersAdded) {
3180 mLayersAdded = false;
3181 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003182 mVisibleRegionsDirty = true;
3183 }
3184
3185 // some layers might have been removed, so
3186 // we need to update the regions they're exposing.
3187 if (mLayersRemoved) {
3188 mLayersRemoved = false;
3189 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003190 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003191 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003192 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003193 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003194 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003195 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003196 }
Robert Carr2047fae2016-11-28 14:09:09 -08003197 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003198 }
3199
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003200 doCommitTransactions();
3201 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3202 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003203}
3204
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003205void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003206 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003207 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003208 return;
3209 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003210
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003211 std::vector<WindowInfo> windowInfos;
3212 std::vector<DisplayInfo> displayInfos;
3213 bool updateWindowInfo = false;
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003214 if (mVisibleRegionsDirty || mInputInfoChanged) {
3215 mInputInfoChanged = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003216 updateWindowInfo = true;
3217 buildWindowInfos(windowInfos, displayInfos);
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003218 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003219 if (!updateWindowInfo && mInputWindowCommands.empty()) {
3220 return;
3221 }
3222 BackgroundExecutor::getInstance().execute([updateWindowInfo,
3223 windowInfos = std::move(windowInfos),
3224 displayInfos = std::move(displayInfos),
3225 inputWindowCommands =
3226 std::move(mInputWindowCommands),
3227 inputFlinger = mInputFlinger, this]() {
3228 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3229 if (updateWindowInfo) {
3230 mWindowInfosListenerInvoker->windowInfosChanged(windowInfos, displayInfos,
3231 inputWindowCommands.syncInputWindows);
3232 } else if (inputWindowCommands.syncInputWindows) {
3233 // If the caller requested to sync input windows, but there are no
3234 // changes to input windows, notify immediately.
3235 windowInfosReported();
3236 }
3237 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3238 inputFlinger->setFocusedWindow(focusRequest);
3239 }
3240 });
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003241
Arthur Hung6cbb9752019-09-05 16:38:18 +08003242 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003243}
3244
Alec Mouricdf16792021-12-10 13:16:06 -08003245void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3246 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3247 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3248 if (!supportsDisplayBrightnessCommand) {
3249 return;
3250 }
3251
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003252 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003253 if (const auto brightness = display->getStagedBrightness(); brightness) {
3254 if (!needsComposite) {
3255 const status_t error =
3256 getHwComposer()
3257 .setDisplayBrightness(display->getPhysicalId(), *brightness,
3258 Hwc2::Composer::DisplayBrightnessOptions{
3259 .applyImmediately = true})
3260 .get();
3261
3262 ALOGE_IF(error != NO_ERROR,
3263 "Error setting display brightness for display %s: %d (%s)",
3264 display->getDebugName().c_str(), error, strerror(error));
3265 }
3266 display->persistBrightness(needsComposite);
3267 }
3268 }
3269}
3270
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003271void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3272 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003273 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3274
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003275 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003276 const auto layerStack = display->getLayerStack();
3277 const auto info = display->getInputInfo();
3278
3279 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003280 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003281 continue;
3282 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003283
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003284 // If the layer stack is mirrored on multiple displays, the first display that is configured
3285 // to receive input takes precedence.
3286 auto& otherInfo = it->second;
3287 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003288 ALOGW_IF(display->receivesInput(),
3289 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003290 layerStack.id);
3291 } else {
3292 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003293 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003294 }
Robert Carr720e5062018-07-30 17:45:14 -07003295
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003296 static size_t sNumWindowInfos = 0;
3297 outWindowInfos.reserve(sNumWindowInfos);
3298 sNumWindowInfos = 0;
3299
Robert Carr720e5062018-07-30 17:45:14 -07003300 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003301 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003302
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003303 // Do not create WindowInfos for windows on displays that cannot receive input.
3304 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3305 const auto& info = opt->get();
3306 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003307 }
Robert Carr720e5062018-07-30 17:45:14 -07003308 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003309
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003310 sNumWindowInfos = outWindowInfos.size();
3311
3312 outDisplayInfos.reserve(displayInputInfos.size());
3313 for (const auto& [_, info] : displayInputInfos) {
3314 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003315 }
Robert Carr720e5062018-07-30 17:45:14 -07003316}
3317
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003318void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003319 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003320 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003321 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003322 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003323 }
3324 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003325
3326 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003327}
3328
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003329void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003330 // If this is called from the main thread mStateLock must be locked before
3331 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003332 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003333
3334 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003335
3336 const auto display = getDefaultDisplayDeviceLocked();
3337 if (!display || mBootStage != BootStage::FINISHED) {
3338 return;
3339 }
3340 ATRACE_CALL();
3341
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003342 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3343 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003344 return;
3345 }
3346
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003347 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003348}
3349
Ady Abraham62a0be22020-12-08 16:54:10 -08003350void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3351 PhysicalDisplayId displayId = [&]() {
3352 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3353 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3354 }();
3355
3356 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3357}
3358
Ady Abraham3efa3942021-06-24 19:01:25 -07003359void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003360 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003361 // If the scheduler is already initialized, this means that we received
3362 // a hotplug(connected) on the primary display. In that case we should
3363 // update the scheduler with the most recent display information.
3364 ALOGW("Scheduler already initialized, updating instead");
3365 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003366 return;
3367 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003368 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003369 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3370 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003371
Marin Shalamanova903d032020-12-29 20:35:13 +01003372 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003373 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003374
Dominik Laskowski068173d2021-08-11 17:22:59 -07003375 using Feature = scheduler::Feature;
3376 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003377
Dominik Laskowski068173d2021-08-11 17:22:59 -07003378 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3379 features |= Feature::kContentDetection;
3380 }
3381 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3382 features |= Feature::kTracePredictedVsync;
3383 }
3384 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003385 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003386 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003387 }
3388
Dominik Laskowski068173d2021-08-11 17:22:59 -07003389 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3390 static_cast<ISchedulerCallback&>(*this),
3391 features);
3392 {
3393 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003394 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003395 features |= Feature::kKernelIdleTimer;
3396 }
3397
3398 mScheduler->createVsyncSchedule(features);
3399 mScheduler->setRefreshRateConfigs(std::move(configs));
3400 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003401 setVsyncEnabled(false);
3402 mScheduler->startTimers();
3403
Ady Abraham9c53ee72020-07-22 21:16:18 -07003404 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003405 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003406 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003407 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003408 /*workDuration=*/configs.late.appWorkDuration,
3409 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003410 impl::EventThread::InterceptVSyncsCallback());
3411 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003412 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3413 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3414 /*readyDuration=*/configs.late.sfWorkDuration,
3415 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003416 mInterceptor->saveVSyncEvent(timestamp);
3417 });
3418
Dominik Laskowski756b7892021-08-04 12:53:59 -07003419 mScheduler->initVsync(mScheduler->getVsyncDispatch(), *mFrameTimeline->getTokenManager(),
3420 configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003421
3422 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003423 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003424 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003425 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003426 // initialization, so that the EventThreads always contain a reference to a
3427 // prior configuration.
3428 //
3429 // This is a bit hacky, but this avoids a back-pointer into the main SF
3430 // classes from EventThread, and there should be no run-time binder cost
3431 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003432 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003433}
3434
Marin Shalamanov5801c942020-12-17 17:00:13 +01003435void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3436 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003437 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003438 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003439}
3440
Ady Abraham55fa7272020-09-30 19:19:27 -07003441void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3442 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003443 mScheduler->setDuration(mAppConnectionHandle,
3444 /*workDuration=*/config.appWorkDuration,
3445 /*readyDuration=*/config.sfWorkDuration);
3446 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003447 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3448 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003449 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003450}
3451
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003452void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003453 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003454
Lloyd Pique58e24a32019-08-01 15:50:14 -07003455 if (!mLayersPendingRemoval.isEmpty()) {
3456 // Notify removed layers now that they can't be drawn from
3457 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003458 // Ensure any buffers set to display on any children are released.
3459 if (l->isRemovedFromCurrentState()) {
3460 l->latchAndReleaseBuffer();
3461 }
3462
3463 // If the layer has been removed and has no parent, then it will not be reachable
3464 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3465 // ensure we can copy its current to drawing state.
3466 if (!l->getParent()) {
3467 mOffscreenLayers.emplace(l.get());
3468 }
3469 }
3470 mLayersPendingRemoval.clear();
3471 }
3472
3473 // If this transaction is part of a window animation then the next frame
3474 // we composite should be considered an animation as well.
3475 mAnimCompositionPending = mAnimTransactionPending;
3476
3477 mDrawingState = mCurrentState;
3478 // clear the "changed" flags in current state
3479 mCurrentState.colorMatrixChanged = false;
3480
Robert Carra70e91c2021-06-11 13:59:52 -07003481 if (mVisibleRegionsDirty) {
3482 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3483 rootLayer->commitChildList();
3484 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003485 }
Robert Carra70e91c2021-06-11 13:59:52 -07003486
Lloyd Pique58e24a32019-08-01 15:50:14 -07003487 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003488 if (mNumClones > 0) {
3489 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3490 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003491}
3492
chaviw74d90ad2019-04-26 14:45:26 -07003493void SurfaceFlinger::commitOffscreenLayers() {
3494 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003495 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003496 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3497 layer->doTransaction(0);
3498 layer->commitChildList();
3499 }
chaviw74d90ad2019-04-26 14:45:26 -07003500 });
3501 }
3502}
3503
Chia-I Wuab0c3192017-08-01 11:29:00 -07003504void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003505 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003506 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003507 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003508 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003509 }
3510 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003511}
3512
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003513bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003514 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003515
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003516 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517
Mathias Agopian4fec8732012-06-29 14:12:52 -07003518 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003519 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003520 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003521
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003522 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3523
Eric Penner51c59cd2014-07-28 19:51:58 -07003524 // Store the set of layers that need updates. This set must not change as
3525 // buffers are being latched, as this could result in a deadlock.
3526 // Example: Two producers share the same command stream and:
3527 // 1.) Layer 0 is latched
3528 // 2.) Layer 0 gets a new frame
3529 // 2.) Layer 1 gets a new frame
3530 // 3.) Layer 1 is latched.
3531 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3532 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003533 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003534 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3535 const uint32_t flags = layer->doTransaction(0);
3536 if (flags & Layer::eVisibleRegion) {
3537 mVisibleRegionsDirty = true;
3538 }
3539 }
Robert Carrb552ff52021-06-11 13:35:54 -07003540
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003541 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003542 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003543 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003544 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003545 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003546 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003547 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003548 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003549 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003550 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003551 }
Robert Carr2047fae2016-11-28 14:09:09 -08003552 });
Robert Carrb552ff52021-06-11 13:35:54 -07003553 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003554
chaviw49a108c2019-08-12 11:23:06 -07003555 // The client can continue submitting buffers for offscreen layers, but they will not
3556 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3557 // layers to ensure dequeueBuffer doesn't block indefinitely.
3558 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003559 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003560 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3561 }
3562
Lloyd Piquef2c79392018-12-20 16:23:33 -08003563 if (!mLayersWithQueuedFrames.empty()) {
3564 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3565 // writes to Layer current state. See also b/119481871
3566 Mutex::Autolock lock(mStateLock);
3567
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003568 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003569 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003570 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003571 newDataLatched = true;
3572 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003573 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003574 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003575 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003576
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003577 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003578
3579 // If we will need to wake up at some time in the future to deal with a
3580 // queued frame that shouldn't be displayed during this vsync period, wake
3581 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003582 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003583 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003584 }
3585
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003586 // enter boot animation on first buffer latch
3587 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3588 ALOGI("Enter boot animation");
3589 mBootStage = BootStage::BOOTANIMATION;
3590 }
3591
Robert Carr6a0382d2021-07-01 15:57:17 -07003592 if (mNumClones > 0) {
3593 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3594 }
chaviw74b03172019-08-19 11:09:03 -07003595
Dan Stoza6b9454d2014-11-07 16:00:59 -08003596 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003597 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003598}
3599
Robert Carrc0df3122019-04-11 13:18:21 -07003600status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003601 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003602 bool addToRoot, uint32_t* outTransformHint) {
arthurhungdba591c2021-02-08 17:28:49 +08003603 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
3604 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
3605 ISurfaceComposer::MAX_LAYERS);
3606 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003607 }
3608
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003609 {
3610 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3611 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3612 }
arthurhungdba591c2021-02-08 17:28:49 +08003613
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003614 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003615 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003616 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003617 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003618 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003619 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003620 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003621 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003622
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003623 setTransactionFlags(eTransactionNeeded);
3624 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003625}
3626
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003627uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003628 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003629}
3630
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003631uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3632 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003633}
3634
Dominik Laskowski94000c42022-03-17 12:55:14 -07003635void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
3636 const sp<IBinder>& applyToken) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003637 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003638
3639 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
3640 scheduleCommit(FrameHint::kActive);
3641 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642}
3643
Ady Abraham9dada822022-02-03 10:26:59 -08003644bool SurfaceFlinger::stopTransactionProcessing(
3645 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3646 applyTokensWithUnsignaledTransactions) const {
3647 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3648 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3649 // then we should have only one applyToken for processing.
3650 // so we can stop further transactions on this applyToken.
3651 return !applyTokensWithUnsignaledTransactions.empty();
3652 }
3653
3654 return false;
3655}
3656
ramindani9eff2492022-03-23 00:28:26 +00003657int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3658 std::vector<TransactionState>& transactions,
3659 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3660 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3661 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3662 applyTokensWithUnsignaledTransactions,
3663 /*tryApplyUnsignaled*/ true);
3664}
3665
Robert Carr79dc06a2022-02-22 15:28:59 -08003666int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003667 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003668 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003669 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3670 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003671 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003672 auto it = mPendingTransactionQueues.begin();
3673 while (it != mPendingTransactionQueues.end()) {
3674 auto& [applyToken, transactionQueue] = *it;
3675 while (!transactionQueue.empty()) {
3676 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3677 ATRACE_NAME("stopTransactionProcessing");
3678 break;
3679 }
3680
3681 auto& transaction = transactionQueue.front();
3682 const auto ready =
3683 transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3684 transaction.isAutoTimestamp,
3685 transaction.desiredPresentTime,
3686 transaction.originUid, transaction.states,
3687 bufferLayersReadyToPresent, transactions.size(),
3688 tryApplyUnsignaled);
3689 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3690 if (ready == TransactionReadiness::NotReady) {
3691 setTransactionFlags(eTransactionFlushNeeded);
3692 break;
3693 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003694 if (ready == TransactionReadiness::NotReadyBarrier) {
3695 transactionsPendingBarrier++;
3696 setTransactionFlags(eTransactionFlushNeeded);
3697 break;
3698 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003699 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003700 const bool frameNumberChanged = state.bufferData->flags.test(
3701 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003702 if (frameNumberChanged) {
3703 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3704 } else {
3705 // Barrier function only used for BBQ which always includes a frame number
3706 bufferLayersReadyToPresent[state.surface] =
3707 std::numeric_limits<uint64_t>::max();
3708 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003709 });
3710 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3711 if (appliedUnsignaled) {
3712 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3713 }
3714
3715 transactions.emplace_back(std::move(transaction));
3716 transactionQueue.pop();
3717 }
3718
3719 if (transactionQueue.empty()) {
3720 it = mPendingTransactionQueues.erase(it);
3721 mTransactionQueueCV.broadcast();
3722 } else {
3723 it = std::next(it, 1);
3724 }
3725 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003726 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003727}
3728
Vishnu Nair7891e962021-11-11 12:07:21 -08003729bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003730 // to prevent onHandleDestroyed from being called while the lock is held,
3731 // we must keep a copy of the transactions (specifically the composer
3732 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003733 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003734 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003735 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003736 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003737 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003738 Mutex::Autolock _l(mStateLock);
3739 {
3740 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003741
Robert Carr79dc06a2022-02-22 15:28:59 -08003742 int lastTransactionsPendingBarrier = 0;
3743 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003744 // First collect transactions from the pending transaction queues.
3745 // We are not allowing unsignaled buffers here as we want to
3746 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003747 transactionsPendingBarrier =
3748 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3749 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003750
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003751 // Second, collect transactions from the transaction queue.
3752 // Here as well we are not allowing unsignaled buffers for the same
3753 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003754 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003755 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003756 const bool pendingTransactions =
3757 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003758 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003759 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003760 if (pendingTransactions) {
3761 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003762 return TransactionReadiness::NotReady;
3763 }
3764
3765 return transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3766 transaction.isAutoTimestamp,
3767 transaction.desiredPresentTime,
3768 transaction.originUid, transaction.states,
3769 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003770 transactions.size(),
3771 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003772 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003773 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003774 if (ready != TransactionReadiness::Ready) {
3775 if (ready == TransactionReadiness::NotReadyBarrier) {
3776 transactionsPendingBarrier++;
3777 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003778 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003779 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003780 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003781 const bool frameNumberChanged = state.bufferData->flags.test(
3782 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003783 if (frameNumberChanged) {
3784 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3785 } else {
3786 // Barrier function only used for BBQ which always includes a frame number.
3787 // This value only used for barrier logic.
3788 bufferLayersReadyToPresent[state.surface] =
3789 std::numeric_limits<uint64_t>::max();
3790 }
Xiang Wang76236e12022-03-22 17:25:30 +00003791 });
Ady Abraham9dada822022-02-03 10:26:59 -08003792 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003793 }
ramindani4d48f902021-09-20 21:07:45 +00003794 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003795 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003796 }
Arthur Hung58144272021-01-16 03:43:53 +00003797
Robert Carr79dc06a2022-02-22 15:28:59 -08003798 // Transactions with a buffer pending on a barrier may be on a different applyToken
3799 // than the transaction which satisfies our barrier. In fact this is the exact use case
3800 // that the primitive is designed for. This means we may first process
3801 // the barrier dependent transaction, determine it ineligible to complete
3802 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3803 // The barrier dependent transaction was eligible to be presented in this frame
3804 // but we would have prevented it without case. To fix this we continually
3805 // loop through flushPendingTransactionQueues until we perform an iteration
3806 // where the number of transactionsPendingBarrier doesn't change. This way
3807 // we can continue to resolve dependency chains of barriers as far as possible.
3808 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3809 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3810 transactionsPendingBarrier =
3811 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3812 applyTokensWithUnsignaledTransactions,
3813 /*tryApplyUnsignaled*/ false);
3814 }
3815
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003816 // We collected all transactions that could apply without latching unsignaled buffers.
3817 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3818 // transactions that were not applied and try to apply them unsignaled.
3819 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003820 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3821 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003822 }
3823
Vishnu Nair7891e962021-11-11 12:07:21 -08003824 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003825 }
ramindani4d48f902021-09-20 21:07:45 +00003826 }
3827}
3828
Vishnu Nair7891e962021-11-11 12:07:21 -08003829bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3830 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003831 bool needsTraversal = false;
3832 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003833 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003834 needsTraversal |=
3835 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3836 transaction.displays, transaction.flags,
3837 transaction.inputWindowCommands,
3838 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3839 transaction.buffer, transaction.postTime,
3840 transaction.permissions, transaction.hasListenerCallbacks,
3841 transaction.listenerCallbacks, transaction.originPid,
3842 transaction.originUid, transaction.id);
3843 if (transaction.transactionCommittedSignal) {
3844 mTransactionCommittedSignals.emplace_back(
3845 std::move(transaction.transactionCommittedSignal));
3846 }
3847 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003848
Dominik Laskowski46471e62022-01-14 15:34:03 -08003849 if (mTransactionTracing) {
3850 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003851 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003852 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003853}
3854
3855bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003856 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003857 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003858}
3859
Ady Abraham8db10102021-03-15 17:19:23 -07003860bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3861 // The amount of time SF can delay a frame if it is considered early based
3862 // on the VsyncModulator::VsyncConfig::appWorkDuration
3863 constexpr static std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3864
3865 const auto currentVsyncPeriod = mScheduler->getDisplayStatInfo(systemTime()).vsyncPeriod;
3866 const auto earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
3867
3868 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3869 if (!prediction.has_value()) {
3870 return false;
3871 }
3872
3873 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3874 kEarlyLatchMaxThreshold.count()) {
3875 return false;
3876 }
3877
3878 return prediction->presentTime >= expectedPresentTime &&
3879 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3880}
Ady Abraham9dada822022-02-03 10:26:59 -08003881bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003882 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003883 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3884 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3885 return false;
3886 }
Ady Abraham8db10102021-03-15 17:19:23 -07003887
Ady Abraham9dada822022-02-03 10:26:59 -08003888 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3889 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3890 return true;
3891 }
3892
3893 // We only want to latch unsignaled when a single layer is updated in this
3894 // transaction (i.e. not a blast sync transaction).
3895 if (numStates != 1) {
3896 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3897 return false;
3898 }
3899
Ady Abraham2739e832022-02-14 17:42:00 -08003900 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3901 if (totalTXapplied > 0) {
3902 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3903 __func__, totalTXapplied);
3904 return false;
3905 }
3906
3907 // We don't want to latch unsignaled if are in early / client composition
3908 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3909 // or window animations being slow.
3910 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3911 if (!isDefaultVsyncConfig) {
3912 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3913 __func__);
3914 return false;
3915 }
Ady Abraham9dada822022-02-03 10:26:59 -08003916 }
3917
3918 if (!layer->simpleBufferUpdate(state)) {
3919 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3920 return false;
3921 }
3922
3923 ALOGV("%s: true", __func__);
3924 return true;
3925}
3926
3927auto SurfaceFlinger::transactionIsReadyToBeApplied(
Ady Abraham43752eb2021-03-04 16:24:25 -08003928 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003929 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003930 const std::unordered_map<
3931 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003932 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003933 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003934 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003935 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3936 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003937 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08003938 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003939 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003940 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003941 }
3942
Ady Abraham5690bda2021-03-12 15:01:18 -08003943 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
3944 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003945 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003946 }
3947
Ady Abraham8db10102021-03-15 17:19:23 -07003948 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3949 // present time of this transaction.
3950 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
3951 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08003952 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07003953 }
3954
Ady Abraham9dada822022-02-03 10:26:59 -08003955 bool fenceUnsignaled = false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003956 for (const ComposerState& state : states) {
3957 const layer_state_t& s = state.state;
Ady Abrahamf20c1922020-12-21 18:39:01 -08003958 sp<Layer> layer = nullptr;
3959 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07003960 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003961 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08003962 ALOGW("Transaction with buffer, but no Layer?");
3963 continue;
3964 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003965 if (!layer) {
3966 continue;
3967 }
Ady Abraham43752eb2021-03-04 16:24:25 -08003968
Robert Carr79dc06a2022-02-22 15:28:59 -08003969 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
3970 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
3971 const bool willApplyBarrierFrame =
3972 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
3973 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
3974 if (!willApplyBarrierFrame) {
3975 ATRACE_NAME("NotReadyBarrier");
3976 return TransactionReadiness::NotReadyBarrier;
3977 }
3978 }
3979
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003980 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08003981 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08003982 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
3983 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08003984
3985 const bool acquireFenceChanged = s.bufferData &&
3986 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
3987 s.bufferData->acquireFence;
3988 fenceUnsignaled = fenceUnsignaled ||
3989 (acquireFenceChanged &&
3990 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
3991
3992 if (fenceUnsignaled && !allowLatchUnsignaled) {
3993 ATRACE_NAME("fence unsignaled");
3994 return TransactionReadiness::NotReady;
3995 }
3996
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003997 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08003998 // If backpressure is enabled and we already have a buffer to commit, keep the
3999 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08004000 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
4001 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08004002 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08004003 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08004004 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004005 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004006 }
4007 }
Ady Abraham9dada822022-02-03 10:26:59 -08004008 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004009}
4010
arthurhungf1b7c7b2021-03-03 17:42:23 +08004011void SurfaceFlinger::queueTransaction(TransactionState& state) {
Ady Abrahame46243a2021-02-23 19:33:49 -08004012 Mutex::Autolock _l(mQueueLock);
4013
arthurhungf1b7c7b2021-03-03 17:42:23 +08004014 // Generate a CountDownLatch pending state if this is a synchronous transaction.
4015 if ((state.flags & eSynchronous) || state.inputWindowCommands.syncInputWindows) {
4016 state.transactionCommittedSignal = std::make_shared<CountDownLatch>(
Arthur Hung2274a312021-04-28 15:13:06 +00004017 (state.inputWindowCommands.syncInputWindows
4018 ? (CountDownLatch::eSyncInputWindows | CountDownLatch::eSyncTransaction)
4019 : CountDownLatch::eSyncTransaction));
arthurhungf1b7c7b2021-03-03 17:42:23 +08004020 }
4021
ramindani4d48f902021-09-20 21:07:45 +00004022 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004023 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4024
Ady Abrahame46243a2021-02-23 19:33:49 -08004025 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004026 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4027 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004028 return TransactionSchedule::Late;
4029 }(state.flags);
4030
Ady Abraham23ea9da2021-07-14 16:32:56 -07004031 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken);
Ady Abrahame46243a2021-02-23 19:33:49 -08004032}
4033
arthurhungf1b7c7b2021-03-03 17:42:23 +08004034void SurfaceFlinger::waitForSynchronousTransaction(
4035 const CountDownLatch& transactionCommittedSignal) {
4036 // applyTransactionState is called on the main SF thread. While a given process may wish
4037 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4038 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004039 if (!transactionCommittedSignal.wait_until(
4040 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004041 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004042 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004043}
Ady Abrahame46243a2021-02-23 19:33:49 -08004044
Arthur Hung2274a312021-04-28 15:13:06 +00004045void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004046 for (auto it = mTransactionCommittedSignals.begin();
4047 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004048 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004049 it = mTransactionCommittedSignals.erase(it);
4050 } else {
4051 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004052 }
4053 }
4054}
4055
chaviw308ddba2020-08-11 16:23:51 -07004056status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004057 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004058 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4059 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004060 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004061 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004062 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004063
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004064 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004065 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4066 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004067 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4068 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004069 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004070 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004071 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004072 }
4073
Leon Scroggins9a20f722021-12-28 14:43:12 +00004074 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004075 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004076 }
4077
Robert Carrde6d7b42022-01-07 18:23:06 -08004078 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004079 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4080 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4081 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004082 }
4083
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004084 const int64_t postTime = systemTime();
4085
4086 IPCThreadState* ipc = IPCThreadState::self();
4087 const int originPid = ipc->getCallingPid();
4088 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004089 TransactionState state{frameTimelineInfo, states,
4090 displays, flags,
4091 applyToken, inputWindowCommands,
4092 desiredPresentTime, isAutoTimestamp,
4093 uncacheBuffer, postTime,
4094 permissions, hasListenerCallbacks,
4095 listenerCallbacks, originPid,
4096 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004097
4098 // Check for incoming buffer updates and increment the pending buffer count.
4099 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4100 mBufferCountTracker.increment(state.surface->localBinder());
4101 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004102
Dominik Laskowski46471e62022-01-14 15:34:03 -08004103 if (mTransactionTracing) {
4104 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004105 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004106 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004107
arthurhungf1b7c7b2021-03-03 17:42:23 +08004108 // Check the pending state to make sure the transaction is synchronous.
4109 if (state.transactionCommittedSignal) {
4110 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004111 }
4112
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004113 return NO_ERROR;
4114}
Marissa Wall713b63f2018-10-17 15:42:43 -07004115
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004116bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004117 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004118 const Vector<DisplayState>& displays, uint32_t flags,
4119 const InputWindowCommands& inputWindowCommands,
4120 const int64_t desiredPresentTime, bool isAutoTimestamp,
4121 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004122 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004123 bool hasListenerCallbacks,
4124 const std::vector<ListenerCallbacks>& listenerCallbacks,
4125 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004126 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004127 for (const DisplayState& display : displays) {
4128 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004129 }
4130
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004131 // start and end registration for listeners w/ no surface so they can get their callback. Note
4132 // that listeners with SurfaceControls will start registration during setClientStateLocked
4133 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004134 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004135 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004136 }
4137
Marissa Walle2ffb422018-10-12 11:33:52 -07004138 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004139 for (int i = 0; i < states.size(); i++) {
4140 ComposerState& state = states.editItemAt(i);
4141 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004142 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004143 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004144 if (const auto layer = fromHandle(state.state.surface).promote()) {
4145 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004146 mScheduler->recordLayerHistory(layer.get(),
4147 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004148 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004149 }
4150 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004151 }
4152
Marissa Walle2ffb422018-10-12 11:33:52 -07004153 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004154
Robert Carrde6d7b42022-01-07 18:23:06 -08004155 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004156 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4157 } else if (!inputWindowCommands.empty()) {
4158 ALOGE("Only privileged callers are allowed to send input commands.");
4159 }
chaviw273171b2018-12-26 11:46:30 -08004160
Marissa Wall947d34e2019-03-29 14:03:53 -07004161 if (uncacheBuffer.isValid()) {
4162 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004163 }
4164
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004165 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4166 // anyway. This can be used as a flush mechanism for previous async transactions.
4167 // Empty animation transaction can be used to simulate back-pressure, so also force a
4168 // transaction for empty animation transactions.
4169 if (transactionFlags == 0 &&
4170 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004171 transactionFlags = eTransactionNeeded;
4172 }
4173
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004174 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004175 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004176 if (mInterceptor->isEnabled()) {
4177 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004178 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004179 }
4180
Arthur Hung58144272021-01-16 03:43:53 +00004181 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4182 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4183 if (transactionFlags & eTraversalNeeded) {
4184 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004185 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004186 }
Arthur Hung58144272021-01-16 03:43:53 +00004187 if (transactionFlags) {
4188 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004189 }
4190
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004191 if (flags & eAnimation) {
4192 mAnimTransactionPending = true;
4193 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004194 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004195
4196 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004197}
4198
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004199uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4200 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4201 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004202
Mathias Agopiane57f2922012-08-09 16:29:12 -07004203 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004204 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4205
4206 const uint32_t what = s.what;
4207 if (what & DisplayState::eSurfaceChanged) {
4208 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4209 state.surface = s.surface;
4210 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004211 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004212 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004213 if (what & DisplayState::eLayerStackChanged) {
4214 if (state.layerStack != s.layerStack) {
4215 state.layerStack = s.layerStack;
4216 flags |= eDisplayTransactionNeeded;
4217 }
4218 }
Evan Rosky2239b372021-05-20 13:43:47 -07004219 if (what & DisplayState::eFlagsChanged) {
4220 if (state.flags != s.flags) {
4221 state.flags = s.flags;
4222 flags |= eDisplayTransactionNeeded;
4223 }
4224 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004225 if (what & DisplayState::eDisplayProjectionChanged) {
4226 if (state.orientation != s.orientation) {
4227 state.orientation = s.orientation;
4228 flags |= eDisplayTransactionNeeded;
4229 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004230 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4231 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004232 flags |= eDisplayTransactionNeeded;
4233 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004234 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4235 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004236 flags |= eDisplayTransactionNeeded;
4237 }
4238 }
4239 if (what & DisplayState::eDisplaySizeChanged) {
4240 if (state.width != s.width) {
4241 state.width = s.width;
4242 flags |= eDisplayTransactionNeeded;
4243 }
4244 if (state.height != s.height) {
4245 state.height = s.height;
4246 flags |= eDisplayTransactionNeeded;
4247 }
4248 }
4249
Mathias Agopiane57f2922012-08-09 16:29:12 -07004250 return flags;
4251}
4252
Steven Thomasd4071902020-03-24 16:02:53 -07004253bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004254 IPCThreadState* ipc = IPCThreadState::self();
4255 const int pid = ipc->getCallingPid();
4256 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004257 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004258 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4259 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004260 return false;
4261 }
4262 return true;
4263}
4264
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004265uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004266 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004267 int64_t desiredPresentTime, bool isAutoTimestamp,
4268 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004269 layer_state_t& s = composerState.state;
4270 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004271
4272 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004273 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004274 // Starts a registration but separates the callback ids according to callback type. This
4275 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004276 // note that startRegistration will not re-register if the listener has
4277 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004278
4279 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4280 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004281 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004282 }
4283
4284 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4285 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004286 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004287 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004288 }
4289
arthurhungdba591c2021-02-08 17:28:49 +08004290 const uint64_t what = s.what;
4291 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004292 sp<Layer> layer = nullptr;
4293 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004294 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004295 } else {
4296 // The client may provide us a null handle. Treat it as if the layer was removed.
4297 ALOGW("Attempt to set client state with a null layer handle");
4298 }
chaviw8b3871a2017-11-01 17:41:01 -07004299 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004300 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004301 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004302 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004303 }
chaviw8b3871a2017-11-01 17:41:01 -07004304 return 0;
4305 }
4306
Valerie Hau871d6352020-01-29 08:44:02 -08004307 // Only set by BLAST adapter layers
4308 if (what & layer_state_t::eProducerDisconnect) {
4309 layer->onDisconnect();
4310 }
4311
chaviw8b3871a2017-11-01 17:41:01 -07004312 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004313 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004314 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004315 }
chaviw8b3871a2017-11-01 17:41:01 -07004316 }
4317 if (what & layer_state_t::eLayerChanged) {
4318 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004319 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004320 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004321 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004322 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004323 mCurrentState.layersSortedByZ.removeAt(idx);
4324 mCurrentState.layersSortedByZ.add(layer);
4325 // we need traversal (state changed)
4326 // AND transaction (list changed)
4327 flags |= eTransactionNeeded|eTraversalNeeded;
4328 }
chaviw8b3871a2017-11-01 17:41:01 -07004329 } else {
4330 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004331 flags |= eTransactionNeeded|eTraversalNeeded;
4332 }
4333 }
chaviw8b3871a2017-11-01 17:41:01 -07004334 }
4335 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004336 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004337 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004338 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4339 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004340 if (p == nullptr) {
4341 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004342 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004343 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004344 mCurrentState.layersSortedByZ.removeAt(idx);
4345 mCurrentState.layersSortedByZ.add(layer);
4346 // we need traversal (state changed)
4347 // AND transaction (list changed)
4348 flags |= eTransactionNeeded|eTraversalNeeded;
4349 }
4350 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004351 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004352 flags |= eTransactionNeeded|eTraversalNeeded;
4353 }
chaviw8b3871a2017-11-01 17:41:01 -07004354 }
4355 }
4356 if (what & layer_state_t::eSizeChanged) {
4357 if (layer->setSize(s.w, s.h)) {
4358 flags |= eTraversalNeeded;
4359 }
4360 }
4361 if (what & layer_state_t::eAlphaChanged) {
4362 if (layer->setAlpha(s.alpha))
4363 flags |= eTraversalNeeded;
4364 }
4365 if (what & layer_state_t::eColorChanged) {
4366 if (layer->setColor(s.color))
4367 flags |= eTraversalNeeded;
4368 }
Peiyong Lind3788632018-09-18 16:01:31 -07004369 if (what & layer_state_t::eColorTransformChanged) {
4370 if (layer->setColorTransform(s.colorTransform)) {
4371 flags |= eTraversalNeeded;
4372 }
4373 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004374 if (what & layer_state_t::eBackgroundColorChanged) {
4375 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4376 flags |= eTraversalNeeded;
4377 }
4378 }
chaviw8b3871a2017-11-01 17:41:01 -07004379 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004380 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004381 }
4382 if (what & layer_state_t::eTransparentRegionChanged) {
4383 if (layer->setTransparentRegionHint(s.transparentRegion))
4384 flags |= eTraversalNeeded;
4385 }
4386 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004387 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004388 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004389 if (what & layer_state_t::eCornerRadiusChanged) {
4390 if (layer->setCornerRadius(s.cornerRadius))
4391 flags |= eTraversalNeeded;
4392 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004393 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004394 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4395 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004396 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004397 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4398 }
chaviw8b3871a2017-11-01 17:41:01 -07004399 if (what & layer_state_t::eLayerStackChanged) {
4400 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4401 // We only allow setting layer stacks for top level layers,
4402 // everything else inherits layer stack from its parent.
4403 if (layer->hasParent()) {
4404 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004405 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004406 } else if (idx < 0) {
4407 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004408 "that also does not appear in the top level layer list. Something"
4409 " has gone wrong.",
4410 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004411 } else if (layer->setLayerStack(s.layerStack)) {
4412 mCurrentState.layersSortedByZ.removeAt(idx);
4413 mCurrentState.layersSortedByZ.add(layer);
4414 // we need traversal (state changed)
4415 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004416 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004417 }
4418 }
Marissa Wall61c58622018-07-18 10:12:20 -07004419 if (what & layer_state_t::eTransformChanged) {
4420 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4421 }
4422 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4423 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4424 flags |= eTraversalNeeded;
4425 }
4426 if (what & layer_state_t::eCropChanged) {
4427 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4428 }
Marissa Wall61c58622018-07-18 10:12:20 -07004429 if (what & layer_state_t::eDataspaceChanged) {
4430 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4431 }
4432 if (what & layer_state_t::eHdrMetadataChanged) {
4433 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4434 }
4435 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4436 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4437 }
4438 if (what & layer_state_t::eApiChanged) {
4439 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4440 }
4441 if (what & layer_state_t::eSidebandStreamChanged) {
4442 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4443 }
Robert Carr720e5062018-07-30 17:45:14 -07004444 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004445 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4446 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004447 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004448 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004449 if (what & layer_state_t::eMetadataChanged) {
Vishnu Nairadf632b2021-01-07 14:05:08 -08004450 dequeueBufferTimestamp = s.metadata.getInt64(METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004451
4452 if (const int32_t gameMode = s.metadata.getInt32(METADATA_GAME_MODE, -1); gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004453 // The transaction will be received on the Task layer and needs to be applied to all
4454 // child layers. Child layers that are added at a later point will obtain the game mode
4455 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004456 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004457 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004458
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004459 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4460 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004461 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4462 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4463 flags |= eTraversalNeeded;
4464 }
4465 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004466 if (what & layer_state_t::eShadowRadiusChanged) {
4467 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4468 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004469 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004470 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004471 flags |= eTraversalNeeded;
4472 }
4473 }
Steven Thomas3172e202020-01-06 19:25:30 -08004474 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004475 const auto compatibility =
4476 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4477 const auto strategy =
4478 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004479
Robert Carrde6d7b42022-01-07 18:23:06 -08004480 if (layer->setFrameRate(
4481 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4482 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004483 }
Steven Thomas3172e202020-01-06 19:25:30 -08004484 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004485 if (what & layer_state_t::eFixedTransformHintChanged) {
4486 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4487 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4488 }
4489 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004490 if (what & layer_state_t::eAutoRefreshChanged) {
4491 layer->setAutoRefresh(s.autoRefresh);
4492 }
Sally Qi421ffb02022-03-21 19:41:33 -07004493 if (what & layer_state_t::eDimmingEnabledChanged) {
4494 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4495 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004496 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004497 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4498 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004499 }
4500 }
John Reckcdb4ed72021-02-04 13:39:33 -05004501 if (what & layer_state_t::eStretchChanged) {
4502 if (layer->setStretchEffect(s.stretchEffect)) {
4503 flags |= eTraversalNeeded;
4504 }
4505 }
chaviwf3f40fe2021-04-27 15:54:02 -05004506 if (what & layer_state_t::eBufferCropChanged) {
4507 if (layer->setBufferCrop(s.bufferCrop)) {
4508 flags |= eTraversalNeeded;
4509 }
4510 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004511 if (what & layer_state_t::eDestinationFrameChanged) {
4512 if (layer->setDestinationFrame(s.destinationFrame)) {
4513 flags |= eTraversalNeeded;
4514 }
4515 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004516 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004517 if (layer->setDropInputMode(s.dropInputMode)) {
4518 flags |= eTraversalNeeded;
4519 mInputInfoChanged = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004520 }
4521 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004522 // This has to happen after we reparent children because when we reparent to null we remove
4523 // child layers from current state and remove its relative z. If the children are reparented in
4524 // the same transaction, then we have to make sure we reparent the children first so we do not
4525 // lose its relative z order.
4526 if (what & layer_state_t::eReparent) {
4527 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004528 auto parentHandle = (s.parentSurfaceControlForChild)
4529 ? s.parentSurfaceControlForChild->getHandle()
4530 : nullptr;
4531 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004532 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004533 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004534 mCurrentState.layersSortedByZ.remove(layer);
4535 }
4536 flags |= eTransactionNeeded | eTraversalNeeded;
4537 }
4538 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004539 std::vector<sp<CallbackHandle>> callbackHandles;
4540 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4541 for (auto& [listener, callbackIds] : filteredListeners) {
4542 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4543 }
4544 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004545
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004546 if (what & layer_state_t::eBufferChanged) {
4547 std::shared_ptr<renderengine::ExternalTexture> buffer =
4548 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4549 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4550 dequeueBufferTimestamp, frameTimelineInfo)) {
4551 flags |= eTraversalNeeded;
4552 }
Ady Abraham8db10102021-03-15 17:19:23 -07004553 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4554 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004555 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004556
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004557 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004558 // Do not put anything that updates layer state or modifies flags after
4559 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004560 return flags;
4561}
4562
chaviw273171b2018-12-26 11:46:30 -08004563uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004564 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004565 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004566}
4567
Vishnu Nair84125ac2021-12-02 08:47:48 -08004568status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4569 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4570 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004571 if (!mirrorFromHandle) {
4572 return NAME_NOT_FOUND;
4573 }
4574
4575 sp<Layer> mirrorLayer;
4576 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004577 {
4578 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004579 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004580 if (!mirrorFrom) {
4581 return NAME_NOT_FOUND;
4582 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004583 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004584 if (result != NO_ERROR) {
4585 return result;
4586 }
4587
Robert Carr6a0382d2021-07-01 15:57:17 -07004588 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004589 }
4590
Ady Abraham9f0a4002020-10-05 15:47:26 -07004591 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004592 if (mTransactionTracing) {
4593 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4594 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004595 }
4596 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004597 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004598}
4599
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004600status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004601 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4602 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004603 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4604 "Expected only one of parentLayer or parentHandle to be non-null. "
4605 "Programmer error?");
4606
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004607 status_t result = NO_ERROR;
4608
4609 sp<Layer> layer;
4610
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004611 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004612 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004613 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004614 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004615 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4616 if (pendingBufferCounter) {
4617 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004618 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004619 pendingBufferCounter);
4620 }
4621 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004622 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004623 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004624 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004625 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004626 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004627 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004628 default:
4629 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004630 break;
4631 }
4632
Dan Stoza7d89d062015-04-30 13:29:25 -07004633 if (result != NO_ERROR) {
4634 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004635 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004636
Vishnu Nair858a3b42022-01-12 20:42:28 -08004637 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004638 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4639 if (parentHandle != nullptr && parent == nullptr) {
4640 ALOGE("Invalid parent handle %p.", parentHandle.get());
4641 addToRoot = false;
4642 }
4643 if (parentLayer != nullptr) {
4644 addToRoot = false;
4645 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004646
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004647 int parentId = -1;
4648 // We can safely promote the layer in binder thread because we have a strong reference
4649 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4650 sp<Layer> parentSp = parent.promote();
4651 if (parentSp != nullptr) {
4652 parentId = parentSp->getSequence();
4653 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004654 if (mTransactionTracing) {
4655 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4656 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004657 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004658
Vishnu Nair047fb332021-12-09 09:54:36 -08004659 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4660 if (result != NO_ERROR) {
4661 return result;
4662 }
4663
Ady Abraham9f0a4002020-10-05 15:47:26 -07004664 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004665 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004666}
4667
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004668status_t SurfaceFlinger::createBufferQueueLayer(LayerCreationArgs& args, PixelFormat& format,
Evan Roskya1f1e152019-01-24 16:17:46 -08004669 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004670 sp<IGraphicBufferProducer>* gbp,
4671 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004672 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004673 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004674 case PIXEL_FORMAT_TRANSPARENT:
4675 case PIXEL_FORMAT_TRANSLUCENT:
4676 format = PIXEL_FORMAT_RGBA_8888;
4677 break;
4678 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004679 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004680 break;
4681 }
4682
chaviwb4c6e582019-08-16 14:35:07 -07004683 sp<BufferQueueLayer> layer;
chaviwb4c6e582019-08-16 14:35:07 -07004684 args.textureName = getNewTexture();
4685 {
4686 // Grab the SF state lock during this since it's the only safe way to access
4687 // RenderEngine when creating a BufferLayerConsumer
4688 // TODO: Check if this lock is still needed here
4689 Mutex::Autolock lock(mStateLock);
4690 layer = getFactory().createBufferQueueLayer(args);
4691 }
4692
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004693 status_t err = layer->setDefaultBufferProperties(0, 0, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004694 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004695 *handle = layer->getHandle();
4696 *gbp = layer->getProducer();
4697 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004698 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004699
Marissa Wallfd668622018-05-10 10:21:13 -07004700 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004701 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004702}
4703
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004704status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004705 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004706 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004707 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004708 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004709 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004710}
4711
Vishnu Nair84125ac2021-12-02 08:47:48 -08004712status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004713 sp<Layer>* outLayer) {
4714 *outLayer = getFactory().createEffectLayer(args);
4715 *handle = (*outLayer)->getHandle();
4716 return NO_ERROR;
4717}
4718
Vishnu Nair84125ac2021-12-02 08:47:48 -08004719status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004720 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004721 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004722 *handle = (*outLayer)->getHandle();
4723 return NO_ERROR;
4724}
4725
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004726void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004727 mLayersPendingRemoval.add(layer);
4728 mLayersRemoved = true;
4729 setTransactionFlags(eTransactionNeeded);
4730}
4731
Vishnu Nairf9096652021-07-20 18:49:42 -07004732void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004733 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004734 // If a layer has a parent, we allow it to out-live it's handle
4735 // with the idea that the parent holds a reference and will eventually
4736 // be cleaned up. However no one cleans up the top-level so we do so
4737 // here.
Vishnu Nair14d218b2021-07-13 13:57:39 -07004738 if (layer->isAtRoot()) {
4739 layer->setIsAtRoot(false);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004740 mCurrentState.layersSortedByZ.remove(layer);
4741 }
4742 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004743 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004744 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004745 if (mTransactionTracing) {
4746 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004747 }
Rob Carr4bba3702018-10-08 21:53:30 +00004748}
4749
Mathias Agopianb60314a2012-04-10 22:09:54 -07004750// ---------------------------------------------------------------------------
4751
Andy McFadden13a082e2012-08-24 10:16:42 -07004752void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004753 const auto display = getDefaultDisplayDeviceLocked();
4754 if (!display) return;
4755
4756 const sp<IBinder> token = display->getDisplayToken().promote();
4757 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004758
Jesse Hall01e29052013-02-19 16:13:35 -08004759 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004760 Vector<ComposerState> state;
4761 Vector<DisplayState> displays;
4762 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004763 d.what = DisplayState::eDisplayProjectionChanged |
4764 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004765 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004766 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004767 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004768 d.orientedDisplaySpaceRect.makeInvalid();
4769 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004770 d.width = 0;
4771 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004772 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004773
Vishnu Nair9a69a042021-06-18 13:19:49 -07004774 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004775
4776 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004777 // It should be on the main thread, apply it directly.
4778 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004779 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004780 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004781
Peiyong Lin65248e02020-04-18 21:15:07 -07004782 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004783 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004784 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004785 mActiveDisplayTransformHint = display->getTransformHint();
Brian Andersond0010582017-03-07 13:20:31 -08004786 // Use phase of 0 since phase is not known.
4787 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004788 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004789 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004790}
4791
4792void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004793 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004794 static_cast<void>(
4795 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004796}
4797
Peiyong Lin65248e02020-04-18 21:15:07 -07004798void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004799 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004800 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004801 return;
4802 }
4803
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004804 const auto displayId = display->getPhysicalId();
4805 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004806
Peiyong Lin65248e02020-04-18 21:15:07 -07004807 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004808 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004809 return;
4810 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004811
Ady Abraham4f960d12021-10-13 16:59:49 -07004812 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4813 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4814 activeDisplay->isPoweredOn()) {
4815 ALOGW("Trying to change power mode on non active display while the active display is ON");
4816 }
4817
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004818 display->setPowerMode(mode);
4819
Lloyd Pique4dccc412018-01-22 17:21:36 -08004820 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004821 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004822 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004823 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004824 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004825 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004826 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004827 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004828 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004829 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4830 // We can merge the syscall later.
4831 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4832 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4833 }
Martin Liu4a322352020-03-24 21:30:38 +08004834 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4835 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4836 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004837 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004838 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004839 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004840 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004841 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004842 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004843
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004844 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004845 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004846 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004847 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004848 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004849 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4850 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004851 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004852 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4853 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4854 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004855 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004856 mScheduler->disableHardwareVsync(true);
4857 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004858 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004859
Ady Abraham27c70212019-06-11 10:52:26 -07004860 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004861 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004862
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004863 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004864 mVisibleRegionsDirty = true;
4865 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004866 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004867 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004868 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004869 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004870 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004871 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004872 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004873 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004874 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004875 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004876 mScheduler->disableHardwareVsync(true);
4877 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004878 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004879 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004880 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004881 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004882 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004883 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004884
Ady Abrahamadc914c2021-10-13 17:04:27 -07004885 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004886 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004887 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004888 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004889 }
4890
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004891 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004892}
4893
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004894void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004895 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004896 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004897 if (!display) {
4898 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4899 displayToken.get());
4900 } else if (display->isVirtual()) {
4901 ALOGW("Attempt to set power mode %d for virtual display", mode);
4902 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004903 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004904 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004905 });
4906
4907 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004908}
4909
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004910status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004911 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004912
Mathias Agopianbd115332013-04-18 16:41:04 -07004913 IPCThreadState* ipc = IPCThreadState::self();
4914 const int pid = ipc->getCallingPid();
4915 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004916
Mathias Agopianbd115332013-04-18 16:41:04 -07004917 if ((uid != AID_SHELL) &&
4918 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004919 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4920 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004921 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004922 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004923 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004924 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004925 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004926 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4927 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4928 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4929 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004930 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004931 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4932 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004933 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004934 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004935 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004936 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004937
Dominik Laskowskic2867142019-01-21 11:33:38 -08004938 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004939
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004940 bool dumpLayers = true;
4941 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004942 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004943 if (!lock.locked()) {
4944 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4945 strerror(-lock.status), lock.status);
4946 }
4947
4948 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4949 (it->second)(args, asProto, result);
4950 dumpLayers = false;
4951 } else if (!asProto) {
4952 dumpAllLocked(args, result);
4953 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004954 }
4955
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004956 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004957 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05004958 LayersTraceProto* layersTrace = traceFileProto.add_entry();
4959 LayersProto layersProto = dumpProtoFromMainThread();
4960 layersTrace->mutable_layers()->Swap(&layersProto);
4961 dumpDisplayProto(*layersTrace);
4962
Dominik Laskowski46470112019-08-02 13:13:11 -07004963 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05004964 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07004965 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004966 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05004967 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07004968 result.append(LayerProtoParser::layerTreeToString(layerTree));
4969 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004970 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004971 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004972 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004973 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004974 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004975 return NO_ERROR;
4976}
4977
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004978status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08004979 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004980 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004981 if (mTransactionTracing) {
4982 mTransactionTracing->writeToFile();
4983 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004984 }
4985
4986 return doDump(fd, DumpArgs(), asProto);
4987}
4988
Dominik Laskowskic2867142019-01-21 11:33:38 -08004989void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004990 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004991 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004992}
4993
Dominik Laskowskic2867142019-01-21 11:33:38 -08004994void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07004995 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004996
Dominik Laskowskic2867142019-01-21 11:33:38 -08004997 if (args.size() > 1) {
4998 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004999 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005000 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005001 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005002 }
Robert Carr2047fae2016-11-28 14:09:09 -08005003 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005004 } else {
5005 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005006 }
5007}
5008
Dominik Laskowskic2867142019-01-21 11:33:38 -08005009void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005010 const bool clearAll = args.size() < 2;
5011 const auto name = clearAll ? String8() : String8(args[1]);
5012
Edgar Arriaga844fa672020-01-16 14:21:42 -08005013 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005014 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005015 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005016 }
Robert Carr2047fae2016-11-28 14:09:09 -08005017 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005018
Svetoslavd85084b2014-03-20 10:28:31 -07005019 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005020}
5021
Dominik Laskowskic2867142019-01-21 11:33:38 -08005022void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5023 mTimeStats->parseArgs(asProto, args, result);
5024}
5025
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005026void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5027 mFrameTimeline->parseArgs(args, result);
5028}
5029
Jamie Gennis6547ff42013-07-16 20:12:42 -07005030void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005031 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005032 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005033 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005034
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005035 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005036}
5037
Yiwei Zhang5434a782018-12-05 18:06:32 -08005038void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005039 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005040
Yiwei Zhang5434a782018-12-05 18:06:32 -08005041 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5042 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005043 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5044 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005045 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5046 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5047 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005048 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005049}
5050
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005051void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005052 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005053
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005054 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005055 result.append("\n");
5056
Ady Abraham8287e852020-08-12 14:44:58 -07005057 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005058 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005059 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005060 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005061
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005062 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5063 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005064
Ana Krulecc2870422019-01-29 19:00:58 -08005065 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005066 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005067 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5068 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005069}
5070
Dan Stoza269dc4d2021-01-15 15:07:43 -08005071void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5072 for (const auto& [token, display] : mDisplays) {
5073 const auto compositionDisplay = display->getCompositionDisplay();
5074 compositionDisplay->dumpPlannerInfo(args, result);
5075 }
5076}
5077
Yiwei Zhang5434a782018-12-05 18:06:32 -08005078void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5079 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005080 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5081 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005082 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005083 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005084 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005085 }
David Sodman4a36e932017-11-07 14:29:47 -08005086 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005087 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005088 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005089 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5090 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005091}
5092
Yiwei Zhang5434a782018-12-05 18:06:32 -08005093void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
5094 result.append("Layer frame timestamps:\n");
Josh Chienedaa9132020-12-04 18:30:46 +08005095 // Traverse all layers to dump frame-events for each layer
5096 mCurrentState.traverseInZOrder(
5097 [&] (Layer* layer) { layer->dumpFrameEvents(result); });
Brian Andersond6927fb2016-07-23 23:37:30 -07005098}
5099
Yiwei Zhang5434a782018-12-05 18:06:32 -08005100void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005101 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005102 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005103 if (!displayId) {
5104 continue;
5105 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005106 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005107 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005108 continue;
5109 }
5110
Yiwei Zhang5434a782018-12-05 18:06:32 -08005111 StringAppendF(&result,
5112 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5113 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005114 uint8_t port;
5115 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005116 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005117 result.append("no identification data\n");
5118 continue;
5119 }
5120
5121 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005122 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005123 continue;
5124 }
5125
5126 const auto edid = parseEdid(data);
5127 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005128 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005129 continue;
5130 }
5131
Yiwei Zhang5434a782018-12-05 18:06:32 -08005132 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005133 result.append(edid->displayName.data(), edid->displayName.length());
5134 result.append("\"\n");
5135 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005136}
5137
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005138void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5139 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005140 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005141 uint8_t port;
5142 DisplayIdentificationData data;
5143
5144 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5145 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5146 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5147 }
5148}
5149
Yiwei Zhang5434a782018-12-05 18:06:32 -08005150void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005151 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005152 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5153 StringAppendF(&result, "DisplayColorSetting: %s\n",
5154 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005155
5156 // TODO: print out if wide-color mode is active or not
5157
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005158 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005159 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005160 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005161 continue;
5162 }
5163
Yiwei Zhang5434a782018-12-05 18:06:32 -08005164 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005165 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005166 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005167 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005168 }
5169
Lloyd Pique32cbe282018-10-19 13:09:22 -07005170 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005171 StringAppendF(&result, " Current color mode: %s (%d)\n",
5172 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005173 }
5174 result.append("\n");
5175}
5176
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005177LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005178 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005179 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005180 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005181 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005182
chaviw1d044282017-09-27 12:19:28 -07005183 return layersProto;
5184}
5185
chaviw0a398992021-08-13 10:13:01 -05005186void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005187 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005188 DisplayProto* displayProto = layersTraceProto.add_displays();
5189 displayProto->set_id(display->getId().value);
5190 displayProto->set_name(display->getDisplayName());
5191 displayProto->set_layer_stack(display->getLayerStack().id);
5192 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5193 [&]() { return displayProto->mutable_size(); });
5194 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5195 return displayProto->mutable_layer_stack_space_rect();
5196 });
5197 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5198 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005199 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005200 }
5201}
5202
Alec Mouri6b9e9912020-01-21 10:50:24 -08005203void SurfaceFlinger::dumpHwc(std::string& result) const {
5204 getHwComposer().dump(result);
5205}
5206
Vishnu Nair0f085c62019-08-30 08:49:12 -07005207void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5208 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5209 // it.
5210 LayerProto* rootProto = layersProto.add_layers();
5211 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5212 rootProto->set_id(offscreenRootLayerId);
5213 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005214 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005215
5216 for (Layer* offscreenLayer : mOffscreenLayers) {
5217 // Add layer as child of the fake root
5218 rootProto->add_children(offscreenLayer->sequence);
5219
5220 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005221 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005222 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005223 }
5224}
5225
Vishnu Nair8406fd72019-07-30 11:29:31 -07005226LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005227 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005228}
5229
Vishnu Nair0f085c62019-08-30 08:49:12 -07005230void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005231 auto future = mScheduler->schedule([this] {
5232 std::string result;
5233 for (Layer* offscreenLayer : mOffscreenLayers) {
5234 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5235 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5236 }
5237 return result;
5238 });
5239
Vishnu Nair0f085c62019-08-30 08:49:12 -07005240 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005241 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005242}
5243
Dominik Laskowskic2867142019-01-21 11:33:38 -08005244void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5245 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005246 Colorizer colorizer(colorize);
5247
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005248 // figure out if we're stuck somewhere
5249 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005250 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005251 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5252
5253 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005254 * Dump library configuration.
5255 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005256
5257 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005258 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005259 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005260 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005261 result.append("\n");
5262
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005263 result.append("\nDisplay identification data:\n");
5264 dumpDisplayIdentificationData(result);
5265
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005266 result.append("\nWide-Color information:\n");
5267 dumpWideColorInfo(result);
5268
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005269 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005270 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005271 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005272 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005273 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005274
Andy McFadden41d67d72014-04-25 16:58:34 -07005275 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005276 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005277 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005278 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005279 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005280
Dan Stozab90cf072015-03-05 11:05:59 -08005281 dumpStaticScreenStats(result);
5282 result.append("\n");
5283
Alec Mouri40189b02019-03-05 15:07:54 -08005284 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5285 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5286 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005287
Andy McFadden4803b742012-09-24 19:07:20 -07005288 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005289 * Dump the visible layer list
5290 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005291 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005292 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005293 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005294
Chia-I Wu2f884132018-09-13 15:17:58 -07005295 {
Lloyd Pique207def92019-02-28 16:09:52 -08005296 StringAppendF(&result, "Composition layers\n");
5297 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005298 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005299 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005300
5301 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5302 layer->getDebugName() ? layer->getDebugName()
5303 : "<unknown>");
5304 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005305 });
5306 }
5307
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005308 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005309 * Dump Display state
5310 */
5311
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005312 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005313 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005314 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005315 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005316 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005317 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005318 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005319
5320 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005321 * Dump CompositionEngine state
5322 */
5323
5324 mCompositionEngine->dump(result);
5325
5326 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005327 * Dump SurfaceFlinger global state
5328 */
5329
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005330 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005331 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005332 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005333
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005334 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005335
Robert Carrbeba6f02021-02-10 21:06:27 -08005336 result.append("ClientCache state:\n");
5337 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005338 DebugEGLImageTracker::getInstance()->dump(result);
5339
Dominik Laskowski075d3172018-05-24 15:50:06 -07005340 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005341 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5342 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005343 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5344 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005345 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005346 StringAppendF(&result,
5347 " transaction-flags : %08x\n"
5348 " gpu_to_cpu_unsupported : %d\n",
5349 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005350
Marin Shalamanov045b7002021-01-07 16:56:24 +01005351 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005352 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005353 if (const auto activeMode = display->getActiveMode()) {
5354 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005355
5356 const auto dpi = activeMode->getDpi();
5357 xDpi = base::StringPrintf("%.2f", dpi.x);
5358 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005359 } else {
5360 fps = "unknown";
5361 xDpi = "unknown";
5362 yDpi = "unknown";
5363 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005364 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005365 " refresh-rate : %s\n"
5366 " x-dpi : %s\n"
5367 " y-dpi : %s\n",
5368 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005369 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005370
Yiwei Zhang5434a782018-12-05 18:06:32 -08005371 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005372
Dan Stozae22aec72016-08-01 13:20:59 -07005373 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005374 * Tracing state
5375 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005376 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005377
5378 result.append("\nTransaction tracing: ");
5379 if (mTransactionTracing) {
5380 result.append("enabled\n");
5381 mTransactionTracing->dump(result);
5382 } else {
5383 result.append("disabled\n");
5384 }
5385 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005386
5387 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005388 * HWC layer minidump
5389 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005390 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005391 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005392 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005393 continue;
5394 }
5395
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005396 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5397 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005398 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005399
5400 const DisplayDevice& ref = *display;
5401 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005402 result.append("\n");
5403 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005404
Ady Abraham2790e9f2021-04-28 13:14:20 -07005405 {
5406 DumpArgs plannerArgs;
5407 plannerArgs.add(); // first argument is ignored
5408 plannerArgs.add(String16("--layers"));
5409 dumpPlannerInfo(plannerArgs, result);
5410 }
5411
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005412 /*
5413 * Dump HWComposer state
5414 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005415 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005416 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005417 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005418 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005419 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005420 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005421
5422 /*
5423 * Dump gralloc state
5424 */
5425 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5426 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005427
rnleea2ecd832021-07-29 13:58:30 -07005428 /*
5429 * Dump flag/property manager state
5430 */
Robert Carr9b623c32022-03-21 15:55:22 -07005431 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005432
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005433 result.append(mTimeStats->miniDump());
5434 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005435}
5436
chaviw17ac24b2021-01-28 18:50:05 -08005437mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5438 if (saturation == 1) {
5439 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005440 }
5441
chaviw17ac24b2021-01-28 18:50:05 -08005442 float3 luminance{0.213f, 0.715f, 0.072f};
5443 luminance *= 1.0f - saturation;
5444 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5445 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5446 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5447 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5448 return saturationMatrix;
5449}
5450
5451void SurfaceFlinger::updateColorMatrixLocked() {
5452 mat4 colorMatrix =
5453 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5454
Chia-I Wu28f320b2018-05-03 11:02:56 -07005455 if (mCurrentState.colorMatrix != colorMatrix) {
5456 mCurrentState.colorMatrix = colorMatrix;
5457 mCurrentState.colorMatrixChanged = true;
5458 setTransactionFlags(eTransactionNeeded);
5459 }
5460}
5461
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005462status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005463#pragma clang diagnostic push
5464#pragma clang diagnostic error "-Wswitch-enum"
5465 switch (static_cast<ISurfaceComposerTag>(code)) {
5466 // These methods should at minimum make sure that the client requested
5467 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005468 case BOOT_FINISHED:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005469 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005470 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005471 case GET_GAME_CONTENT_TYPE_SUPPORT:
Ady Abraham8532d012019-05-08 14:50:56 -07005472 case GET_DISPLAYED_CONTENT_SAMPLE:
Steven Thomasd4071902020-03-24 16:02:53 -07005473 case SET_GLOBAL_SHADOW_SETTINGS:
5474 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005475 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5476 // permission dynamically. Don't use the permission cache for this check.
5477 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005478 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005479 IPCThreadState* ipc = IPCThreadState::self();
5480 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5481 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005482 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005483 }
Robert Carr1db73f62016-12-21 12:58:51 -08005484 return OK;
5485 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005486 // Used by apps to hook Choreographer to SurfaceFlinger.
5487 case CREATE_DISPLAY_EVENT_CONNECTION:
5488 // The following calls are currently used by clients that do not
5489 // request necessary permissions. However, they do not expose any secret
5490 // information, so it is OK to pass them.
5491 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005492 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005493 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005494 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005495 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005496 // Calling setTransactionState is safe, because you need to have been
5497 // granted a reference to Client* and Handle* to do anything with it.
5498 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005499 case CREATE_CONNECTION:
Steven Thomas62a4cf82020-01-31 12:04:03 -08005500 // setFrameRate() is deliberately available for apps to call without any
5501 // special permissions.
5502 case SET_FRAME_RATE:
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05005503 case GET_DISPLAY_DECORATION_SUPPORT:
Huihong Luo02186fb2022-02-23 14:21:54 -08005504 case SET_FRAME_TIMELINE_INFO: {
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 }
Andy Yu8c38b252022-01-15 01:13:19 -08005508 case SET_OVERRIDE_FRAME_RATE: {
5509 const int uid = IPCThreadState::self()->getCallingUid();
5510 if (uid == AID_ROOT || uid == AID_SYSTEM) {
5511 return OK;
5512 }
5513 return PERMISSION_DENIED;
5514 }
Huihong Luo07e72362022-02-14 14:26:04 -08005515 case CREATE_DISPLAY:
5516 case DESTROY_DISPLAY:
5517 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5518 case GET_PHYSICAL_DISPLAY_IDS:
5519 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo37396db2022-02-15 10:43:00 -08005520 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005521 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005522 case GET_DISPLAY_STATE:
5523 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005524 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005525 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005526 case GET_DISPLAY_NATIVE_PRIMARIES:
5527 case SET_ACTIVE_COLOR_MODE:
5528 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005529 case CLEAR_BOOT_DISPLAY_MODE:
5530 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5531 case SET_AUTO_LOW_LATENCY_MODE:
5532 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005533 case CAPTURE_LAYERS:
5534 case CAPTURE_DISPLAY:
5535 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005536 case CLEAR_ANIMATION_FRAME_STATS:
5537 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005538 case OVERRIDE_HDR_TYPES:
5539 case ON_PULL_ATOM:
5540 case ENABLE_VSYNC_INJECTIONS:
5541 case INJECT_VSYNC:
5542 case GET_LAYER_DEBUG_INFO:
5543 case GET_COLOR_MANAGEMENT:
5544 case GET_COMPOSITION_PREFERENCE:
5545 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5546 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5547 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005548 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005549 case ADD_REGION_SAMPLING_LISTENER:
5550 case REMOVE_REGION_SAMPLING_LISTENER:
5551 case ADD_FPS_LISTENER:
5552 case REMOVE_FPS_LISTENER:
5553 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5554 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5555 case ADD_WINDOW_INFOS_LISTENER:
5556 case REMOVE_WINDOW_INFOS_LISTENER:
5557 case SET_DESIRED_DISPLAY_MODE_SPECS:
5558 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005559 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5560 case SET_DISPLAY_BRIGHTNESS:
5561 case ADD_HDR_LAYER_INFO_LISTENER:
5562 case REMOVE_HDR_LAYER_INFO_LISTENER:
5563 case NOTIFY_POWER_BOOST:
Huihong Luo02186fb2022-02-23 14:21:54 -08005564 case ADD_TRANSACTION_TRACE_LISTENER:
5565 case GET_GPU_CONTEXT_PRIORITY:
5566 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005567 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005568 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005569 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005570
5571 // These codes are used for the IBinder protocol to either interrogate the recipient
5572 // side of the transaction for its canonical interface descriptor or to dump its state.
5573 // We let them pass by default.
5574 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5575 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5576 code == IBinder::SYSPROPS_TRANSACTION) {
5577 return OK;
5578 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005579 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005580 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005581 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005582 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5583 return OK;
5584 }
5585 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5586 return PERMISSION_DENIED;
5587#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005588}
5589
Ana Krulec13be8ad2018-08-21 02:43:56 +00005590status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5591 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005592 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5593 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005594 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005595
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005596 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5597 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005598 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005599 IPCThreadState* ipc = IPCThreadState::self();
5600 const int uid = ipc->getCallingUid();
5601 if (CC_UNLIKELY(uid != AID_SYSTEM
5602 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005603 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005604 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005605 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005606 return PERMISSION_DENIED;
5607 }
5608 int n;
5609 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005610 case 1000: // Unused.
5611 case 1001:
5612 return NAME_NOT_FOUND;
5613 case 1002: // Toggle flashing on surface damage.
5614 if (const int delay = data.readInt32(); delay > 0) {
5615 mDebugFlashDelay = delay;
5616 } else {
5617 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5618 }
5619 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005620 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005621 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005622 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005623 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005624 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005625 case 1005: { // Force commit ahead of next VSYNC.
5626 Mutex::Autolock lock(mStateLock);
5627 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5628 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005629 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005630 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005631 case 1007: // Unused.
5632 return NAME_NOT_FOUND;
5633 case 1008: // Toggle forced GPU composition.
5634 mDebugDisableHWC = data.readInt32() != 0;
5635 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005636 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005637 case 1009: // Toggle use of transform hint.
5638 mDebugDisableTransformHint = data.readInt32() != 0;
5639 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005640 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005641 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005642 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005643 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005644 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005645 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005646 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005647 return NO_ERROR;
5648 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005649 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005650 if (!display) {
5651 return NAME_NOT_FOUND;
5652 }
5653
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005654 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005655 return NO_ERROR;
5656 }
5657 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005658 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005659 // daltonize
5660 n = data.readInt32();
5661 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005662 case 1:
5663 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5664 break;
5665 case 2:
5666 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5667 break;
5668 case 3:
5669 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5670 break;
5671 default:
5672 mDaltonizer.setType(ColorBlindnessType::None);
5673 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005674 }
5675 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005676 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005677 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005678 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005679 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005680
5681 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005682 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005683 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005684 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005685 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005686 // apply a color matrix
5687 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005688 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005689 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005690 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005691 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005692 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005693 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005694 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005695 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005696 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005697 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005698
5699 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5700 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005701 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005702 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5703 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5704 }
5705
Chia-I Wu28f320b2018-05-03 11:02:56 -07005706 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005707 return NO_ERROR;
5708 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005709 case 1016: { // Unused.
5710 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005711 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005712 case 1017: {
5713 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005714 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005715 return NO_ERROR;
5716 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005717 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005718 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005719 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005720 return NO_ERROR;
5721 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005722 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005723 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005724 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005725 return NO_ERROR;
5726 }
Irvel468051e2016-06-13 16:44:44 -07005727 case 1020: { // Layer updates interceptor
5728 n = data.readInt32();
5729 if (n) {
5730 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005731 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005732 }
5733 else{
5734 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005735 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005736 }
5737 return NO_ERROR;
5738 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005739 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005740 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005741 static_cast<void>(
5742 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005743 return NO_ERROR;
5744 }
Romain Guy0147a172017-06-01 13:53:56 -07005745 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005746 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005747 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005748
Chia-I Wu28f320b2018-05-03 11:02:56 -07005749 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005750 return NO_ERROR;
5751 }
Romain Guy54f154a2017-10-24 21:40:32 +01005752 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005753 int32_t colorMode;
5754
Chia-I Wu0d711262018-05-21 15:19:35 -07005755 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005756 if (data.readInt32(&colorMode) == NO_ERROR) {
5757 mForceColorMode = static_cast<ColorMode>(colorMode);
5758 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005759 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005760 return NO_ERROR;
5761 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005762 // Deprecate, use 1030 to check whether the device is color managed.
5763 case 1024: {
5764 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005765 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005766 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005767 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005768 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005769 if (n == 1) {
5770 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005771 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005772 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005773 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005774 int64_t startingTime =
5775 (fixedStartingTime) ? fixedStartingTime : systemTime();
5776 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005777 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005778 mLayerTracing.notify("start", startingTime);
5779 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005780 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005781 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005782 } else if (n == 2) {
5783 std::string filename = std::string(data.readCString());
5784 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5785 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005786 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005787 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005788 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005789 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005790 mTracingEnabledChanged = tracingEnabledChanged;
5791 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005792 return NO_ERROR;
5793 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005794 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005795 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005796 return NO_ERROR;
5797 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005798 // Is a DisplayColorSetting supported?
5799 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005800 const auto display = getDefaultDisplayDevice();
5801 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005802 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005803 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005804
5805 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5806 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005807 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005808 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005809 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005810 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005811 reply->writeBool(true);
5812 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005813 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005814 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005815 break;
5816 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005817 reply->writeBool(
5818 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005819 break;
5820 }
5821 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005822 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005823 case 1028: { // Unused.
5824 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005825 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005826 // Set buffer size for SF tracing (value in KB)
5827 case 1029: {
5828 n = data.readInt32();
5829 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5830 ALOGW("Invalid buffer size: %d KB", n);
5831 reply->writeInt32(BAD_VALUE);
5832 return BAD_VALUE;
5833 }
5834
5835 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005836 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005837 reply->writeInt32(NO_ERROR);
5838 return NO_ERROR;
5839 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005840 // Is device color managed?
5841 case 1030: {
5842 reply->writeBool(useColorManagement);
5843 return NO_ERROR;
5844 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005845 // Override default composition data space
5846 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5847 // && adb shell stop zygote && adb shell start zygote
5848 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5849 // adb shell stop zygote && adb shell start zygote
5850 case 1031: {
5851 Mutex::Autolock _l(mStateLock);
5852 n = data.readInt32();
5853 if (n) {
5854 n = data.readInt32();
5855 if (n) {
5856 Dataspace dataspace = static_cast<Dataspace>(n);
5857 if (!validateCompositionDataspace(dataspace)) {
5858 return BAD_VALUE;
5859 }
5860 mDefaultCompositionDataspace = dataspace;
5861 }
5862 n = data.readInt32();
5863 if (n) {
5864 Dataspace dataspace = static_cast<Dataspace>(n);
5865 if (!validateCompositionDataspace(dataspace)) {
5866 return BAD_VALUE;
5867 }
5868 mWideColorGamutCompositionDataspace = dataspace;
5869 }
5870 } else {
5871 // restore composition data space.
5872 mDefaultCompositionDataspace = defaultCompositionDataspace;
5873 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5874 }
5875 return NO_ERROR;
5876 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005877 // Set trace flags
5878 case 1033: {
5879 n = data.readUint32();
5880 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005881 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005882 reply->writeInt32(NO_ERROR);
5883 return NO_ERROR;
5884 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005885 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005886 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005887 switch (n = data.readInt32()) {
5888 case 0:
5889 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005890 FTL_FAKE_GUARD(mStateLock,
5891 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005892 break;
5893 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005894 reply->writeBool(
5895 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005896 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005897 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005898 });
5899
5900 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005901 return NO_ERROR;
5902 }
Ady Abraham34392f72019-04-10 11:29:27 -07005903 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005904 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005905
Dominik Laskowskif1833852021-03-23 15:06:50 -07005906 const auto display = [&]() -> sp<IBinder> {
5907 uint64_t value;
5908 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005909 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005910 }
5911
Dominik Laskowskif1833852021-03-23 15:06:50 -07005912 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5913 return getPhysicalDisplayToken(*id);
5914 }
5915
5916 ALOGE("Invalid physical display ID");
5917 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005918 }();
5919
Shiyong Li2bcece92021-08-30 20:38:50 +00005920 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005921 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005922 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5923 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005924 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005925 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5926 // manager frame rate policy a new policy which allows switching between all refresh
5927 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005928 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005929 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005930 return mScheduler
5931 ->schedule([this] {
5932 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005933 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005934
Dominik Laskowski756b7892021-08-04 12:53:59 -07005935 // This is a little racy, but not in a way that hurts anything. As
5936 // we grab the defaultMode from the display manager policy, we could
5937 // be setting a new display manager policy, leaving us using a stale
5938 // defaultMode. The defaultMode doesn't matter for the override
5939 // policy though, since we set allowGroupSwitching to true, so it's
5940 // not a problem.
5941 scheduler::RefreshRateConfigs::Policy overridePolicy;
5942 overridePolicy.defaultMode = display->refreshRateConfigs()
5943 .getDisplayManagerPolicy()
5944 .defaultMode;
5945 overridePolicy.allowGroupSwitching = true;
5946 constexpr bool kOverridePolicy = true;
5947 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5948 kOverridePolicy);
5949 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005950 .get();
5951 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07005952 return mScheduler
5953 ->schedule([this] {
5954 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005955 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07005956 constexpr bool kOverridePolicy = true;
5957 return setDesiredDisplayModeSpecsInternal(display, {},
5958 kOverridePolicy);
5959 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005960 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07005961 }
Ady Abraham07e54702020-04-16 15:05:37 -07005962 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02005963 // Inject a hotplug connected event for the primary display. This will deallocate and
5964 // reallocate the display state including framebuffers.
5965 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07005966 const hal::HWDisplayId hwcId =
5967 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
5968
5969 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02005970 return NO_ERROR;
5971 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07005972 // Modify the max number of display frames stored within FrameTimeline
5973 case 1038: {
5974 n = data.readInt32();
5975 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
5976 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
5977 return BAD_VALUE;
5978 }
5979 if (n == 0) {
5980 // restore to default
5981 mFrameTimeline->reset();
5982 return NO_ERROR;
5983 }
5984 mFrameTimeline->setMaxDisplayFrames(n);
5985 return NO_ERROR;
5986 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07005987 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07005988 PhysicalDisplayId displayId = [&]() {
5989 Mutex::Autolock lock(mStateLock);
5990 return getDefaultDisplayDeviceLocked()->getPhysicalId();
5991 }();
5992
5993 auto inUid = static_cast<uid_t>(data.readInt32());
5994 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08005995 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
5996 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07005997 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08005998 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005999 // Toggle caching feature
6000 // First argument is an int32 - nonzero enables caching and zero disables caching
6001 // Second argument is an optional uint64 - if present, then limits enabling/disabling
6002 // caching to a particular physical display
6003 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006004 auto future = mScheduler->schedule([&] {
6005 n = data.readInt32();
6006 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6007 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6008 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6009 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6010 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6011 return NAME_NOT_FOUND;
6012 }
6013 }
6014 {
6015 Mutex::Autolock lock(mStateLock);
6016 mLayerCachingEnabled = n != 0;
6017 for (const auto& [_, display] : mDisplays) {
6018 if (!inputId || *inputId == display->getPhysicalId()) {
6019 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006020 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006021 }
6022 }
6023 return OK;
6024 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006025
Dominik Laskowski756b7892021-08-04 12:53:59 -07006026 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006027 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006028 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006029 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006030 return NO_ERROR;
6031 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006032 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006033 if (mTransactionTracing) {
6034 if (data.readInt32()) {
6035 // Transaction tracing is always running but allow the user to temporarily
6036 // increase the buffer when actively debugging.
6037 mTransactionTracing->setBufferSize(
6038 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6039 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006040 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006041 mTransactionTracing->setBufferSize(
6042 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006043 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006044 }
6045 reply->writeInt32(NO_ERROR);
6046 return NO_ERROR;
6047 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006048 case 1042: { // Write layers trace or transaction trace to file
6049 if (mTransactionTracing) {
6050 mTransactionTracing->writeToFile();
6051 }
6052 if (mLayerTracingEnabled) {
6053 mLayerTracing.writeToFile();
6054 }
6055 reply->writeInt32(NO_ERROR);
6056 return NO_ERROR;
6057 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006058 }
6059 }
6060 return err;
6061}
6062
Ady Abrahama09852a2020-02-20 14:23:42 -08006063void SurfaceFlinger::kernelTimerChanged(bool expired) {
6064 static bool updateOverlay =
6065 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006066 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006067
6068 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006069 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006070 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006071 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006072 if (!display) {
6073 ALOGW("%s: default display is null", __func__);
6074 return;
6075 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006076 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006077
6078 const auto desiredActiveMode = display->getDesiredActiveMode();
6079 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6080 ? std::make_optional(desiredActiveMode->mode->getId())
6081 : std::nullopt;
6082
6083 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6084
Ady Abraham1b11bc62021-06-03 19:51:19 -07006085 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006086 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006087 }
6088 }));
6089}
6090
ramindani32cf0602022-03-02 02:30:29 +00006091std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6092SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6093 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6094 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6095 const auto timeout = getIdleTimerTimeout(displayId);
6096 if (isKernelIdleTimerHwcSupported) {
6097 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6098 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6099 // In order to decide if we can use the HWC api for idle timer
6100 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6101 // without relying on hasDisplayCapability.
6102 // hasDisplayCapability relies on DisplayCapabilities
6103 // which are updated after we set the PowerMode::ON.
6104 // DISPLAY_IDLE_TIMER is a display driver property
6105 // and is available before the PowerMode::ON
6106 return {KernelIdleTimerController::HwcApi, timeout};
6107 }
6108 return {std::nullopt, timeout};
6109 }
6110 if (getKernelIdleTimerSyspropConfig(displayId)) {
6111 return {KernelIdleTimerController::Sysprop, timeout};
6112 }
6113
6114 return {std::nullopt, timeout};
6115}
6116
6117void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6118 KernelIdleTimerController controller,
6119 PhysicalDisplayId displayId) {
6120 switch (controller) {
6121 case KernelIdleTimerController::HwcApi: {
6122 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6123 break;
6124 }
6125 case KernelIdleTimerController::Sysprop: {
6126 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6127 break;
6128 }
6129 }
6130}
6131
Ana Krulecb9afd792020-06-11 13:16:15 -07006132void SurfaceFlinger::toggleKernelIdleTimer() {
6133 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6134
Ady Abraham3efa3942021-06-24 19:01:25 -07006135 const auto display = getDefaultDisplayDeviceLocked();
6136 if (!display) {
6137 ALOGW("%s: default display is null", __func__);
6138 return;
6139 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006140
Ady Abrahame9316b72021-09-24 17:04:36 -07006141 // If the support for kernel idle timer is disabled for the active display,
6142 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006143 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6144 display->refreshRateConfigs().kernelIdleTimerController();
6145 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006146 return;
6147 }
6148
Ady Abraham3efa3942021-06-24 19:01:25 -07006149 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006150
Ana Krulecb9afd792020-06-11 13:16:15 -07006151 switch (action) {
6152 case KernelIdleTimerAction::TurnOff:
6153 if (mKernelIdleTimerEnabled) {
6154 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006155 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6156 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6157 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006158 mKernelIdleTimerEnabled = false;
6159 }
6160 break;
6161 case KernelIdleTimerAction::TurnOn:
6162 if (!mKernelIdleTimerEnabled) {
6163 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006164 const std::chrono::milliseconds timeout =
6165 display->refreshRateConfigs().getIdleTimerTimeout();
6166 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6167 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006168 mKernelIdleTimerEnabled = true;
6169 }
6170 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006171 }
6172}
6173
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006174// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6175class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006176public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006177 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6178 ~WindowDisconnector() {
6179 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006180 }
6181
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006182private:
6183 ANativeWindow* mWindow;
6184 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006185};
6186
chaviw93df2ea2019-04-30 16:45:12 -07006187static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6188 switch (colorMode) {
6189 case ColorMode::DISPLAY_P3:
6190 case ColorMode::BT2100_PQ:
6191 case ColorMode::BT2100_HLG:
6192 case ColorMode::DISPLAY_BT2020:
6193 return Dataspace::DISPLAY_P3;
6194 default:
6195 return Dataspace::V0_SRGB;
6196 }
6197}
6198
chaviwf5bb97b2021-04-28 15:35:37 -05006199static bool hasCaptureBlackoutContentPermission() {
6200 IPCThreadState* ipc = IPCThreadState::self();
6201 const int pid = ipc->getCallingPid();
6202 const int uid = ipc->getCallingUid();
6203 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6204 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6205}
6206
chaviw4b9d5e12020-08-04 18:30:35 -07006207static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6208 IPCThreadState* ipc = IPCThreadState::self();
6209 const int pid = ipc->getCallingPid();
6210 const int uid = ipc->getCallingUid();
6211 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6212 return OK;
6213 }
6214
6215 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6216 // itself, we allow it to continue.
6217 if (captureArgs.uid == uid) {
6218 return OK;
6219 }
6220
6221 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6222 return PERMISSION_DENIED;
6223}
6224
Peiyong Lin05cc0112020-10-14 16:16:37 -07006225status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6226 static constexpr int kFifoPriority = 2;
6227 static constexpr int kOtherPriority = 0;
6228
6229 struct sched_param param = {0};
6230 int sched_policy;
6231 if (enabled) {
6232 sched_policy = SCHED_FIFO;
6233 param.sched_priority = kFifoPriority;
6234 } else {
6235 sched_policy = SCHED_OTHER;
6236 param.sched_priority = kOtherPriority;
6237 }
6238
6239 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6240 return -errno;
6241 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006242
6243 return NO_ERROR;
6244}
6245
6246status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6247 static const unsigned int kUclampMin =
6248 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6249
6250 if (!kUclampMin) {
6251 // uclamp.min set to 0 (default), skip setting
6252 return NO_ERROR;
6253 }
6254
6255 // Currently, there is no wrapper in bionic: b/183240349.
6256 struct sched_attr {
6257 uint32_t size;
6258 uint32_t sched_policy;
6259 uint64_t sched_flags;
6260 int32_t sched_nice;
6261 uint32_t sched_priority;
6262 uint64_t sched_runtime;
6263 uint64_t sched_deadline;
6264 uint64_t sched_period;
6265 uint32_t sched_util_min;
6266 uint32_t sched_util_max;
6267 };
6268
6269 sched_attr attr = {};
6270 attr.size = sizeof(attr);
6271
6272 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6273 attr.sched_util_min = enabled ? kUclampMin : 0;
6274 attr.sched_util_max = 1024;
6275
6276 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6277 return -errno;
6278 }
6279
Peiyong Lin05cc0112020-10-14 16:16:37 -07006280 return NO_ERROR;
6281}
6282
chaviwd2432892020-07-24 17:42:39 -07006283status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006284 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006285 ATRACE_CALL();
6286
chaviw4b9d5e12020-08-04 18:30:35 -07006287 status_t validate = validateScreenshotPermissions(args);
6288 if (validate != OK) {
6289 return validate;
6290 }
6291
chaviwd2432892020-07-24 17:42:39 -07006292 if (!args.displayToken) return BAD_VALUE;
6293
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006294 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006295 ui::LayerStack layerStack;
6296 ui::Size reqSize(args.width, args.height);
6297 ui::Dataspace dataspace;
6298 {
6299 Mutex::Autolock lock(mStateLock);
6300 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6301 if (!display) return NAME_NOT_FOUND;
6302 displayWeak = display;
6303 layerStack = display->getLayerStack();
6304
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006305 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006306 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006307 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006308 }
6309
arthurhung79e81aa2020-08-28 00:09:19 +08006310 // The dataspace is depended on the color mode of display, that could use non-native mode
6311 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6312 // and failed if display is not in native mode. This provide a way to force using native
6313 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006314 dataspace = args.dataspace;
6315 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006316 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6317 dataspace = pickDataspaceFromColorMode(colorMode);
6318 }
chaviwd2432892020-07-24 17:42:39 -07006319 }
6320
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006321 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006322 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006323 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006324 });
6325
chaviw4b9d5e12020-08-04 18:30:35 -07006326 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6327 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006328 };
chaviw03900772020-08-18 12:34:51 -07006329
Sally Qi59a9f502021-10-12 18:53:23 +00006330 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6331 reqSize, args.pixelFormat, args.allowProtected,
6332 args.grayscale, captureListener);
6333 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006334}
6335
Dominik Laskowskif1833852021-03-23 15:06:50 -07006336status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006337 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006338 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006339 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006340 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006341 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006342 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006343 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006344
Dominik Laskowskif1833852021-03-23 15:06:50 -07006345 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006346 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006347 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006348 }
6349
chaviw93df2ea2019-04-30 16:45:12 -07006350 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006351 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006352 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006353
chaviw426b5c02020-07-27 11:20:15 -07006354 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006355 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6356 }
6357
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006358 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006359 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006360 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006361 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006362 });
chaviw93df2ea2019-04-30 16:45:12 -07006363
Marin Shalamanov1c434292020-06-12 01:47:29 +02006364 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006365 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006366 };
6367
Sally Qi59a9f502021-10-12 18:53:23 +00006368 if (captureListener == nullptr) {
6369 ALOGE("capture screen must provide a capture listener callback");
6370 return BAD_VALUE;
6371 }
6372 auto captureResultFuture =
6373 captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6374 ui::PixelFormat::RGBA_8888, false /* allowProtected */,
6375 false /* grayscale */, captureListener);
6376 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006377}
6378
chaviw3efadb12020-07-27 10:07:15 -07006379status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006380 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006381 ATRACE_CALL();
6382
chaviw4b9d5e12020-08-04 18:30:35 -07006383 status_t validate = validateScreenshotPermissions(args);
6384 if (validate != OK) {
6385 return validate;
6386 }
6387
Marin Shalamanov1c434292020-06-12 01:47:29 +02006388 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006389 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006390 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006391 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006392 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006393
6394 // Call this before holding mStateLock to avoid any deadlocking.
6395 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6396
Robert Carrc0df3122019-04-11 13:18:21 -07006397 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006398 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006399
Vishnu Nairf9096652021-07-20 18:49:42 -07006400 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006401 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006402 ALOGE("captureLayers called with an invalid or removed parent");
6403 return NAME_NOT_FOUND;
6404 }
6405
chaviwf5bb97b2021-04-28 15:35:37 -05006406 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006407 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006408 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6409 return PERMISSION_DENIED;
6410 }
6411
Robert Carr6a160312021-05-17 12:08:20 -07006412 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006413 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006414 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006415 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006416 }
6417
chaviw3efadb12020-07-27 10:07:15 -07006418 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006419 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006420 crop.bottom = parentSourceBounds.getHeight();
6421 }
6422
chaviw17ac24b2021-01-28 18:50:05 -08006423 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006424 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6425 // crop was not specified, or an invalid frame scale was provided.
6426 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006427 }
chaviw17ac24b2021-01-28 18:50:05 -08006428 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006429
chaviw3efadb12020-07-27 10:07:15 -07006430 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006431 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006432 if (excludeLayer != nullptr) {
6433 excludeLayers.emplace(excludeLayer);
6434 } else {
6435 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6436 return NAME_NOT_FOUND;
6437 }
6438 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006439
arthurhung79e81aa2020-08-28 00:09:19 +08006440 // The dataspace is depended on the color mode of display, that could use non-native mode
6441 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6442 // and failed if display is not in native mode. This provide a way to force using native
6443 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006444 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006445 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006446
Chia-I Wu20261cb2018-08-23 12:55:44 -07006447 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006448 if (reqSize.width <= 0 || reqSize.height <= 0) {
6449 ALOGW("Failed to captureLayes: crop or scale too small");
6450 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006451 }
6452
chaviw79468ab2021-10-27 11:11:24 -05006453 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006454 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006455 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006456 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006457 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006458 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006459 });
6460
chaviw03900772020-08-18 12:34:51 -07006461 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006462 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6463 if (!layer->isVisible()) {
6464 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006465 } else if (args.childrenOnly && layer == parent.get()) {
6466 return;
6467 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006468 return;
chaviwa76b2712017-09-20 12:02:26 -07006469 }
Robert Carr866455f2019-04-02 16:28:26 -07006470
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006471 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006472 while (p != nullptr) {
6473 if (excludeLayers.count(p) != 0) {
6474 return;
6475 }
6476 p = p->getParent();
6477 }
6478
chaviwa76b2712017-09-20 12:02:26 -07006479 visitor(layer);
6480 });
6481 };
Robert Carr108b2c72019-04-02 16:32:58 -07006482
Sally Qi59a9f502021-10-12 18:53:23 +00006483 if (captureListener == nullptr) {
6484 ALOGE("capture screen must provide a capture listener callback");
6485 return BAD_VALUE;
6486 }
6487
6488 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6489 reqSize, args.pixelFormat, args.allowProtected,
6490 args.grayscale, captureListener);
6491 return captureResultFuture.get().status;
chaviwa76b2712017-09-20 12:02:26 -07006492}
6493
Sally Qi59a9f502021-10-12 18:53:23 +00006494std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
6495 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6496 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6497 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006498 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006499
Garfield Tan9c9c1912021-07-19 12:02:16 -07006500 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6501 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6502 ") that exceeds render target size limit.",
6503 bufferSize.getWidth(), bufferSize.getHeight());
Sally Qi59a9f502021-10-12 18:53:23 +00006504 return ftl::yield<renderengine::RenderEngineResult>({BAD_VALUE, base::unique_fd()}).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006505 }
6506
Peiyong Lin05cc0112020-10-14 16:16:37 -07006507 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6508 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6509 // A protected layer has no implication on whether it's secure, which is explicitly set by
6510 // application to avoid being screenshot or drawn via unsecure display.
6511 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6512 bool hasProtectedLayer = false;
6513 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006514 auto future = mScheduler->schedule([=]() {
6515 bool protectedLayerFound = false;
6516 traverseLayers([&](Layer* layer) {
6517 protectedLayerFound =
6518 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6519 });
6520 return protectedLayerFound;
6521 });
6522 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006523 }
6524
Richard Liucbcb8952020-04-08 10:51:55 +00006525 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6526 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006527 (hasProtectedLayer && allowProtected && supportsProtected
6528 ? GRALLOC_USAGE_PROTECTED
6529 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006530 sp<GraphicBuffer> buffer =
6531 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6532 static_cast<android_pixel_format>(reqPixelFormat),
6533 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006534
6535 const status_t bufferStatus = buffer->initCheck();
6536 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6537 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006538 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6539 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6540 renderengine::impl::ExternalTexture::Usage::
6541 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006542 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006543 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006544}
6545
Sally Qi59a9f502021-10-12 18:53:23 +00006546std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006547 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6548 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6549 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006550 ATRACE_CALL();
6551
chaviwf5bb97b2021-04-28 15:35:37 -05006552 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006553
Dominik Laskowski756b7892021-08-04 12:53:59 -07006554 auto scheduleResultFuture = mScheduler->schedule([=,
6555 renderAreaFuture =
6556 std::move(renderAreaFuture)]() mutable
6557 -> std::shared_future<
6558 renderengine::RenderEngineResult> {
chaviw03900772020-08-18 12:34:51 -07006559 ScreenCaptureResults captureResults;
6560 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6561 if (!renderArea) {
6562 ALOGW("Skipping screen capture because of invalid render area.");
6563 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006564 captureListener->onScreenCaptureCompleted(captureResults);
Sally Qi59a9f502021-10-12 18:53:23 +00006565 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()})
6566 .share();
chaviw03900772020-08-18 12:34:51 -07006567 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006568
Sally Qi59a9f502021-10-12 18:53:23 +00006569 std::shared_future<renderengine::RenderEngineResult> renderEngineResultFuture;
6570
chaviw03900772020-08-18 12:34:51 -07006571 renderArea->render([&] {
Sally Qi59a9f502021-10-12 18:53:23 +00006572 renderEngineResultFuture =
Robert Carr12a3b9b2022-03-10 09:55:29 -08006573 renderScreenImpl(*renderArea, traverseLayers, buffer,
Sally Qi59a9f502021-10-12 18:53:23 +00006574 canCaptureBlackoutContent, regionSampling, grayscale,
6575 captureResults);
chaviw03900772020-08-18 12:34:51 -07006576 });
Sally Qi59a9f502021-10-12 18:53:23 +00006577 // spring up a thread to unblock SF main thread and wait for
6578 // RenderEngineResult to be available
6579 if (captureListener != nullptr) {
6580 std::async([=]() mutable {
6581 ATRACE_NAME("captureListener is nonnull!");
6582 auto& [status, drawFence] = renderEngineResultFuture.get();
6583 captureResults.result = status;
6584 captureResults.fence = new Fence(dup(drawFence));
6585 captureListener->onScreenCaptureCompleted(captureResults);
6586 });
6587 }
6588 return renderEngineResultFuture;
6589 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006590
Sally Qi59a9f502021-10-12 18:53:23 +00006591 // flatten scheduleResultFuture object to single shared_future object
6592 if (captureListener == nullptr) {
6593 std::future<renderengine::RenderEngineResult> captureScreenResultFuture =
6594 ftl::chain(std::move(scheduleResultFuture))
6595 .then([=](std::shared_future<renderengine::RenderEngineResult> futureObject)
6596 -> renderengine::RenderEngineResult {
6597 auto& [status, drawFence] = futureObject.get();
6598 return {status, base::unique_fd(dup(drawFence))};
6599 });
6600 return captureScreenResultFuture.share();
6601 } else {
6602 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()}).share();
6603 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006604}
6605
Robert Carr12a3b9b2022-03-10 09:55:29 -08006606std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006607 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006608 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6609 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6610 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006611 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006612
chaviw426b5c02020-07-27 11:20:15 -07006613 traverseLayers([&](Layer* layer) {
6614 captureResults.capturedSecureLayers =
6615 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6616 });
6617
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006618 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006619
chaviw426b5c02020-07-27 11:20:15 -07006620 // We allow the system server to take screenshots of secure layers for
6621 // use in situations like the Screen-rotation animation and place
6622 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006623 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006624 ALOGW("FB is protected: PERMISSION_DENIED");
Sally Qi59a9f502021-10-12 18:53:23 +00006625 return ftl::yield<renderengine::RenderEngineResult>({PERMISSION_DENIED, base::unique_fd()})
6626 .share();
chaviw426b5c02020-07-27 11:20:15 -07006627 }
6628
Alec Mouria90a5702021-04-16 16:36:21 +00006629 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006630 auto dataspace = renderArea.getReqDataSpace();
6631 auto parent = renderArea.getParentLayer();
6632 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6633 Mutex::Autolock lock(mStateLock);
6634 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6635 return display.getLayerStack() == layerStack;
6636 });
6637 if (!display) {
6638 // If the layer is not on a display, use the dataspace for the default display.
6639 display = getDefaultDisplayDeviceLocked();
6640 }
6641
6642 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6643 dataspace = pickDataspaceFromColorMode(colorMode);
6644 }
6645 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006646
chaviwa76b2712017-09-20 12:02:26 -07006647 const auto reqWidth = renderArea.getReqWidth();
6648 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006649 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006650 const auto transform = renderArea.getTransform();
6651 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006652 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006653
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006654 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006655 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006656
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006657 // assume that bounds are never offset, and that they are the same as the
6658 // buffer bounds.
6659 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006660 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006661 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006662
Robert Carr12a3b9b2022-03-10 09:55:29 -08006663 clientCompositionDisplay.outputDataspace = dataspace;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006664 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006665
chaviw17ac24b2021-01-28 18:50:05 -08006666 const float colorSaturation = grayscale ? 0 : 1;
6667 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6668
chaviw50da5042018-04-09 13:49:37 -07006669 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006670
Vishnu Nair9b079a22020-01-21 14:36:08 -08006671 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006672 fillLayer.source.buffer.buffer = nullptr;
6673 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006674 fillLayer.geometry.boundaries =
6675 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006676 fillLayer.alpha = half(alpha);
6677 clientCompositionLayers.push_back(fillLayer);
6678
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006679 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006680 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006681 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006682 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006683 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006684
Lloyd Piquef16688f2019-02-19 17:47:57 -08006685 Region clip(renderArea.getBounds());
6686 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6687 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006688 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006689 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006690 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006691 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006692 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006693 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006694 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006695 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006696 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6697 BlurSetting::Disabled
6698 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6699 BlurSetting::Enabled,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006700 DisplayDevice::sDefaultMaxLumiance,
6701
Lloyd Piquef16688f2019-02-19 17:47:57 -08006702 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006703 std::vector<compositionengine::LayerFE::LayerSettings> results =
6704 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006705 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006706 for (auto& settings : results) {
6707 settings.geometry.positionTransform =
6708 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006709 // There's no need to process blurs when we're executing region sampling,
6710 // we're just trying to understand what we're drawing, and doing so without
6711 // blurs is already a pretty good approximation.
6712 if (regionSampling) {
6713 settings.backgroundBlurRadius = 0;
6714 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07006715 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006716
Yichi Chen40773d92020-04-01 10:10:18 +08006717 clientCompositionLayers.insert(clientCompositionLayers.end(),
6718 std::make_move_iterator(results.begin()),
6719 std::make_move_iterator(results.end()));
6720 renderedLayers.push_back(layer);
6721 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006722
chaviwa76b2712017-09-20 12:02:26 -07006723 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006724
Sally Qi59a9f502021-10-12 18:53:23 +00006725 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6726 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006727 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006728 std::back_inserter(clientRenderEngineLayers),
6729 [](compositionengine::LayerFE::LayerSettings& settings)
6730 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006731
Alec Mouri6338c9d2019-02-07 16:57:51 -08006732 // Use an empty fence for the buffer fence, since we just created the buffer so
6733 // there is no need for synchronization with the GPU.
6734 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006735 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006736
Alec Mouria90a5702021-04-16 16:36:21 +00006737 const constexpr bool kUseFramebufferCache = false;
Sally Qi59a9f502021-10-12 18:53:23 +00006738 std::future<renderengine::RenderEngineResult> drawLayersResult =
6739 getRenderEngine().drawLayers(clientCompositionDisplay, clientRenderEngineLayers, buffer,
6740 kUseFramebufferCache, std::move(bufferFence));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006741
Sally Qi59a9f502021-10-12 18:53:23 +00006742 std::shared_future<renderengine::RenderEngineResult> drawLayersResultFuture =
6743 drawLayersResult.share(); // drawLayersResult will be moved to shared one
6744
6745 for (auto* layer : renderedLayers) {
6746 // make a copy of shared_future object for each layer
6747 layer->onLayerDisplayed(drawLayersResultFuture);
Yichi Chen40773d92020-04-01 10:10:18 +08006748 }
Ady Abraham99599942021-01-27 20:27:23 -08006749
Peiyong Lin05cc0112020-10-14 16:16:37 -07006750 // Always switch back to unprotected context.
6751 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006752
Sally Qi59a9f502021-10-12 18:53:23 +00006753 return drawLayersResultFuture;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006754}
6755
chaviwbf023a62021-06-07 16:00:06 -05006756void SurfaceFlinger::windowInfosReported() {
chaviw95ef3c42019-02-14 10:55:09 -08006757 Mutex::Autolock _l(mStateLock);
Arthur Hung2274a312021-04-28 15:13:06 +00006758 signalSynchronousTransactions(CountDownLatch::eSyncInputWindows);
chaviw95ef3c42019-02-14 10:55:09 -08006759}
chaviw5f21a5e2019-02-14 10:00:34 -08006760
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006761// ---------------------------------------------------------------------------
6762
Edgar Arriaga844fa672020-01-16 14:21:42 -08006763void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6764 layersSortedByZ.traverse(visitor);
6765}
6766
Dan Stoza412903f2017-04-27 13:42:17 -07006767void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6768 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006769}
6770
Dan Stoza412903f2017-04-27 13:42:17 -07006771void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6772 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006773}
6774
chaviw4b9d5e12020-08-04 18:30:35 -07006775void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006776 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006777 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006778 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006779 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006780 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006781 continue;
6782 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006783 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006784 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006785 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006786 return;
6787 }
chaviwa76b2712017-09-20 12:02:26 -07006788 if (!layer->isVisible()) {
6789 return;
6790 }
chaviw4b9d5e12020-08-04 18:30:35 -07006791 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6792 return;
6793 }
chaviwa76b2712017-09-20 12:02:26 -07006794 visitor(layer);
6795 });
6796 }
6797}
6798
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006799status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006800 const sp<DisplayDevice>& display,
6801 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006802 Mutex::Autolock lock(mStateLock);
6803
Ady Abrahamfb853662021-04-09 11:46:40 -07006804 if (mDebugDisplayModeSetByBackdoor) {
6805 // ignore this request as mode is overridden by backdoor
6806 return NO_ERROR;
6807 }
6808
Ady Abraham3efa3942021-06-24 19:01:25 -07006809 status_t setPolicyResult = overridePolicy
6810 ? display->refreshRateConfigs().setOverridePolicy(policy)
6811 : display->refreshRateConfigs().setDisplayManagerPolicy(*policy);
6812 if (setPolicyResult < 0) {
6813 return BAD_VALUE;
6814 }
6815 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6816 return NO_ERROR;
6817 }
6818
Ady Abraham3efa3942021-06-24 19:01:25 -07006819 scheduler::RefreshRateConfigs::Policy currentPolicy =
6820 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006821
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006822 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006823
Ana Krulecb9afd792020-06-11 13:16:15 -07006824 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6825 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006826 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006827 if (isDisplayActiveLocked(display)) {
6828 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6829 toggleKernelIdleTimer();
6830 } else {
6831 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6832 }
Ady Abraham838de062019-02-04 10:24:03 -08006833
Ady Abraham690f4612021-07-01 23:24:03 -07006834 const DisplayModePtr preferredDisplayMode = [&] {
6835 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6836 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6837 return schedulerMode;
6838 }
6839
6840 return display->getMode(currentPolicy.defaultMode);
6841 }();
6842
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006843 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006844 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006845
Ady Abraham690f4612021-07-01 23:24:03 -07006846 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006847 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006848 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006849 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006850 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006851 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006852 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006853 }
6854
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006855 return NO_ERROR;
6856}
6857
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006858status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6859 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6860 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6861 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006862 ATRACE_CALL();
6863
6864 if (!displayToken) {
6865 return BAD_VALUE;
6866 }
6867
Dominik Laskowski756b7892021-08-04 12:53:59 -07006868 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006869 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006870 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006871 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006872 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006873 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006874 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006875 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006876 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006877 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006878 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006879 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006880 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006881 {Fps::fromValue(primaryRefreshRateMin),
6882 Fps::fromValue(primaryRefreshRateMax)},
6883 {Fps::fromValue(appRequestRefreshRateMin),
6884 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006885 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006886
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006887 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006888 }
6889 });
6890
6891 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006892}
6893
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006894status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6895 ui::DisplayModeId* outDefaultMode,
6896 bool* outAllowGroupSwitching,
6897 float* outPrimaryRefreshRateMin,
6898 float* outPrimaryRefreshRateMax,
6899 float* outAppRequestRefreshRateMin,
6900 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006901 ATRACE_CALL();
6902
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006903 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006904 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006905 return BAD_VALUE;
6906 }
6907
6908 Mutex::Autolock lock(mStateLock);
6909 const auto display = getDisplayDeviceLocked(displayToken);
6910 if (!display) {
6911 return NAME_NOT_FOUND;
6912 }
6913
Ady Abraham3efa3942021-06-24 19:01:25 -07006914 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006915 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006916 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006917
6918 scheduler::RefreshRateConfigs::Policy policy =
6919 display->refreshRateConfigs().getDisplayManagerPolicy();
6920 *outDefaultMode = policy.defaultMode.value();
6921 *outAllowGroupSwitching = policy.allowGroupSwitching;
6922 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6923 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6924 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6925 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6926 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006927}
6928
Vishnu Nairf9096652021-07-20 18:49:42 -07006929wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6930 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006931}
6932
Dominik Laskowski75848362019-11-11 17:57:20 -08006933void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006934 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006935 if (!layer->isRemovedFromCurrentState()) {
6936 mScheduler->registerLayer(layer);
6937 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006938}
6939
6940void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6941 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006942 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006943 if (!layer->isRemovedFromCurrentState()) {
6944 mScheduler->deregisterLayer(layer);
6945 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08006946 if (mTransactionTracing) {
6947 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08006948 }
Valerie Hauc5686802019-11-22 14:18:09 -08006949}
6950
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006951void SurfaceFlinger::onLayerUpdate() {
6952 scheduleCommit(FrameHint::kActive);
6953}
6954
Valerie Hauc5686802019-11-22 14:18:09 -08006955// WARNING: ONLY CALL THIS FROM LAYER DTOR
6956// Here we add children in the current state to offscreen layers and remove the
6957// layer itself from the offscreen layer list. Since
6958// this is the dtor, it is safe to access the current state. This keeps us
6959// from dangling children layers such that they are not reachable from the
6960// Drawing state nor the offscreen layer list
6961// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07006962void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08006963 for (auto& child : layer->getCurrentChildren()) {
6964 mOffscreenLayers.emplace(child.get());
6965 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006966 mOffscreenLayers.erase(layer);
6967}
6968
Robert Carr867be372021-06-29 17:36:02 -07006969void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6970 mOffscreenLayers.erase(layer);
6971}
6972
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006973status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6974 float lightPosY, float lightPosZ,
6975 float lightRadius) {
6976 Mutex::Autolock _l(mStateLock);
6977 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6978 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6979 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6980 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6981 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6982
6983 // these values are overridden when calculating the shadow settings for a layer.
6984 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6985 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006986 return NO_ERROR;
6987}
6988
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006989const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6990 const {
6991 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6992 // on the work to remove the table in that bug rather than adding more to
6993 // it.
6994 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006995 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6996 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6997 };
6998 return genericLayerMetadataKeyMap;
6999}
7000
Steven Thomas62a4cf82020-01-31 12:04:03 -08007001status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
Marin Shalamanovc5986772021-03-16 16:09:49 +01007002 int8_t compatibility, int8_t changeFrameRateStrategy) {
7003 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
7004 "SurfaceFlinger::setFrameRate")) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08007005 return BAD_VALUE;
7006 }
7007
Dominik Laskowski756b7892021-08-04 12:53:59 -07007008 static_cast<void>(mScheduler->schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07007009 Mutex::Autolock lock(mStateLock);
7010 if (authenticateSurfaceTextureLocked(surface)) {
7011 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
Ady Abraham162f6432020-10-08 18:40:47 +00007012 if (layer == nullptr) {
7013 ALOGE("Attempt to set frame rate on a layer that no longer exists");
7014 return BAD_VALUE;
7015 }
Marin Shalamanovc5986772021-03-16 16:09:49 +01007016 const auto strategy =
7017 Layer::FrameRate::convertChangeFrameRateStrategy(changeFrameRateStrategy);
Ady Abraham60e42ea2020-03-09 19:17:31 -07007018 if (layer->setFrameRate(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007019 Layer::FrameRate(Fps::fromValue(frameRate),
Marin Shalamanov46084422020-10-13 12:33:42 +02007020 Layer::FrameRate::convertCompatibility(compatibility),
Marin Shalamanovc5986772021-03-16 16:09:49 +01007021 strategy))) {
Ady Abraham60e42ea2020-03-09 19:17:31 -07007022 setTransactionFlags(eTraversalNeeded);
7023 }
7024 } else {
7025 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
7026 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08007027 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07007028 return NO_ERROR;
7029 }));
7030
Steven Thomas62a4cf82020-01-31 12:04:03 -08007031 return NO_ERROR;
7032}
7033
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007034status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7035 PhysicalDisplayId displayId = [&]() {
7036 Mutex::Autolock lock(mStateLock);
7037 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7038 }();
7039
7040 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7041 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7042 return NO_ERROR;
7043}
7044
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10007045status_t SurfaceFlinger::setFrameTimelineInfo(const sp<IGraphicBufferProducer>& surface,
7046 const FrameTimelineInfo& frameTimelineInfo) {
Ady Abraham74e17562020-08-24 18:18:19 -07007047 Mutex::Autolock lock(mStateLock);
7048 if (!authenticateSurfaceTextureLocked(surface)) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10007049 ALOGE("Attempt to set frame timeline info on an unrecognized IGraphicBufferProducer");
Ady Abraham74e17562020-08-24 18:18:19 -07007050 return BAD_VALUE;
7051 }
7052
7053 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
Ady Abrahamfdf1bff2020-09-28 11:27:30 -07007054 if (layer == nullptr) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10007055 ALOGE("Attempt to set frame timeline info on a layer that no longer exists");
Ady Abrahamfdf1bff2020-09-28 11:27:30 -07007056 return BAD_VALUE;
7057 }
7058
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10007059 layer->setFrameTimelineInfoForBuffer(frameTimelineInfo);
Ady Abraham74e17562020-08-24 18:18:19 -07007060 return NO_ERROR;
7061}
7062
Dominik Laskowski20134642020-04-20 22:36:44 -07007063void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007064 for (const auto& [ignored, display] : mDisplays) {
7065 if (display->isInternal()) {
7066 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007067 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007068 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007069}
7070
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007071status_t SurfaceFlinger::addTransactionTraceListener(
7072 const sp<gui::ITransactionTraceListener>& listener) {
7073 if (!listener) {
7074 return BAD_VALUE;
7075 }
7076
7077 mInterceptor->addTransactionTraceListener(listener);
7078
7079 return NO_ERROR;
7080}
7081
Huihong Luo02186fb2022-02-23 14:21:54 -08007082int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007083 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007084}
7085
Ady Abraham899dcdb2021-06-15 16:56:21 -07007086int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7087 std::chrono::nanoseconds presentLatency) {
7088 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7089 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007090 pipelineDepth++;
7091 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007092 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007093}
7094
Ady Abraham899dcdb2021-06-15 16:56:21 -07007095status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007096 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007097
7098 if (!getHwComposer().isHeadless()) {
7099 if (const auto display = getDefaultDisplayDevice()) {
7100 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007101 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007102 }
7103
7104 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007105 return NO_ERROR;
7106}
7107
rnleeed20fa42021-08-10 18:00:03 -07007108uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007109 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007110
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007111 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7112 refreshRate = *frameRateOverride;
7113 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007114 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007115 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007116 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007117 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007118
Ady Abraham899dcdb2021-06-15 16:56:21 -07007119 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7120}
7121
7122int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7123 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7124 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7125 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7126}
7127
Vishnu Nair6b591152021-10-08 11:45:14 -07007128void TransactionState::traverseStatesWithBuffers(
Vishnu Nair83df0342021-03-30 11:50:44 -07007129 std::function<void(const layer_state_t&)> visitor) {
7130 for (const auto& state : states) {
Ady Abraham6e8e3642021-07-08 19:44:07 -07007131 if (state.state.hasBufferChanges() && state.state.hasValidBuffer() && state.state.surface) {
Vishnu Nair83df0342021-03-30 11:50:44 -07007132 visitor(state.state);
7133 }
7134 }
7135}
7136
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007137void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state) {
7138 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007139 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007140 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7141 return;
arthurhungdba591c2021-02-08 17:28:49 +08007142 }
7143
7144 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007145 bool addToRoot = state.addToRoot;
7146 if (state.initialParent != nullptr) {
7147 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007148 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007149 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007150 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007151 }
arthurhungdba591c2021-02-08 17:28:49 +08007152 }
7153
Garfield Tand712ad32021-10-27 13:44:22 -07007154 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007155 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007156 mCurrentState.layersSortedByZ.add(layer);
7157 } else if (parent == nullptr) {
7158 layer->onRemovedFromCurrentState();
7159 } else if (parent->isRemovedFromCurrentState()) {
7160 parent->addChild(layer);
7161 layer->onRemovedFromCurrentState();
7162 } else {
7163 parent->addChild(layer);
7164 }
7165
Ady Abraham1273ac12021-08-26 17:31:53 -07007166 layer->updateTransformHint(mActiveDisplayTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +08007167
Arthur Hung23e07502021-10-15 11:58:19 +00007168 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007169}
Ady Abraham562c2712021-05-07 15:10:42 -07007170
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007171void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007172 if (!mLumaSampling || !mRegionSamplingThread) {
7173 return;
7174 }
7175
Dominik Laskowski756b7892021-08-04 12:53:59 -07007176 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007177}
7178
Ady Abrahamed3290f2021-05-17 15:12:14 -07007179void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7180 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7181 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7182}
7183
7184void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7185 ATRACE_CALL();
7186
Ady Abrahamdb036a82021-07-16 14:18:34 -07007187 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7188 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7189 }
7190
Ady Abrahamed3290f2021-05-17 15:12:14 -07007191 if (!activeDisplay) {
7192 ALOGE("%s: activeDisplay is null", __func__);
7193 return;
7194 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007195 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007196 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007197 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007198 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007199 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007200 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007201 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007202
7203 // Update the kernel timer for the current active display, since the policy
7204 // for this display might have changed when it was not the active display.
7205 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007206}
7207
chaviw60c9d3e2021-06-04 12:52:17 -05007208status_t SurfaceFlinger::addWindowInfosListener(
7209 const sp<IWindowInfosListener>& windowInfosListener) const {
7210 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7211 return NO_ERROR;
7212}
7213
7214status_t SurfaceFlinger::removeWindowInfosListener(
7215 const sp<IWindowInfosListener>& windowInfosListener) const {
7216 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7217 return NO_ERROR;
7218}
7219
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007220std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7221 const BufferData& bufferData, const char* layerName) const {
7222 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7223 bool bufferSizeExceedsLimit = false;
7224 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7225 if (cacheIdChanged && bufferData.buffer != nullptr) {
7226 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7227 bufferData.buffer->getHeight());
7228 if (!bufferSizeExceedsLimit) {
7229 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7230 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7231 }
7232 } else if (cacheIdChanged) {
7233 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7234 } else if (bufferData.buffer != nullptr) {
7235 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7236 bufferData.buffer->getHeight());
7237 if (!bufferSizeExceedsLimit) {
7238 buffer = std::make_shared<
7239 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7240 renderengine::impl::ExternalTexture::
7241 Usage::READABLE);
7242 }
7243 }
7244 ALOGE_IF(bufferSizeExceedsLimit,
7245 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7246 "limit.",
7247 layerName);
7248 return buffer;
7249}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007250
7251bool SurfaceFlinger::commitCreatedLayers() {
7252 std::vector<LayerCreatedState> createdLayers;
7253 {
7254 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7255 createdLayers = std::move(mCreatedLayers);
7256 mCreatedLayers.clear();
7257 if (createdLayers.size() == 0) {
7258 return false;
7259 }
7260 }
7261
7262 Mutex::Autolock _l(mStateLock);
7263 for (const auto& createdLayer : createdLayers) {
7264 handleLayerCreatedLocked(createdLayer);
7265 }
7266 createdLayers.clear();
7267 mLayersAdded = true;
7268 return true;
7269}
Huihong Luof5029222021-12-16 14:33:46 -08007270
7271// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007272
7273binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7274 sp<IBinder>* outDisplay) {
7275 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007276 if (status != OK) {
7277 return binder::Status::fromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007278 }
Huihong Luo37396db2022-02-15 10:43:00 -08007279 String8 displayName8 = String8::format("%s", displayName.c_str());
7280 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7281 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007282}
7283
7284binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7285 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007286 if (status != OK) {
7287 return binder::Status::fromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007288 }
Huihong Luo37396db2022-02-15 10:43:00 -08007289 mFlinger->destroyDisplay(display);
7290 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007291}
7292
7293binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7294 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7295 std::vector<int64_t> displayIds;
7296 displayIds.reserve(physicalDisplayIds.size());
7297 for (auto item : physicalDisplayIds) {
7298 displayIds.push_back(static_cast<int64_t>(item.value));
7299 }
7300 *outDisplayIds = displayIds;
7301 return binder::Status::ok();
7302}
7303
7304binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7305 status_t status = checkAccessPermission();
7306 if (status != OK) {
7307 return binder::Status::fromStatusT(status);
7308 }
7309
7310 PhysicalDisplayId id;
7311 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7312 if (status == NO_ERROR) {
7313 *outDisplayId = id.value;
7314 }
7315 return binder::Status::fromStatusT(status);
7316}
7317
7318binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7319 sp<IBinder>* outDisplay) {
7320 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7321 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7322 return binder::Status::ok();
7323}
7324
Huihong Luo37396db2022-02-15 10:43:00 -08007325binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7326 status_t status = checkAccessPermission();
7327 if (status != OK) {
7328 return binder::Status::fromStatusT(status);
7329 }
7330 mFlinger->setPowerMode(display, mode);
7331 return binder::Status::ok();
7332}
7333
Huihong Luo0a81aa32022-02-22 16:02:36 -08007334binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7335 std::vector<FrameEvent>* outSupported) {
7336 status_t status;
7337 if (!outSupported) {
7338 status = UNEXPECTED_NULL;
7339 } else {
7340 outSupported->clear();
7341 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7342 }
7343 return binder::Status::fromStatusT(status);
7344}
7345
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007346binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7347 gui::DisplayStatInfo* outStatInfo) {
7348 DisplayStatInfo statInfo;
7349 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7350 if (status == NO_ERROR) {
7351 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7352 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7353 }
7354 return binder::Status::fromStatusT(status);
7355}
7356
7357binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7358 gui::DisplayState* outState) {
7359 ui::DisplayState state;
7360 status_t status = mFlinger->getDisplayState(display, &state);
7361 if (status == NO_ERROR) {
7362 outState->layerStack = state.layerStack.id;
7363 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7364 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7365 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7366 }
7367 return binder::Status::fromStatusT(status);
7368}
7369
Huihong Luoa79ddf42022-02-17 00:01:38 -08007370binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7371 gui::StaticDisplayInfo* outInfo) {
7372 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7373 ui::StaticDisplayInfo info;
7374 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7375 if (status == NO_ERROR) {
7376 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7377 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7378 outInfo->density = info.density;
7379 outInfo->secure = info.secure;
7380 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7381
7382 gui::DeviceProductInfo dinfo;
7383 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7384 dinfo.name = std::move(dpi->name);
7385 dinfo.manufacturerPnpId =
7386 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7387 dinfo.productId = dpi->productId;
7388 if (const auto* model =
7389 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7390 gui::DeviceProductInfo::ModelYear modelYear;
7391 modelYear.year = model->year;
7392 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7393 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7394 &dpi->manufactureOrModelDate)) {
7395 gui::DeviceProductInfo::ManufactureYear date;
7396 date.modelYear.year = manufacture->year;
7397 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7398 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7399 &dpi->manufactureOrModelDate)) {
7400 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7401 date.manufactureYear.modelYear.year = manufacture->year;
7402 date.week = manufacture->week;
7403 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7404 }
7405
7406 outInfo->deviceProductInfo = dinfo;
7407 }
7408 return binder::Status::fromStatusT(status);
7409}
7410
Huihong Luo38603fd2022-02-21 14:32:54 -08007411binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7412 gui::DynamicDisplayInfo* outInfo) {
7413 ui::DynamicDisplayInfo info;
7414 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7415 if (status == NO_ERROR) {
7416 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7417 outInfo->supportedDisplayModes.clear();
7418 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7419 for (const auto& mode : info.supportedDisplayModes) {
7420 gui::DisplayMode outMode;
7421 outMode.id = mode.id;
7422 outMode.resolution.width = mode.resolution.width;
7423 outMode.resolution.height = mode.resolution.height;
7424 outMode.xDpi = mode.xDpi;
7425 outMode.yDpi = mode.yDpi;
7426 outMode.refreshRate = mode.refreshRate;
7427 outMode.appVsyncOffset = mode.appVsyncOffset;
7428 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7429 outMode.presentationDeadline = mode.presentationDeadline;
7430 outMode.group = mode.group;
7431 outInfo->supportedDisplayModes.push_back(outMode);
7432 }
7433
7434 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7435
7436 outInfo->supportedColorModes.clear();
7437 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7438 for (const auto& cmode : info.supportedColorModes) {
7439 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7440 }
7441
7442 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7443
7444 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7445 hdrCapabilities.supportedHdrTypes.clear();
7446 hdrCapabilities.supportedHdrTypes.reserve(
7447 info.hdrCapabilities.getSupportedHdrTypes().size());
7448 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7449 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7450 }
7451 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7452 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7453 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7454
7455 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7456 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7457 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7458 }
7459 return binder::Status::fromStatusT(status);
7460}
7461
Huihong Luoca3d9a42022-02-22 11:07:34 -08007462binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7463 gui::DisplayPrimaries* outPrimaries) {
7464 ui::DisplayPrimaries primaries;
7465 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7466 if (status == NO_ERROR) {
7467 outPrimaries->red.X = primaries.red.X;
7468 outPrimaries->red.Y = primaries.red.Y;
7469 outPrimaries->red.Z = primaries.red.Z;
7470
7471 outPrimaries->green.X = primaries.green.X;
7472 outPrimaries->green.Y = primaries.green.Y;
7473 outPrimaries->green.Z = primaries.green.Z;
7474
7475 outPrimaries->blue.X = primaries.blue.X;
7476 outPrimaries->blue.Y = primaries.blue.Y;
7477 outPrimaries->blue.Z = primaries.blue.Z;
7478
7479 outPrimaries->white.X = primaries.white.X;
7480 outPrimaries->white.Y = primaries.white.Y;
7481 outPrimaries->white.Z = primaries.white.Z;
7482 }
7483 return binder::Status::fromStatusT(status);
7484}
7485
7486binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7487 status_t status = checkAccessPermission();
7488 if (status == OK) {
7489 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7490 }
7491 return binder::Status::fromStatusT(status);
7492}
7493
7494binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7495 int displayModeId) {
7496 status_t status = checkAccessPermission();
7497 if (status == OK) {
7498 status = mFlinger->setBootDisplayMode(display,
7499 static_cast<ui::DisplayModeId>(displayModeId));
7500 }
7501 return binder::Status::fromStatusT(status);
7502}
7503
Huihong Luo37396db2022-02-15 10:43:00 -08007504binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7505 status_t status = checkAccessPermission();
7506 if (status == OK) {
7507 status = mFlinger->clearBootDisplayMode(display);
7508 }
7509 return binder::Status::fromStatusT(status);
7510}
7511
7512binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7513 status_t status = checkAccessPermission();
7514 if (status == OK) {
7515 status = mFlinger->getBootDisplayModeSupport(outMode);
7516 }
7517 return binder::Status::fromStatusT(status);
7518}
7519
7520binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7521 status_t status = checkAccessPermission();
7522 if (status != OK) {
7523 return binder::Status::fromStatusT(status);
7524 }
7525 mFlinger->setAutoLowLatencyMode(display, on);
7526 return binder::Status::ok();
7527}
7528
7529binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7530 status_t status = checkAccessPermission();
7531 if (status != OK) {
7532 return binder::Status::fromStatusT(status);
7533 }
7534 mFlinger->setGameContentType(display, on);
7535 return binder::Status::ok();
7536}
7537
Huihong Luof5029222021-12-16 14:33:46 -08007538binder::Status SurfaceComposerAIDL::captureDisplay(
7539 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7540 status_t status = mFlinger->captureDisplay(args, captureListener);
7541 return binder::Status::fromStatusT(status);
7542}
7543
7544binder::Status SurfaceComposerAIDL::captureDisplayById(
7545 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7546 status_t status;
7547 IPCThreadState* ipc = IPCThreadState::self();
7548 const int uid = ipc->getCallingUid();
7549 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7550 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7551 status = mFlinger->captureDisplay(*id, captureListener);
7552 } else {
7553 status = PERMISSION_DENIED;
7554 }
7555 return binder::Status::fromStatusT(status);
7556}
7557
7558binder::Status SurfaceComposerAIDL::captureLayers(
7559 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7560 status_t status = mFlinger->captureLayers(args, captureListener);
7561 return binder::Status::fromStatusT(status);
7562}
7563
Huihong Luo4ed1c912022-02-22 14:30:01 -08007564binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7565 status_t status = checkAccessPermission();
7566 if (status == OK) {
7567 status = mFlinger->clearAnimationFrameStats();
7568 }
7569 return binder::Status::fromStatusT(status);
7570}
7571
7572binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7573 status_t status = checkAccessPermission();
7574 if (status != OK) {
7575 return binder::Status::fromStatusT(status);
7576 }
7577
7578 FrameStats stats;
7579 status = mFlinger->getAnimationFrameStats(&stats);
7580 if (status == NO_ERROR) {
7581 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7582 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7583 for (const auto& t : stats.desiredPresentTimesNano) {
7584 outStats->desiredPresentTimesNano.push_back(t);
7585 }
7586 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7587 for (const auto& t : stats.actualPresentTimesNano) {
7588 outStats->actualPresentTimesNano.push_back(t);
7589 }
7590 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7591 for (const auto& t : stats.frameReadyTimesNano) {
7592 outStats->frameReadyTimesNano.push_back(t);
7593 }
7594 }
7595 return binder::Status::fromStatusT(status);
7596}
7597
Huihong Luo05539a12022-02-23 10:29:40 -08007598binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7599 const std::vector<int32_t>& hdrTypes) {
7600 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7601 // permission dynamically. Don't use the permission cache for this check.
7602 status_t status = checkAccessPermission(false);
7603 if (status != OK) {
7604 return binder::Status::fromStatusT(status);
7605 }
7606
7607 std::vector<ui::Hdr> hdrTypesVector;
7608 for (int32_t i : hdrTypes) {
7609 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7610 }
7611 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
7612 return binder::Status::fromStatusT(status);
7613}
7614
7615binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7616 status_t status;
7617 const int uid = IPCThreadState::self()->getCallingUid();
7618 if (uid != AID_SYSTEM) {
7619 status = PERMISSION_DENIED;
7620 } else {
7621 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7622 }
7623 return binder::Status::fromStatusT(status);
7624}
7625
7626binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7627 if (!mFlinger->hasMockHwc()) {
7628 return binder::Status::fromStatusT(PERMISSION_DENIED);
7629 }
7630
7631 status_t status = checkAccessPermission();
7632 if (status == OK) {
7633 status = mFlinger->enableVSyncInjections(enable);
7634 }
7635 return binder::Status::fromStatusT(status);
7636}
7637
7638binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
7639 if (!mFlinger->hasMockHwc()) {
7640 return binder::Status::fromStatusT(PERMISSION_DENIED);
7641 }
7642
7643 status_t status = checkAccessPermission();
7644 if (status == OK) {
7645 status = mFlinger->injectVSync(when);
7646 }
7647 return binder::Status::fromStatusT(status);
7648}
7649
7650binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7651 if (!outLayers) {
7652 return binder::Status::fromStatusT(UNEXPECTED_NULL);
7653 }
7654
7655 IPCThreadState* ipc = IPCThreadState::self();
7656 const int pid = ipc->getCallingPid();
7657 const int uid = ipc->getCallingUid();
7658 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7659 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
7660 return binder::Status::fromStatusT(PERMISSION_DENIED);
7661 }
7662 status_t status = mFlinger->getLayerDebugInfo(outLayers);
7663 return binder::Status::fromStatusT(status);
7664}
7665
7666binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7667 status_t status = mFlinger->getColorManagement(outGetColorManagement);
7668 return binder::Status::fromStatusT(status);
7669}
7670
7671binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7672 ui::Dataspace dataspace;
7673 ui::PixelFormat pixelFormat;
7674 ui::Dataspace wideColorGamutDataspace;
7675 ui::PixelFormat wideColorGamutPixelFormat;
7676 status_t status =
7677 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7678 &wideColorGamutPixelFormat);
7679 if (status == NO_ERROR) {
7680 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7681 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7682 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7683 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7684 }
7685 return binder::Status::fromStatusT(status);
7686}
7687
7688binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7689 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7690 status_t status = checkAccessPermission();
7691 if (status != OK) {
7692 return binder::Status::fromStatusT(status);
7693 }
7694
7695 ui::PixelFormat format;
7696 ui::Dataspace dataspace;
7697 uint8_t componentMask;
7698 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7699 &componentMask);
7700 if (status == NO_ERROR) {
7701 outAttrs->format = static_cast<int32_t>(format);
7702 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7703 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7704 }
7705 return binder::Status::fromStatusT(status);
7706}
7707
7708binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7709 bool enable,
7710 int8_t componentMask,
7711 int64_t maxFrames) {
7712 status_t status = checkAccessPermission();
7713 if (status == OK) {
7714 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7715 static_cast<uint8_t>(componentMask),
7716 static_cast<uint64_t>(maxFrames));
7717 }
7718 return binder::Status::fromStatusT(status);
7719}
7720
7721binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7722 status_t status = mFlinger->getProtectedContentSupport(outSupported);
7723 return binder::Status::fromStatusT(status);
7724}
7725
Huihong Luo37396db2022-02-15 10:43:00 -08007726binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7727 bool* outIsWideColorDisplay) {
7728 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
7729 return binder::Status::fromStatusT(status);
7730}
7731
Huihong Luo02186fb2022-02-23 14:21:54 -08007732binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7733 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7734 const sp<gui::IRegionSamplingListener>& listener) {
7735 status_t status = checkReadFrameBufferPermission();
7736 if (status != OK) {
7737 return binder::Status::fromStatusT(status);
7738 }
7739 android::Rect rect;
7740 rect.left = samplingArea.left;
7741 rect.top = samplingArea.top;
7742 rect.right = samplingArea.right;
7743 rect.bottom = samplingArea.bottom;
7744 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
7745 return binder::Status::fromStatusT(status);
7746}
7747
7748binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7749 const sp<gui::IRegionSamplingListener>& listener) {
7750 status_t status = checkReadFrameBufferPermission();
7751 if (status == OK) {
7752 status = mFlinger->removeRegionSamplingListener(listener);
7753 }
7754 return binder::Status::fromStatusT(status);
7755}
7756
7757binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7758 const sp<gui::IFpsListener>& listener) {
7759 status_t status = checkReadFrameBufferPermission();
7760 if (status == OK) {
7761 status = mFlinger->addFpsListener(taskId, listener);
7762 }
7763 return binder::Status::fromStatusT(status);
7764}
7765
7766binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7767 status_t status = checkReadFrameBufferPermission();
7768 if (status == OK) {
7769 status = mFlinger->removeFpsListener(listener);
7770 }
7771 return binder::Status::fromStatusT(status);
7772}
7773
7774binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7775 const sp<gui::ITunnelModeEnabledListener>& listener) {
7776 status_t status = checkAccessPermission();
7777 if (status == OK) {
7778 status = mFlinger->addTunnelModeEnabledListener(listener);
7779 }
7780 return binder::Status::fromStatusT(status);
7781}
7782
7783binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7784 const sp<gui::ITunnelModeEnabledListener>& listener) {
7785 status_t status = checkAccessPermission();
7786 if (status == OK) {
7787 status = mFlinger->removeTunnelModeEnabledListener(listener);
7788 }
7789 return binder::Status::fromStatusT(status);
7790}
7791
7792binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7793 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7794 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7795 float appRequestRefreshRateMax) {
7796 status_t status = checkAccessPermission();
7797 if (status == OK) {
7798 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7799 static_cast<ui::DisplayModeId>(defaultMode),
7800 allowGroupSwitching, primaryRefreshRateMin,
7801 primaryRefreshRateMax,
7802 appRequestRefreshRateMin,
7803 appRequestRefreshRateMax);
7804 }
7805 return binder::Status::fromStatusT(status);
7806}
7807
7808binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7809 gui::DisplayModeSpecs* outSpecs) {
7810 if (!outSpecs) {
7811 return binder::Status::fromStatusT(BAD_VALUE);
7812 }
7813
7814 status_t status = checkAccessPermission();
7815 if (status != OK) {
7816 return binder::Status::fromStatusT(status);
7817 }
7818
7819 ui::DisplayModeId displayModeId;
7820 bool allowGroupSwitching;
7821 float primaryRefreshRateMin;
7822 float primaryRefreshRateMax;
7823 float appRequestRefreshRateMin;
7824 float appRequestRefreshRateMax;
7825 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7826 &allowGroupSwitching, &primaryRefreshRateMin,
7827 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7828 &appRequestRefreshRateMax);
7829 if (status == NO_ERROR) {
7830 outSpecs->defaultMode = displayModeId;
7831 outSpecs->allowGroupSwitching = allowGroupSwitching;
7832 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7833 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7834 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7835 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7836 }
7837
7838 return binder::Status::fromStatusT(status);
7839}
7840
Huihong Luo37396db2022-02-15 10:43:00 -08007841binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7842 bool* outSupport) {
7843 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
7844 return binder::Status::fromStatusT(status);
7845}
7846
7847binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7848 const gui::DisplayBrightness& brightness) {
7849 status_t status = checkControlDisplayBrightnessPermission();
7850 if (status == OK) {
7851 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7852 }
7853 return binder::Status::fromStatusT(status);
7854}
7855
7856binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7857 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7858 status_t status = checkControlDisplayBrightnessPermission();
7859 if (status == OK) {
7860 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7861 }
7862 return binder::Status::fromStatusT(status);
7863}
7864
7865binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7866 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7867 status_t status = checkControlDisplayBrightnessPermission();
7868 if (status == OK) {
7869 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7870 }
7871 return binder::Status::fromStatusT(status);
7872}
7873
7874binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7875 status_t status = checkAccessPermission();
7876 if (status == OK) {
7877 status = mFlinger->notifyPowerBoost(boostId);
7878 }
7879 return binder::Status::fromStatusT(status);
7880}
7881
Huihong Luo02186fb2022-02-23 14:21:54 -08007882binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
7883 const sp<gui::ITransactionTraceListener>& listener) {
7884 status_t status;
7885 IPCThreadState* ipc = IPCThreadState::self();
7886 const int uid = ipc->getCallingUid();
7887 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7888 status = mFlinger->addTransactionTraceListener(listener);
7889 } else {
7890 status = PERMISSION_DENIED;
7891 }
7892 return binder::Status::fromStatusT(status);
7893}
7894
7895binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
7896 *outPriority = mFlinger->getGpuContextPriority();
7897 return binder::Status::ok();
7898}
7899
7900binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
7901 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
7902 return binder::Status::fromStatusT(status);
7903}
7904
7905binder::Status SurfaceComposerAIDL::addWindowInfosListener(
7906 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7907 status_t status;
7908 const int uid = IPCThreadState::self()->getCallingUid();
7909 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7910 status = mFlinger->addWindowInfosListener(windowInfosListener);
7911 } else {
7912 status = PERMISSION_DENIED;
7913 }
7914 return binder::Status::fromStatusT(status);
7915}
7916
7917binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
7918 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7919 status_t status;
7920 const int uid = IPCThreadState::self()->getCallingUid();
7921 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7922 status = mFlinger->removeWindowInfosListener(windowInfosListener);
7923 } else {
7924 status = PERMISSION_DENIED;
7925 }
7926 return binder::Status::fromStatusT(status);
7927}
7928
Huihong Luo07e72362022-02-14 14:26:04 -08007929status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
7930 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
7931 IPCThreadState* ipc = IPCThreadState::self();
7932 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
7933 ipc->getCallingUid());
7934 return PERMISSION_DENIED;
7935 }
7936 return OK;
7937}
7938
Huihong Luo37396db2022-02-15 10:43:00 -08007939status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
7940 IPCThreadState* ipc = IPCThreadState::self();
7941 const int pid = ipc->getCallingPid();
7942 const int uid = ipc->getCallingUid();
7943 if ((uid != AID_GRAPHICS) &&
7944 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
7945 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
7946 return PERMISSION_DENIED;
7947 }
7948 return OK;
7949}
7950
Huihong Luo02186fb2022-02-23 14:21:54 -08007951status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
7952 IPCThreadState* ipc = IPCThreadState::self();
7953 const int pid = ipc->getCallingPid();
7954 const int uid = ipc->getCallingUid();
7955 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
7956 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
7957 return PERMISSION_DENIED;
7958 }
7959 return OK;
7960}
7961
Dominik Laskowski9dab3432019-03-27 13:21:10 -07007962} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07007963
Mathias Agopian3f844832013-08-07 21:24:32 -07007964#if defined(__gl_h_)
7965#error "don't include gl/gl.h in this file"
7966#endif
7967
7968#if defined(__gl2_h_)
7969#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08007970#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08007971
7972// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01007973#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"