blob: d8cfeeebd62cad6b27ac0068cedf7a56154cc635 [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;
Vishnu Nair9cf89262022-02-26 09:17:49 -0800166using CompositionStrategyPredictionState = android::compositionengine::impl::
167 OutputCompositionState::CompositionStrategyPredictionState;
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800168
Yiwei Zhang5434a782018-12-05 18:06:32 -0800169using base::StringAppendF;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -0700170using gui::DisplayInfo;
Huihong Luo6fac5232021-11-22 16:05:23 -0800171using gui::IDisplayEventConnection;
chaviw60c9d3e2021-06-04 12:52:17 -0500172using gui::IWindowInfosListener;
chaviw98318de2021-05-19 16:45:23 -0500173using gui::WindowInfo;
Peiyong Lin9f034472018-03-28 15:29:00 -0700174using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700175using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800176using ui::DisplayPrimaries;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700177using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900178
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800179using KernelIdleTimerController = scheduler::RefreshRateConfigs::KernelIdleTimerController;
180
Peiyong Line9d809e2020-04-14 13:10:48 -0700181namespace hal = android::hardware::graphics::composer::hal;
182
Steven Thomasb02664d2017-07-26 18:48:28 -0700183namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
185#pragma clang diagnostic push
186#pragma clang diagnostic error "-Wswitch-enum"
187
188bool isWideColorMode(const ColorMode colorMode) {
189 switch (colorMode) {
190 case ColorMode::DISPLAY_P3:
191 case ColorMode::ADOBE_RGB:
192 case ColorMode::DCI_P3:
193 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700194 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700195 case ColorMode::BT2100_PQ:
196 case ColorMode::BT2100_HLG:
197 return true;
198 case ColorMode::NATIVE:
199 case ColorMode::STANDARD_BT601_625:
200 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
201 case ColorMode::STANDARD_BT601_525:
202 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
203 case ColorMode::STANDARD_BT709:
204 case ColorMode::SRGB:
205 return false;
206 }
207 return false;
208}
209
210#pragma clang diagnostic pop
211
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100212// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700213constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800214
215float getDensityFromProperty(const char* property, bool required) {
216 char value[PROPERTY_VALUE_MAX];
217 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
218 if (!density && required) {
219 ALOGE("%s must be defined as a build property", property);
220 return FALLBACK_DENSITY;
221 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700222 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800223}
224
Peiyong Lin9d846a52018-11-05 13:18:20 -0800225// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
226bool validateCompositionDataspace(Dataspace dataspace) {
227 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
228}
229
ramindani32cf0602022-03-02 02:30:29 +0000230std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700231 const auto displayIdleTimerMsKey = [displayId] {
232 std::stringstream ss;
233 ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
234 return ss.str();
235 }();
236
ramindani32cf0602022-03-02 02:30:29 +0000237 const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
238 if (displayIdleTimerMs > 0) {
239 return std::chrono::milliseconds(displayIdleTimerMs);
240 }
241
242 const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
243 const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
244 return std::chrono::milliseconds(millis);
245}
246
247bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
Ady Abraham6d885932021-09-03 18:05:48 -0700248 const auto displaySupportKernelIdleTimerKey = [displayId] {
249 std::stringstream ss;
250 ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
251 return ss.str();
252 }();
253
Ady Abraham6d885932021-09-03 18:05:48 -0700254 const auto displaySupportKernelIdleTimer =
255 base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
ramindani32cf0602022-03-02 02:30:29 +0000256 return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
Ady Abraham6d885932021-09-03 18:05:48 -0700257}
258
Steven Thomasb02664d2017-07-26 18:48:28 -0700259} // namespace anonymous
260
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261// ---------------------------------------------------------------------------
262
Mathias Agopian99b49842011-06-27 16:05:52 -0700263const String16 sHardwareTest("android.permission.HARDWARE_TEST");
264const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
Hongwei Wang46213ea2020-12-04 17:17:31 -0800265const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
Mathias Agopian99b49842011-06-27 16:05:52 -0700266const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
John Reck88270902021-03-18 11:27:35 -0400267const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
Mathias Agopian99b49842011-06-27 16:05:52 -0700268const String16 sDump("android.permission.DUMP");
chaviwf5bb97b2021-04-28 15:35:37 -0500269const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
Leon Scroggins9a20f722021-12-28 14:43:12 +0000270const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
chaviwf5bb97b2021-04-28 15:35:37 -0500271
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800272const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700273
274// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700275int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700276bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800277bool SurfaceFlinger::hasSyncFramework;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800278int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100279uint32_t SurfaceFlinger::maxGraphicsWidth;
280uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600281bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700282bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700283Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
284ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
285Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
286ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
ramindani4d48f902021-09-20 21:07:45 +0000287LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
Mathias Agopian99b49842011-06-27 16:05:52 -0700288
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800289std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
290 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800291 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700292 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800293 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700294 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800295 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700296 return std::string("Enhanced");
297 default:
298 return std::string("Unknown ") +
299 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800300 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800301}
302
Hongwei Wang46213ea2020-12-04 17:17:31 -0800303bool callingThreadHasRotateSurfaceFlingerAccess() {
304 IPCThreadState* ipc = IPCThreadState::self();
305 const int pid = ipc->getCallingPid();
306 const int uid = ipc->getCallingUid();
307 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
308 PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
309}
310
Leon Scroggins9a20f722021-12-28 14:43:12 +0000311bool callingThreadHasInternalSystemWindowAccess() {
312 IPCThreadState* ipc = IPCThreadState::self();
313 const int pid = ipc->getCallingPid();
314 const int uid = ipc->getCallingUid();
Leon Scroggins IIIcf7a7b22021-12-23 20:04:48 -0500315 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
316 PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
Leon Scroggins9a20f722021-12-28 14:43:12 +0000317}
318
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700319SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
320 : mFactory(factory),
Vishnu Nair7891e962021-11-11 12:07:21 -0800321 mPid(getpid()),
Pablo Gamitoc351d6f2020-09-17 15:34:26 +0000322 mInterceptor(mFactory.createSurfaceInterceptor()),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700323 mTimeStats(std::make_shared<impl::TimeStats>()),
Adithya Srinivasan2db3c1b2020-11-18 12:43:17 -0800324 mFrameTracer(mFactory.createFrameTracer()),
Vishnu Nair7891e962021-11-11 12:07:21 -0800325 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700326 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700327 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
Robert Carr3e2a2992021-06-11 13:42:55 -0700328 mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800329 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
Alec Mouridea1ac52021-06-23 18:12:18 -0700330 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
chaviw60c9d3e2021-06-04 12:52:17 -0500331 mPowerAdvisor(*this),
Dominik Laskowski91f635e2022-01-08 05:46:09 -0800332 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make(*this)) {
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700333 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
Chris Ye0783e992020-06-02 21:34:49 -0700334}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800335
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700336SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800337 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800338
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900339 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900341 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700342
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900343 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700344
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800346
Brian Lindahla13f2d52020-03-05 11:54:17 +0100347 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
348 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
349
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900350 hasWideColorDisplay = has_wide_color_display(false);
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900351 mDefaultCompositionDataspace =
352 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700353 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
354 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900355 defaultCompositionDataspace = mDefaultCompositionDataspace;
356 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
357 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
358 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
359 wideColorGamutCompositionPixelFormat =
360 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700361
Yichi Chenda901bf2019-06-28 14:58:27 +0800362 mColorSpaceAgnosticDataspace =
363 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
364
Alec Mouridd8bf2d2021-05-08 16:36:33 -0700365 mLayerCachingEnabled = [] {
366 const bool enable =
367 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
368 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
369 }();
370
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900371 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800372
Sundong Ahn85131bd2019-02-18 15:51:53 +0900373 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800374
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800375 // debugging stuff...
376 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700377
Mathias Agopianb4b17302013-03-20 18:36:41 -0700378 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700379 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700380
Alec Mouri5f487d42020-02-06 09:26:19 -0800381 property_get("ro.build.type", value, "user");
382 mIsUserBuild = strcmp(value, "user") == 0;
383
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700384 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
Orion Hodson34397da2019-02-04 09:36:10 +0000385
386 // DDMS debugging deprecated (b/120782499)
387 property_get("debug.sf.ddms", value, "0");
388 int debugDdms = atoi(value);
389 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700390
Ady Abrahamadb9a992019-09-19 21:21:55 +0000391 property_get("debug.sf.enable_gl_backpressure", value, "0");
392 mPropagateBackpressureClientComposition = atoi(value);
393 ALOGI_IF(mPropagateBackpressureClientComposition,
394 "Enabling backpressure propagation for Client Composition");
395
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800396 property_get("ro.surface_flinger.supports_background_blur", value, "0");
397 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700398 mSupportsBlur = supportsBlurs;
399 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800400 property_get("ro.sf.blurs_are_expensive", value, "0");
401 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800402
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800403 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700404 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
405 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800406 mGraphicBufferProducerListSizeLogThreshold =
407 std::max(static_cast<int>(0.95 *
408 static_cast<double>(mMaxGraphicBufferProducerListSize)),
409 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700410
Dan Stozaec460082018-12-17 15:35:09 -0800411 property_get("debug.sf.luma_sampling", value, "1");
412 mLumaSampling = atoi(value);
413
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800414 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800415 mDisableClientCompositionCache = atoi(value);
416
Vishnu Naira3140382022-02-24 14:07:11 -0800417 property_get("debug.sf.predict_hwc_composition_strategy", value, "0");
418 mPredictCompositionStrategy = atoi(value);
419
Romain Guy11d63f42017-07-20 12:47:14 -0700420 // We should be reading 'persist.sys.sf.color_saturation' here
421 // but since /data may be encrypted, we need to wait until after vold
422 // comes online to attempt to read the property. The property is
423 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800424
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700425 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
Kalle Raitaa099a242017-01-11 11:17:29 -0800426 // Without the override SurfaceFlinger cannot connect to HIDL
427 // services that are not listed in the manifests. Considered
428 // deriving the setting from the set service name, but it
429 // would be brittle if the name that's not 'default' is used
430 // for production purposes later on.
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700431 ALOGI("Enabling Treble testing override");
Steven Moreland7c8af942020-07-08 18:35:51 +0000432 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800433 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800434
Ady Abraham29d0da32020-07-16 18:39:33 -0700435 mRefreshRateOverlaySpinner = property_get_bool("sf.debug.show_refresh_rate_overlay_spinner", 0);
John Reckac09e452021-04-07 16:35:37 -0400436
Dominik Laskowski46471e62022-01-14 15:34:03 -0800437 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
438 mTransactionTracing.emplace();
Vishnu Nair7891e962021-11-11 12:07:21 -0800439 }
John Reck49d9ad32022-02-23 19:03:31 -0500440
441 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
ramindani4d48f902021-09-20 21:07:45 +0000442}
443
444LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
445 if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
446 return LatchUnsignaledConfig::Always;
ramindani4d48f902021-09-20 21:07:45 +0000447 }
Ady Abraham9dada822022-02-03 10:26:59 -0800448
Ady Abrahamd9e8d1b2022-02-25 00:36:10 +0000449 if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
Ady Abraham9dada822022-02-03 10:26:59 -0800450 return LatchUnsignaledConfig::AutoSingleLayer;
451 }
452
453 return LatchUnsignaledConfig::Disabled;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800454}
455
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700456SurfaceFlinger::~SurfaceFlinger() = default;
457
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700458void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800459 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700460 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800461
Dominik Laskowski756b7892021-08-04 12:53:59 -0700462 // Sever the link to inputflinger since it's gone as well.
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000463 static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
Vishnu Nairb9df4702021-03-01 11:53:15 -0800464
Andy McFadden13a082e2012-08-24 10:16:42 -0700465 // restore initial conditions (default device unblank, etc)
466 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800467
468 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700469 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800470}
471
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700472void SurfaceFlinger::run() {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700473 mScheduler->run();
Robert Carr1db73f62016-12-21 12:58:51 -0800474}
475
476sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700477 const sp<Client> client = new Client(this);
478 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800479}
480
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700481sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
chaviwd4a61642020-09-01 14:53:46 -0700482 // onTransact already checks for some permissions, but adding an additional check here.
483 // This is to ensure that only system and graphics can request to create a secure
484 // display. Secure displays can show secure content so we add an additional restriction on it.
485 const int uid = IPCThreadState::self()->getCallingUid();
486 if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
487 ALOGE("Only privileged processes can create a secure display");
488 return nullptr;
489 }
490
Mathias Agopiane57f2922012-08-09 16:29:12 -0700491 class DisplayToken : public BBinder {
492 sp<SurfaceFlinger> flinger;
493 virtual ~DisplayToken() {
494 // no more references, this display must be terminated
495 Mutex::Autolock _l(flinger->mStateLock);
496 flinger->mCurrentState.displays.removeItem(this);
497 flinger->setTransactionFlags(eDisplayTransactionNeeded);
498 }
499 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700500 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501 : flinger(flinger) {
502 }
503 };
504
505 sp<BBinder> token = new DisplayToken(this);
506
507 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700508 // Display ID is assigned when virtual display is allocated by HWC.
509 DisplayDeviceState state;
510 state.isSecure = secure;
511 state.displayName = displayName;
512 mCurrentState.displays.add(token, state);
513 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700514 return token;
515}
516
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700517void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700518 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700519
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700520 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700521 if (index < 0) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800522 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700523 return;
524 }
525
Dominik Laskowski075d3172018-05-24 15:50:06 -0700526 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700527 if (state.physical) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800528 ALOGE("%s: Invalid operation on physical display", __func__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700529 return;
530 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700531 mInterceptor->saveDisplayDeletion(state.sequenceId);
532 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700533 setTransactionFlags(eDisplayTransactionNeeded);
534}
535
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800536void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
537 auto& generator = mVirtualDisplayIdGenerators.hal;
538 if (!generator && enable) {
539 ALOGI("Enabling HAL virtual displays");
540 generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
541 } else if (generator && !enable) {
542 ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
543 generator.reset();
544 }
545}
546
Dominik Laskowski263eec42021-07-21 23:13:24 -0700547VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
548 ui::PixelFormat format) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800549 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
550 if (const auto id = generator->generateId()) {
Dominik Laskowski263eec42021-07-21 23:13:24 -0700551 if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800552 return *id;
553 }
554
555 generator->releaseId(*id);
556 } else {
557 ALOGW("%s: Exhausted HAL virtual displays", __func__);
558 }
559
560 ALOGW("%s: Falling back to GPU virtual display", __func__);
561 }
562
563 const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
564 LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
565 return *id;
566}
567
568void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
569 if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
570 if (auto& generator = mVirtualDisplayIdGenerators.hal) {
571 generator->releaseId(*id);
572 }
573 return;
574 }
575
576 const auto id = GpuVirtualDisplayId::tryCast(displayId);
577 LOG_ALWAYS_FATAL_IF(!id);
578 mVirtualDisplayIdGenerators.gpu.releaseId(*id);
579}
580
Ady Abrahamed3290f2021-05-17 15:12:14 -0700581std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800582 std::vector<PhysicalDisplayId> displayIds;
583 displayIds.reserve(mPhysicalDisplayTokens.size());
Ady Abraham2a0066d2021-07-15 20:16:58 -0700584 const auto defaultDisplayId = [this]() REQUIRES(mStateLock) {
585 if (const auto display = getDefaultDisplayDeviceLocked()) {
586 return display->getPhysicalId();
587 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700588
Ady Abraham2a0066d2021-07-15 20:16:58 -0700589 // fallback to the internal display id if the active display is unknown
590 return getInternalDisplayIdLocked();
591 }();
592 displayIds.push_back(defaultDisplayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800593
594 for (const auto& [id, token] : mPhysicalDisplayTokens) {
Ady Abraham2a0066d2021-07-15 20:16:58 -0700595 if (id != defaultDisplayId) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200596 displayIds.push_back(id);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800597 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700598 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700599
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800600 return displayIds;
601}
602
Vishnu Nair8c8db542021-09-17 19:51:45 -0700603status_t SurfaceFlinger::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) const {
604 Mutex::Autolock lock(mStateLock);
605 *id = getInternalDisplayIdLocked();
606 return NO_ERROR;
607}
608
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800609sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
610 Mutex::Autolock lock(mStateLock);
Marin Shalamanova524a092020-07-27 21:39:55 +0200611 return getPhysicalDisplayTokenLocked(displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700612}
613
Ady Abraham37965d42018-11-01 13:43:32 -0700614status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
615 if (!outGetColorManagement) {
616 return BAD_VALUE;
617 }
618 *outGetColorManagement = useColorManagement;
619 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700620}
621
Lloyd Pique441d5042018-10-18 16:49:51 -0700622HWComposer& SurfaceFlinger::getHwComposer() const {
623 return mCompositionEngine->getHwComposer();
624}
625
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700626renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
627 return mCompositionEngine->getRenderEngine();
628}
629
Lloyd Pique70d91362018-10-18 16:02:55 -0700630compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
631 return *mCompositionEngine.get();
632}
633
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100634void SurfaceFlinger::bootFinished() {
Rob Carr2aa78cb2020-03-10 14:27:49 -0700635 if (mBootFinished == true) {
636 ALOGE("Extra call to bootFinished");
637 return;
638 }
639 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700640 if (mStartPropertySetThread->join() != NO_ERROR) {
641 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800642 }
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700643
644 if (mRenderEnginePrimeCacheFuture.valid()) {
645 mRenderEnginePrimeCacheFuture.get();
646 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800647 const nsecs_t now = systemTime();
648 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000649 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700650
Mikael Pessa90092f42019-08-26 17:22:04 -0700651 mFrameTracer->initialize();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700652 mFrameTimeline->onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700653 getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700654
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700655 // wait patiently for the window manager death
656 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700657 mWindowManager = defaultServiceManager()->getService(name);
658 if (mWindowManager != 0) {
659 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700660 }
661
662 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700663 // formerly we would just kill the process, but we now ask it to exit so it
664 // can choose where to stop the animation.
665 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700666
667 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
668 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
669 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700670
Denis Hsue70cc6c2020-06-17 10:17:30 +0800671 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
672
Jaineel Mehtaac331c52021-11-29 21:38:10 +0000673 static_cast<void>(mScheduler->schedule([=] {
Denis Hsue70cc6c2020-06-17 10:17:30 +0800674 if (input == nullptr) {
675 ALOGE("Failed to link to input service");
676 } else {
Chris Ye0783e992020-06-02 21:34:49 -0700677 mInputFlinger = interface_cast<os::IInputFlinger>(input);
Denis Hsue70cc6c2020-06-17 10:17:30 +0800678 }
679
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800680 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700681 mPowerAdvisor.onBootFinished();
Robert Carr9b623c32022-03-21 15:55:22 -0700682 mPowerAdvisor.enablePowerHint(mFlagManager.use_adpf_cpu_hint());
Matt Buckleyef51fba2021-10-12 19:30:12 +0000683 if (mPowerAdvisor.usePowerHintSession()) {
Xiang Wang76236e12022-03-22 17:25:30 +0000684 std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
685 std::vector<int32_t> tidList;
686 tidList.emplace_back(gettid());
687 if (renderEngineTid.has_value()) {
688 tidList.emplace_back(*renderEngineTid);
689 }
Xiang Wange12b4fa2022-03-25 23:48:40 +0000690 if (!mPowerAdvisor.startPowerHintSession(tidList)) {
691 ALOGW("Cannot start power hint session");
692 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000693 }
694
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800695 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800696
Ady Abraham8a82ba62020-01-17 12:43:17 -0800697 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800698 FTL_FAKE_GUARD(mStateLock, enableRefreshRateOverlay(true));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800699 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800700 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800701}
702
Dan Stoza436ccf32018-06-21 12:10:12 -0700703uint32_t SurfaceFlinger::getNewTexture() {
704 {
705 std::lock_guard lock(mTexturePoolMutex);
706 if (!mTexturePool.empty()) {
707 uint32_t name = mTexturePool.back();
708 mTexturePool.pop_back();
709 ATRACE_INT("TexturePoolSize", mTexturePool.size());
710 return name;
711 }
712
713 // The pool was too small, so increase it for the future
714 ++mTexturePoolSize;
715 }
716
717 // The pool was empty, so we need to get a new texture name directly using a
718 // blocking call to the main thread
Robert Carrcdd7df92021-04-12 15:32:09 -0700719 auto genTextures = [this] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700720 uint32_t name = 0;
721 getRenderEngine().genTextures(1, &name);
722 return name;
Robert Carrcdd7df92021-04-12 15:32:09 -0700723 };
724 if (std::this_thread::get_id() == mMainThreadId) {
725 return genTextures();
726 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -0700727 return mScheduler->schedule(genTextures).get();
Robert Carrcdd7df92021-04-12 15:32:09 -0700728 }
Dan Stoza436ccf32018-06-21 12:10:12 -0700729}
730
Mathias Agopian3f844832013-08-07 21:24:32 -0700731void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700732 std::lock_guard lock(mTexturePoolMutex);
733 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
734 // to actually delete this or not based on mTexturePoolSize
735 mTexturePool.push_back(texture);
736 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700737}
738
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500739static std::optional<renderengine::RenderEngine::RenderEngineType>
740chooseRenderEngineTypeViaSysProp() {
741 char prop[PROPERTY_VALUE_MAX];
742 property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
743
744 if (strcmp(prop, "gles") == 0) {
745 return renderengine::RenderEngine::RenderEngineType::GLES;
746 } else if (strcmp(prop, "threaded") == 0) {
747 return renderengine::RenderEngine::RenderEngineType::THREADED;
748 } else if (strcmp(prop, "skiagl") == 0) {
749 return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
750 } else if (strcmp(prop, "skiaglthreaded") == 0) {
751 return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
752 } else {
753 ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
754 return {};
755 }
756}
757
Wei Wangf9b05ee2017-07-19 20:59:39 -0700758// Do not call property_set on main thread which will be blocked by init
759// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700760void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700761 ALOGI( "SurfaceFlinger's main thread ready to run. "
762 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700763 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800764
Steven Thomasb02664d2017-07-26 18:48:28 -0700765 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700766 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800767 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Leon Scroggins IIIc77162c2021-11-16 17:13:08 -0500768 auto builder = renderengine::RenderEngineCreationArgs::Builder()
769 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
770 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
771 .setUseColorManagerment(useColorManagement)
772 .setEnableProtectedContext(enable_protected_contents(false))
773 .setPrecacheToneMapperShaderOnly(false)
774 .setSupportsBackgroundBlur(mSupportsBlur)
775 .setContextPriority(
776 useContextPriority
777 ? renderengine::RenderEngine::ContextPriority::REALTIME
778 : renderengine::RenderEngine::ContextPriority::MEDIUM);
779 if (auto type = chooseRenderEngineTypeViaSysProp()) {
780 builder.setRenderEngineType(type.value());
781 }
782 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));
Garfield Tan9c9c1912021-07-19 12:02:16 -0700783 mMaxRenderTargetSize =
784 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
Wei Wang976a6452021-06-11 15:26:00 -0700785
786 // Set SF main policy after initializing RenderEngine which has its own policy.
787 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
788 ALOGW("Failed to set main task profile");
789 }
790
Alec Mourie4034bb2019-11-19 12:45:54 -0800791 mCompositionEngine->setTimeStats(mTimeStats);
Dominik Laskowskif06d68e2021-03-24 19:40:03 -0700792 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
Yichi Chen3401b562022-01-17 15:42:35 +0800793 mCompositionEngine->getHwComposer().setCallback(*this);
Alec Mouria90a5702021-04-16 16:36:21 +0000794 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800795
Ady Abraham9dada822022-02-03 10:26:59 -0800796 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
797
Dominik Laskowski3dce4f42021-03-08 20:48:28 -0800798 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
799 enableHalVirtualDisplays(true);
800 }
801
Lloyd Piqueba04e622017-12-14 17:11:26 -0800802 // Process any initial hotplug and resulting display changes.
803 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700804 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700805 LOG_ALWAYS_FATAL_IF(!display, "Missing primary display after registering composer callback.");
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +0200806 const auto displayId = display->getPhysicalId();
807 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700808 "Primary display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800809
Mathias Agopian92a979a2012-08-02 18:32:23 -0700810 // initialize our drawing state
811 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700812
Andy McFadden13a082e2012-08-24 10:16:42 -0700813 // set initial conditions (e.g. unblank default device)
814 initializeDisplays();
815
Alec Mouridea1ac52021-06-23 18:12:18 -0700816 mPowerAdvisor.init();
817
Steven Thomas137d4bc2019-07-25 16:55:14 -0700818 char primeShaderCache[PROPERTY_VALUE_MAX];
819 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
820 if (atoi(primeShaderCache)) {
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700821 if (setSchedFifo(false) != NO_ERROR) {
822 ALOGW("Can't set SCHED_OTHER for primeCache");
823 }
824
825 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
826
827 if (setSchedFifo(true) != NO_ERROR) {
828 ALOGW("Can't set SCHED_OTHER for primeCache");
829 }
Steven Thomas137d4bc2019-07-25 16:55:14 -0700830 }
Dan Stoza4e637772016-07-28 13:31:51 -0700831
Ady Abrahamed3290f2021-05-17 15:12:14 -0700832 onActiveDisplaySizeChanged(display);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400833
Wei Wangf9b05ee2017-07-19 20:59:39 -0700834 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700835
836 const bool presentFenceReliable =
Ady Abrahamde549d42022-01-26 19:19:17 -0800837 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700838 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700839
840 if (mStartPropertySetThread->Start() != NO_ERROR) {
841 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800842 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800843
Dan Stoza9e56aa02015-11-02 13:00:03 -0800844 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700845}
846
Romain Guy11d63f42017-07-20 12:47:14 -0700847void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700848 Mutex::Autolock _l(mStateLock);
849
Romain Guy11d63f42017-07-20 12:47:14 -0700850 char value[PROPERTY_VALUE_MAX];
851
852 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800853 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700854 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800855 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100856
857 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700858 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800859
860 property_get("persist.sys.sf.color_mode", value, "0");
861 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700862}
863
Mathias Agopiana67e4182012-06-19 17:26:12 -0700864void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800865 // Start boot animation service by setting a property mailbox
866 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700867 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800868 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700869 if (mStartPropertySetThread->join() != NO_ERROR) {
870 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800871 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700872}
873
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800874// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800875
Jamie Gennis582270d2011-08-17 18:19:00 -0700876bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800877 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800878 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800879 return authenticateSurfaceTextureLocked(bufferProducer);
880}
881
882bool SurfaceFlinger::authenticateSurfaceTextureLocked(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800883 const sp<IGraphicBufferProducer>& /* bufferProducer */) const {
884 return false;
Jamie Gennis134f0422011-03-08 12:18:54 -0800885}
886
Brian Anderson6b376712017-04-04 10:51:39 -0700887status_t SurfaceFlinger::getSupportedFrameTimestamps(
888 std::vector<FrameEvent>* outSupported) const {
889 *outSupported = {
890 FrameEvent::REQUESTED_PRESENT,
891 FrameEvent::ACQUIRE,
892 FrameEvent::LATCH,
893 FrameEvent::FIRST_REFRESH_START,
894 FrameEvent::LAST_REFRESH_START,
895 FrameEvent::GPU_COMPOSITION_DONE,
896 FrameEvent::DEQUEUE_READY,
897 FrameEvent::RELEASE,
898 };
Dominik Laskowski298b08e2022-02-15 13:45:02 -0800899
900 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
901
Ady Abrahamde549d42022-01-26 19:19:17 -0800902 if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700903 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
904 }
905 return NO_ERROR;
906}
907
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800908status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
909 if (!displayToken || !state) {
910 return BAD_VALUE;
911 }
912
913 Mutex::Autolock lock(mStateLock);
914
915 const auto display = getDisplayDeviceLocked(displayToken);
916 if (!display) {
917 return NAME_NOT_FOUND;
918 }
919
920 state->layerStack = display->getLayerStack();
921 state->orientation = display->getOrientation();
922
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200923 const Rect layerStackRect = display->getLayerStackSpaceRect();
924 state->layerStackSpaceRect =
925 layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800926
927 return NO_ERROR;
928}
929
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100930status_t SurfaceFlinger::getStaticDisplayInfo(const sp<IBinder>& displayToken,
931 ui::StaticDisplayInfo* info) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800932 if (!displayToken || !info) {
933 return BAD_VALUE;
934 }
935
936 Mutex::Autolock lock(mStateLock);
937
938 const auto display = getDisplayDeviceLocked(displayToken);
939 if (!display) {
940 return NAME_NOT_FOUND;
941 }
942
Dominik Laskowski55c85402020-01-21 16:25:47 -0800943 if (const auto connectionType = display->getConnectionType())
944 info->connectionType = *connectionType;
945 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800946 return INVALID_OPERATION;
947 }
948
949 if (mEmulatedDisplayDensity) {
950 info->density = mEmulatedDisplayDensity;
951 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100952 info->density = info->connectionType == ui::DisplayConnectionType::Internal
Dominik Laskowski55c85402020-01-21 16:25:47 -0800953 ? mInternalDisplayDensity
954 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800955 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700956 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800957
958 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200959 info->deviceProductInfo = display->getDeviceProductInfo();
ramindani06e518e2022-03-14 18:47:53 +0000960 info->installOrientation = display->getPhysicalOrientation();
Vishnu Naird0a89652022-01-13 12:05:54 -0800961
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800962 return NO_ERROR;
963}
964
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100965status_t SurfaceFlinger::getDynamicDisplayInfo(const sp<IBinder>& displayToken,
966 ui::DynamicDisplayInfo* info) {
967 if (!displayToken || !info) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700968 return BAD_VALUE;
969 }
970
Dominik Laskowski22488f62019-03-28 09:53:04 -0700971 Mutex::Autolock lock(mStateLock);
972
Marin Shalamanov5801c942020-12-17 17:00:13 +0100973 const auto display = getDisplayDeviceLocked(displayToken);
974 if (!display) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700975 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700976 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700977
Dominik Laskowskif8db0f02021-04-19 11:05:25 -0700978 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
979 if (!displayId) {
980 return INVALID_OPERATION;
981 }
982
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -0800983 info->activeDisplayModeId = display->getActiveMode()->getId().value();
Mathias Agopian1604f772012-09-18 21:54:42 -0700984
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100985 const auto& supportedModes = display->getSupportedModes();
986 info->supportedDisplayModes.clear();
987 info->supportedDisplayModes.reserve(supportedModes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800988
989 for (const auto& [id, mode] : supportedModes) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100990 ui::DisplayMode outMode;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800991 outMode.id = static_cast<int32_t>(id.value());
Dan Stoza7f7da322014-05-02 15:26:25 -0700992
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800993 auto [width, height] = mode->getResolution();
994 auto [xDpi, yDpi] = mode->getDpi();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700995
ramindani06e518e2022-03-14 18:47:53 +0000996 if (const auto physicalOrientation = display->getPhysicalOrientation();
997 physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800998 std::swap(width, height);
999 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -07001000 }
1001
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001002 outMode.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -08001003
Huan Songf7eeb102022-03-28 11:02:38 -07001004 outMode.xDpi = xDpi;
1005 outMode.yDpi = yDpi;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001006
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001007 const nsecs_t period = mode->getVsyncPeriod();
1008 outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08001009
Ady Abraham8287e852020-08-12 14:44:58 -07001010 const auto vsyncConfigSet =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001011 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001012 outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1013 outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1014 outMode.group = mode->getGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001015
Andy McFadden91b2ca82014-06-13 14:04:23 -07001016 // This is how far in advance a buffer must be queued for
1017 // presentation at a given time. If you want a buffer to appear
1018 // on the screen at time N, you must submit the buffer before
1019 // (N - presentationDeadline).
1020 //
1021 // Normally it's one full refresh period (to give SF a chance to
1022 // latch the buffer), but this can be reduced by configuring a
Ady Abraham8cb21882020-08-26 18:22:05 -07001023 // VsyncController offset. Any additional delays introduced by the hardware
Andy McFadden91b2ca82014-06-13 14:04:23 -07001024 // composer or panel must be accounted for here.
1025 //
1026 // We add an additional 1ms to allow for processing time and
1027 // differences between the ideal and actual refresh rate.
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001028 outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -07001029
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001030 info->supportedDisplayModes.push_back(outMode);
Mathias Agopian8b736f12012-08-13 17:54:26 -07001031 }
1032
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001033 info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001034 info->supportedColorModes = getDisplayColorModes(*display);
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001035 info->hdrCapabilities = display->getHdrCapabilities();
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001036
Marin Shalamanovb173f752021-02-16 19:38:36 +01001037 info->autoLowLatencyModeSupported =
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001038 getHwComposer().hasDisplayCapability(*displayId,
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001039 DisplayCapability::AUTO_LOW_LATENCY_MODE);
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001040 info->gameContentTypeSupported =
1041 getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001042
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001043 info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
Kriti Dangac0a74d2022-03-16 11:52:35 +01001044
1045 if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001046 if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
1047 if (const auto modeId = display->translateModeId(*hwcId)) {
1048 info->preferredBootDisplayMode = modeId->value();
1049 }
1050 }
1051 }
Kriti Dang646f8ec2022-01-18 14:35:02 +01001052
Dan Stoza7f7da322014-05-02 15:26:25 -07001053 return NO_ERROR;
1054}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001055
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
1057 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001058 return BAD_VALUE;
1059 }
1060
Ady Abrahame90dd522020-12-29 12:08:45 -08001061 *stats = mScheduler->getDisplayStatInfo(systemTime());
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001062 return NO_ERROR;
1063}
1064
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001065void SurfaceFlinger::setDesiredActiveMode(const ActiveModeInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001066 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001067
1068 if (!info.mode) {
1069 ALOGW("requested display mode is null");
1070 return;
1071 }
1072 auto display = getDisplayDeviceLocked(info.mode->getPhysicalDisplayId());
Ady Abraham3efa3942021-06-24 19:01:25 -07001073 if (!display) {
Ady Abraham690f4612021-07-01 23:24:03 -07001074 ALOGW("%s: display is no longer valid", __func__);
Ady Abraham3efa3942021-06-24 19:01:25 -07001075 return;
1076 }
1077
Ady Abraham690f4612021-07-01 23:24:03 -07001078 if (display->setDesiredActiveMode(info)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001079 scheduleComposite(FrameHint::kNone);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001080
Alec Mouri754c98a2019-03-18 18:53:42 -07001081 // Start receiving vsync samples now, so that we can detect a period
1082 // switch.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001083 mScheduler->resyncToHardwareVsync(true, info.mode->getFps());
Ady Abraham53852a52019-05-28 18:07:44 -07001084 // As we called to set period, we will call to onRefreshRateChangeCompleted once
Ady Abraham8cb21882020-08-26 18:22:05 -07001085 // VsyncController model is locked.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001086 modulateVsync(&VsyncModulator::onRefreshRateChangeInitiated);
Ady Abraham2139f732019-11-13 18:56:40 -08001087
Ady Abraham690f4612021-07-01 23:24:03 -07001088 updatePhaseConfiguration(info.mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001089 mScheduler->setModeChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001090 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001091}
1092
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001093status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001094 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001095
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001096 if (!displayToken) {
1097 return BAD_VALUE;
1098 }
Ady Abraham838de062019-02-04 10:24:03 -08001099
Dominik Laskowski756b7892021-08-04 12:53:59 -07001100 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001101 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001102 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001103 ALOGE("Attempt to set allowed display modes for invalid display token %p",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001104 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001105 return NAME_NOT_FOUND;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001106 }
1107
1108 if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001109 ALOGW("Attempt to set allowed display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001110 return INVALID_OPERATION;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001111 }
Marin Shalamanov5801c942020-12-17 17:00:13 +01001112
1113 const auto mode = display->getMode(DisplayModeId{modeId});
1114 if (!mode) {
1115 ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
1116 return BAD_VALUE;
1117 }
1118
1119 const auto fps = mode->getFps();
1120 // Keep the old switching type.
1121 const auto allowGroupSwitching =
Ady Abraham3efa3942021-06-24 19:01:25 -07001122 display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
Marin Shalamanov5801c942020-12-17 17:00:13 +01001123 const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
1124 allowGroupSwitching,
1125 {fps, fps}};
1126 constexpr bool kOverridePolicy = false;
1127
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001128 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001129 });
1130
1131 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001132}
1133
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001134void SurfaceFlinger::updateInternalStateWithChangedMode() {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001135 ATRACE_CALL();
1136
Dominik Laskowski22488f62019-03-28 09:53:04 -07001137 const auto display = getDefaultDisplayDeviceLocked();
1138 if (!display) {
1139 return;
1140 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001141
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001142 const auto upcomingModeInfo =
1143 FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
1144
Ady Abrahamfaac6da2021-07-15 10:04:40 -07001145 if (!upcomingModeInfo.mode) {
1146 // There is no pending mode change. This can happen if the active
1147 // display changed and the mode change happened on a different display.
1148 return;
1149 }
1150
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001151 if (display->getActiveMode()->getResolution() != upcomingModeInfo.mode->getResolution()) {
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001152 auto& state = mCurrentState.displays.editValueFor(display->getDisplayToken());
1153 // We need to generate new sequenceId in order to recreate the display (and this
1154 // way the framebuffer).
1155 state.sequenceId = DisplayDeviceState{}.sequenceId;
Ady Abraham690f4612021-07-01 23:24:03 -07001156 state.physical->activeMode = upcomingModeInfo.mode;
Marin Shalamanov993ddf42021-05-26 16:54:40 +02001157 processDisplayChangesLocked();
1158
1159 // processDisplayChangesLocked will update all necessary components so we're done here.
1160 return;
1161 }
Alec Mouri8de697e2020-03-19 10:52:01 -07001162
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001163 // We just created this display so we can call even if we are not on the main thread.
1164 ftl::FakeGuard guard(kMainThreadContext);
Ady Abraham690f4612021-07-01 23:24:03 -07001165 display->setActiveMode(upcomingModeInfo.mode->getId());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001166
Ady Abraham690f4612021-07-01 23:24:03 -07001167 const Fps refreshRate = upcomingModeInfo.mode->getFps();
Marin Shalamanov5801c942020-12-17 17:00:13 +01001168 mRefreshRateStats->setRefreshRate(refreshRate);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001169 updatePhaseConfiguration(refreshRate);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001170
Dominik Laskowski068173d2021-08-11 17:22:59 -07001171 if (upcomingModeInfo.event != DisplayModeEvent::None) {
Ady Abraham690f4612021-07-01 23:24:03 -07001172 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, upcomingModeInfo.mode);
Ady Abraham447052e2019-02-13 16:07:27 -08001173 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001174}
1175
Ady Abraham690f4612021-07-01 23:24:03 -07001176void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1177 display->clearDesiredActiveModeState();
1178 if (isDisplayActiveLocked(display)) {
1179 mScheduler->setModeChangePending(false);
1180 }
Ady Abraham53852a52019-05-28 18:07:44 -07001181}
1182
Ady Abraham690f4612021-07-01 23:24:03 -07001183void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1184 const auto refreshRate = display->getDesiredActiveMode()->mode->getFps();
1185 clearDesiredActiveModeState(display);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001186 mScheduler->resyncToHardwareVsync(true, refreshRate);
Marin Shalamanov5801c942020-12-17 17:00:13 +01001187 updatePhaseConfiguration(refreshRate);
1188}
1189
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001190void SurfaceFlinger::setActiveModeInHwcIfNeeded() {
Alec Mourife3dc942019-02-12 14:19:18 -08001191 ATRACE_CALL();
Ady Abraham690f4612021-07-01 23:24:03 -07001192
Marin Shalamanovdd594312021-11-09 16:37:37 +01001193 std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1194
Ady Abraham690f4612021-07-01 23:24:03 -07001195 for (const auto& iter : mDisplays) {
1196 const auto& display = iter.second;
1197 if (!display || !display->isInternal()) {
1198 continue;
1199 }
1200
1201 // Store the local variable to release the lock.
1202 const auto desiredActiveMode = display->getDesiredActiveMode();
1203 if (!desiredActiveMode) {
1204 // No desired active mode pending to be applied
1205 continue;
1206 }
1207
1208 if (!isDisplayActiveLocked(display)) {
1209 // display is no longer the active display, so abort the mode change
1210 clearDesiredActiveModeState(display);
1211 continue;
1212 }
1213
1214 const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
1215 if (!desiredMode) {
1216 ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1217 desiredActiveMode->mode->getId().value());
1218 clearDesiredActiveModeState(display);
1219 continue;
1220 }
1221
1222 const auto refreshRate = desiredMode->getFps();
1223 ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
1224 desiredMode->getId().value(), to_string(refreshRate).c_str(),
1225 to_string(display->getId()).c_str());
1226
1227 if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01001228 // we are already in the requested mode, there is nothing left to do
Ady Abraham690f4612021-07-01 23:24:03 -07001229 desiredActiveModeChangeDone(display);
1230 continue;
1231 }
1232
1233 // Desired active mode was set, it is different than the mode currently in use, however
1234 // allowed modes might have changed by the time we process the refresh.
1235 // Make sure the desired mode is still allowed
1236 const auto displayModeAllowed =
1237 display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
1238 if (!displayModeAllowed) {
Marin Shalamanovdd00c002021-11-04 16:54:38 +01001239 clearDesiredActiveModeState(display);
Ady Abraham690f4612021-07-01 23:24:03 -07001240 continue;
1241 }
1242
1243 // TODO(b/142753666) use constrains
1244 hal::VsyncPeriodChangeConstraints constraints;
1245 constraints.desiredTimeNanos = systemTime();
1246 constraints.seamlessRequired = false;
1247 hal::VsyncPeriodChangeTimeline outTimeline;
1248
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001249 const auto status = FTL_FAKE_GUARD(kMainThreadContext,
1250 display->initiateModeChange(*desiredActiveMode,
1251 constraints, &outTimeline));
1252
Ady Abraham690f4612021-07-01 23:24:03 -07001253 if (status != NO_ERROR) {
1254 // initiateModeChange may fail if a hotplug event is just about
1255 // to be sent. We just log the error in this case.
1256 ALOGW("initiateModeChange failed: %d", status);
1257 continue;
1258 }
1259 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1260
Marin Shalamanovdd594312021-11-09 16:37:37 +01001261 if (outTimeline.refreshRequired) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001262 scheduleComposite(FrameHint::kNone);
Marin Shalamanovdd594312021-11-09 16:37:37 +01001263 mSetActiveModePending = true;
1264 } else {
1265 // Updating the internal state should be done outside the loop,
1266 // because it can recreate a DisplayDevice and modify mDisplays
1267 // which will invalidate the iterator.
1268 displayToUpdateImmediately = display->getPhysicalId();
1269 }
1270 }
1271
1272 if (displayToUpdateImmediately) {
1273 updateInternalStateWithChangedMode();
1274
1275 const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1276 const auto desiredActiveMode = display->getDesiredActiveMode();
1277 if (desiredActiveMode &&
1278 display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
1279 desiredActiveModeChangeDone(display);
1280 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001281 }
Mathias Agopianc666cae2012-07-25 18:56:13 -07001282}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001283
Alec Mouridea1ac52021-06-23 18:12:18 -07001284void SurfaceFlinger::disableExpensiveRendering() {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001285 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001286 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski4d5052d2022-03-23 10:35:47 -07001287 ATRACE_NAME(whence);
Alec Mouridea1ac52021-06-23 18:12:18 -07001288 if (mPowerAdvisor.isUsingExpensiveRendering()) {
Dominik Laskowskibc6c8602022-01-11 08:53:24 -08001289 for (const auto& [_, display] : mDisplays) {
1290 constexpr bool kDisable = false;
Alec Mouridea1ac52021-06-23 18:12:18 -07001291 mPowerAdvisor.setExpensiveRenderingExpected(display->getId(), kDisable);
1292 }
1293 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001294 });
1295
1296 future.wait();
Alec Mouridea1ac52021-06-23 18:12:18 -07001297}
1298
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001299std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
1300 auto modes = getHwComposer().getColorModes(display.getPhysicalId());
Peiyong Linff84a152019-05-17 18:36:19 -07001301
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001302 // If the display is internal and the configuration claims it's not wide color capable,
Peiyong Linff84a152019-05-17 18:36:19 -07001303 // filter out all wide color modes. The typical reason why this happens is that the
1304 // hardware is not good enough to support GPU composition of wide color, and thus the
1305 // OEMs choose to disable this capability.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001306 if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
1307 !hasWideColorDisplay) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001308 const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
1309 modes.erase(newEnd, modes.end());
Peiyong Linff84a152019-05-17 18:36:19 -07001310 }
Michael Wright28f24d02016-07-12 13:30:53 -07001311
Marin Shalamanov228f46b2021-01-28 21:11:45 +01001312 return modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001313}
1314
Daniel Solomon42d04562019-01-20 21:03:19 -08001315status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1316 ui::DisplayPrimaries &primaries) {
1317 if (!displayToken) {
1318 return BAD_VALUE;
1319 }
1320
1321 // Currently we only support this API for a single internal display.
1322 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001323 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001324 }
1325
1326 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1327 return NO_ERROR;
1328}
1329
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001330status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001331 if (!displayToken) {
1332 return BAD_VALUE;
1333 }
1334
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001335 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001336 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001337 if (!display) {
1338 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1339 decodeColorMode(mode).c_str(), mode, displayToken.get());
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001340 return NAME_NOT_FOUND;
1341 }
1342
1343 if (display->isVirtual()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001344 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1345 decodeColorMode(mode).c_str(), mode);
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001346 return INVALID_OPERATION;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001347 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001348
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001349 const auto modes = getDisplayColorModes(*display);
1350 const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1351
1352 if (mode < ColorMode::NATIVE || !exists) {
1353 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1354 decodeColorMode(mode).c_str(), mode, displayToken.get());
1355 return BAD_VALUE;
1356 }
1357
1358 display->getCompositionDisplay()->setColorProfile(
1359 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1360
1361 return NO_ERROR;
1362 });
1363
Dominik Laskowski0a5f9212021-08-05 17:00:04 -07001364 // TODO(b/195698395): Propagate error.
1365 future.wait();
1366 return NO_ERROR;
Michael Wright28f24d02016-07-12 13:30:53 -07001367}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001368
Kriti Dang7defaf32021-11-15 11:55:43 +01001369status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001370 auto future = mScheduler->schedule(
1371 [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1372
1373 *outSupport = future.get();
1374 return NO_ERROR;
Kriti Dang7defaf32021-11-15 11:55:43 +01001375}
1376
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001377status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
1378 ui::DisplayModeId modeId) {
1379 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001380 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001381 const auto display = getDisplayDeviceLocked(displayToken);
1382 if (!display) {
1383 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1384 return NAME_NOT_FOUND;
1385 }
Kriti Dangf50d6772022-02-18 15:09:12 +01001386
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001387 if (display->isVirtual()) {
1388 ALOGE("%s: Invalid operation on virtual display", whence);
1389 return INVALID_OPERATION;
1390 }
1391
1392 const auto displayId = display->getPhysicalId();
1393 const auto mode = display->getMode(DisplayModeId{modeId});
1394 if (!mode) {
1395 ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
1396 to_string(displayId).c_str());
Kriti Dang7defaf32021-11-15 11:55:43 +01001397 return BAD_VALUE;
1398 }
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001399
1400 return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
Kriti Dang7defaf32021-11-15 11:55:43 +01001401 });
1402 return future.get();
1403}
1404
1405status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001406 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001407 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Kriti Dang7defaf32021-11-15 11:55:43 +01001408 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1409 return getHwComposer().clearBootDisplayMode(*displayId);
1410 } else {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001411 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Kriti Dang7defaf32021-11-15 11:55:43 +01001412 return BAD_VALUE;
1413 }
1414 });
1415 return future.get();
1416}
1417
Galia Peycheva5492cb52019-10-30 14:13:16 +01001418void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001419 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001420 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001421 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1422 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1423 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001424 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001425 }
1426 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001427}
1428
Galia Peycheva5492cb52019-10-30 14:13:16 +01001429void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001430 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001431 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001432 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001433 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001434 getHwComposer().setContentType(*displayId, type);
1435 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001436 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001437 }
1438 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001439}
1440
Svetoslavd85084b2014-03-20 10:28:31 -07001441status_t SurfaceFlinger::clearAnimationFrameStats() {
1442 Mutex::Autolock _l(mStateLock);
1443 mAnimFrameTracker.clearStats();
1444 return NO_ERROR;
1445}
1446
1447status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1448 Mutex::Autolock _l(mStateLock);
1449 mAnimFrameTracker.getStats(outStats);
1450 return NO_ERROR;
1451}
1452
Kriti Dang49ad4132021-01-08 11:49:56 +01001453status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1454 const std::vector<ui::Hdr>& hdrTypes) {
1455 Mutex::Autolock lock(mStateLock);
1456
1457 auto display = getDisplayDeviceLocked(displayToken);
1458 if (!display) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08001459 ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
Kriti Dang49ad4132021-01-08 11:49:56 +01001460 return NAME_NOT_FOUND;
1461 }
1462
1463 display->overrideHdrTypes(hdrTypes);
1464 dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1465 return NO_ERROR;
1466}
1467
Tej Singhe2751772021-04-06 22:05:29 -07001468status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) {
1469 *success = mTimeStats->onPullAtom(atomId, pulledData);
1470 return NO_ERROR;
1471}
1472
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001473status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1474 ui::PixelFormat* outFormat,
1475 ui::Dataspace* outDataspace,
1476 uint8_t* outComponentMask) const {
1477 if (!outFormat || !outDataspace || !outComponentMask) {
1478 return BAD_VALUE;
1479 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001480
1481 Mutex::Autolock lock(mStateLock);
1482
1483 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1484 if (!displayId) {
1485 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001486 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001487
1488 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001489 outDataspace, outComponentMask);
1490}
1491
Kevin DuBois74e53772018-11-19 10:52:38 -08001492status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1493 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001494 uint64_t maxFrames) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001495 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001496 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001497 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1498 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1499 componentMask, maxFrames);
1500 } else {
1501 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1502 return NAME_NOT_FOUND;
1503 }
1504 });
1505
1506 return future.get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001507}
1508
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001509status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1510 uint64_t maxFrames, uint64_t timestamp,
1511 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001512 Mutex::Autolock lock(mStateLock);
1513
1514 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1515 if (!displayId) {
1516 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001517 }
1518
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001519 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001520}
1521
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001522status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1523 if (!outSupported) {
1524 return BAD_VALUE;
1525 }
1526 *outSupported = getRenderEngine().supportsProtectedContent();
1527 return NO_ERROR;
1528}
1529
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001530status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1531 bool* outIsWideColorDisplay) const {
1532 if (!displayToken || !outIsWideColorDisplay) {
1533 return BAD_VALUE;
1534 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001535
1536 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001537 const auto display = getDisplayDeviceLocked(displayToken);
1538 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001539 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001540 }
Peiyong Linff84a152019-05-17 18:36:19 -07001541
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001542 *outIsWideColorDisplay =
1543 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001544 return NO_ERROR;
1545}
1546
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001547status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001548 auto future = mScheduler->schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001549 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001550
Dominik Laskowski6505f792019-09-18 11:10:05 -07001551 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001552 mScheduler->setInjector(enable ? mScheduler->getEventConnection(handle) : nullptr);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001553 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07001554 });
Dominik Laskowski8c001672018-05-30 16:52:06 -07001555
Dominik Laskowski756b7892021-08-04 12:53:59 -07001556 future.wait();
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001557 return NO_ERROR;
1558}
1559
1560status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001561 Mutex::Autolock lock(mStateLock);
Ady Abrahame90dd522020-12-29 12:08:45 -08001562 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(when);
Ady Abraham56b42a42020-12-28 16:48:48 -08001563 const auto expectedPresent = calculateExpectedPresentTime(stats);
Ady Abraham9c53ee72020-07-22 21:16:18 -07001564 return mScheduler->injectVSync(when, /*expectedVSyncTime=*/expectedPresent,
1565 /*deadlineTimestamp=*/expectedPresent)
1566 ? NO_ERROR
1567 : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001568}
1569
Huihong Luo05539a12022-02-23 10:29:40 -08001570status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001571 outLayers->clear();
Dominik Laskowski756b7892021-08-04 12:53:59 -07001572 auto future = mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001573 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Vishnu Nair43bccf82020-06-05 10:53:37 -07001574 mDrawingState.traverseInZOrder([&](Layer* layer) {
1575 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1576 });
Dominik Laskowski756b7892021-08-04 12:53:59 -07001577 });
1578
1579 future.wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001580 return NO_ERROR;
1581}
1582
Peiyong Linc6780972018-10-28 15:24:08 -07001583status_t SurfaceFlinger::getCompositionPreference(
1584 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1585 Dataspace* outWideColorGamutDataspace,
1586 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001587 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001588 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001589 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001590 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001591 return NO_ERROR;
1592}
1593
Dan Stozaec460082018-12-17 15:35:09 -08001594status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1595 const sp<IBinder>& stopLayerHandle,
1596 const sp<IRegionSamplingListener>& listener) {
Leon Scroggins IIIae16b802022-01-12 11:42:05 -05001597 if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
Dan Stozaec460082018-12-17 15:35:09 -08001598 return BAD_VALUE;
1599 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001600
1601 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1602 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001603 return NO_ERROR;
1604}
1605
Dan Stozaec460082018-12-17 15:35:09 -08001606status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001607 if (!listener) {
1608 return BAD_VALUE;
1609 }
Dan Stozaec460082018-12-17 15:35:09 -08001610 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001611 return NO_ERROR;
1612}
Dan Gittik57e63c52019-01-18 16:37:54 +00001613
Alec Mouria9a68a62021-03-04 19:14:50 -08001614status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
Alec Mouriadebf5c2021-01-05 12:57:36 -08001615 if (!listener) {
1616 return BAD_VALUE;
1617 }
1618
Alec Mouria9a68a62021-03-04 19:14:50 -08001619 mFpsReporter->addListener(listener, taskId);
Alec Mouriadebf5c2021-01-05 12:57:36 -08001620 return NO_ERROR;
1621}
1622
1623status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1624 if (!listener) {
1625 return BAD_VALUE;
1626 }
1627 mFpsReporter->removeListener(listener);
1628 return NO_ERROR;
1629}
1630
Galia Peycheva8f04b302021-04-27 13:25:38 +02001631status_t SurfaceFlinger::addTunnelModeEnabledListener(
1632 const sp<gui::ITunnelModeEnabledListener>& listener) {
1633 if (!listener) {
1634 return BAD_VALUE;
1635 }
1636
1637 mTunnelModeEnabledReporter->addListener(listener);
1638 return NO_ERROR;
1639}
1640
1641status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1642 const sp<gui::ITunnelModeEnabledListener>& listener) {
1643 if (!listener) {
1644 return BAD_VALUE;
1645 }
1646
1647 mTunnelModeEnabledReporter->removeListener(listener);
1648 return NO_ERROR;
1649}
1650
Dan Gittik57e63c52019-01-18 16:37:54 +00001651status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1652 bool* outSupport) const {
1653 if (!displayToken || !outSupport) {
1654 return BAD_VALUE;
1655 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001656
1657 Mutex::Autolock lock(mStateLock);
1658
Dan Gittik57e63c52019-01-18 16:37:54 +00001659 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1660 if (!displayId) {
1661 return NAME_NOT_FOUND;
1662 }
Leon Scroggins III5967aec2021-12-29 11:14:22 -05001663 *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001664 return NO_ERROR;
1665}
1666
Alec Mouricdf16792021-12-10 13:16:06 -08001667bool SurfaceFlinger::hasVisibleHdrLayer(const sp<DisplayDevice>& display) {
1668 bool hasHdrLayers = false;
1669 mDrawingState.traverse([&,
1670 compositionDisplay = display->getCompositionDisplay()](Layer* layer) {
1671 hasHdrLayers |= (layer->isVisible() &&
1672 compositionDisplay->includesLayer(layer->getCompositionEngineLayerFE()) &&
1673 isHdrDataspace(layer->getDataSpace()));
1674 });
1675 return hasHdrLayers;
1676}
1677
John Reck22be6962021-03-10 12:59:54 -05001678status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1679 const gui::DisplayBrightness& brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001680 if (!displayToken) {
1681 return BAD_VALUE;
1682 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001683
Dominik Laskowski756b7892021-08-04 12:53:59 -07001684 const char* const whence = __func__;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001685 return ftl::chain(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
John Reckac09e452021-04-07 16:35:37 -04001686 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Alec Mouricdf16792021-12-10 13:16:06 -08001687 const bool supportsDisplayBrightnessCommand =
1688 getHwComposer().getComposer()->isSupported(
1689 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1690 // If we support applying display brightness as a command, then we also support
1691 // dimming SDR layers.
Alec Mouri90a19272021-12-30 14:11:38 -08001692 if (supportsDisplayBrightnessCommand) {
Alec Mouri6da0e272022-02-07 12:45:57 -08001693 auto compositionDisplay = display->getCompositionDisplay();
1694 float currentDimmingRatio =
1695 compositionDisplay->editState().sdrWhitePointNits /
1696 compositionDisplay->editState().displayBrightnessNits;
1697 compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1698 brightness.displayBrightnessNits);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001699 FTL_FAKE_GUARD(kMainThreadContext,
1700 display->stageBrightness(brightness.displayBrightness));
1701
Alec Mouri6da0e272022-02-07 12:45:57 -08001702 if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1703 currentDimmingRatio) {
Alec Mouricdf16792021-12-10 13:16:06 -08001704 scheduleComposite(FrameHint::kNone);
1705 } else {
1706 scheduleCommit(FrameHint::kNone);
1707 }
1708 return ftl::yield<status_t>(OK);
1709 } else {
Alec Mouri90a19272021-12-30 14:11:38 -08001710 return getHwComposer()
1711 .setDisplayBrightness(display->getPhysicalId(),
1712 brightness.displayBrightness,
1713 Hwc2::Composer::DisplayBrightnessOptions{
1714 .applyImmediately = true});
John Reckac09e452021-04-07 16:35:37 -04001715 }
Alec Mouricdf16792021-12-10 13:16:06 -08001716
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001717 } else {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001718 ALOGE("%s: Invalid display token %p", whence, displayToken.get());
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001719 return ftl::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001720 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001721 }))
1722 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001723 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001724}
1725
John Reck88270902021-03-18 11:27:35 -04001726status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1727 const sp<gui::IHdrLayerInfoListener>& listener) {
1728 if (!displayToken) {
1729 return BAD_VALUE;
1730 }
1731
1732 Mutex::Autolock lock(mStateLock);
1733
1734 const auto display = getDisplayDeviceLocked(displayToken);
1735 if (!display) {
1736 return NAME_NOT_FOUND;
1737 }
1738 const auto displayId = display->getId();
1739 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1740 if (!hdrInfoReporter) {
1741 hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1742 }
1743 hdrInfoReporter->addListener(listener);
Robert Carr167bdde2021-07-28 11:26:51 -07001744
1745
1746 mAddingHDRLayerInfoListener = true;
John Reck88270902021-03-18 11:27:35 -04001747 return OK;
1748}
1749
1750status_t SurfaceFlinger::removeHdrLayerInfoListener(
1751 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
1752 if (!displayToken) {
1753 return BAD_VALUE;
1754 }
1755
1756 Mutex::Autolock lock(mStateLock);
1757
1758 const auto display = getDisplayDeviceLocked(displayToken);
1759 if (!display) {
1760 return NAME_NOT_FOUND;
1761 }
1762 const auto displayId = display->getId();
1763 sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1764 if (hdrInfoReporter) {
1765 hdrInfoReporter->removeListener(listener);
1766 }
1767 return OK;
1768}
1769
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001770status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001771 using hardware::power::Boost;
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001772 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001773
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001774 if (powerBoost == Boost::INTERACTION) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001775 mScheduler->onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -07001776 }
1777
1778 return NO_ERROR;
1779}
1780
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001781status_t SurfaceFlinger::getDisplayDecorationSupport(
1782 const sp<IBinder>& displayToken,
1783 std::optional<DisplayDecorationSupport>* outSupport) const {
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001784 if (!displayToken || !outSupport) {
1785 return BAD_VALUE;
1786 }
1787
1788 Mutex::Autolock lock(mStateLock);
1789
1790 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1791 if (!displayId) {
1792 return NAME_NOT_FOUND;
1793 }
Leon Scroggins IIIe7c51c62022-02-01 15:53:54 -05001794 getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05001795 return NO_ERROR;
1796}
1797
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001798// ----------------------------------------------------------------------------
1799
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001800sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham62f216c2020-10-13 19:07:23 -07001801 ISurfaceComposer::VsyncSource vsyncSource,
1802 ISurfaceComposer::EventRegistrationFlags eventRegistration) {
Ana Krulecc2870422019-01-29 19:00:58 -08001803 const auto& handle =
1804 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001805
Ady Abraham62f216c2020-10-13 19:07:23 -07001806 return mScheduler->createDisplayEventConnection(handle, eventRegistration);
Mathias Agopianbb641242010-05-18 17:06:55 -07001807}
1808
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001809void SurfaceFlinger::scheduleCommit(FrameHint hint) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001810 if (hint == FrameHint::kActive) {
1811 mScheduler->resetIdleTimer();
1812 }
Dan Stoza030fbc12020-02-19 15:32:01 -08001813 mPowerAdvisor.notifyDisplayUpdateImminent();
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07001814 mScheduler->scheduleFrame();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001815}
1816
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001817void SurfaceFlinger::scheduleComposite(FrameHint hint) {
1818 mMustComposite = true;
1819 scheduleCommit(hint);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001820}
1821
1822void SurfaceFlinger::scheduleRepaint() {
1823 mGeometryDirty = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001824 scheduleComposite(FrameHint::kActive);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001825}
1826
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001827void SurfaceFlinger::scheduleSample() {
Dominik Laskowski756b7892021-08-04 12:53:59 -07001828 static_cast<void>(mScheduler->schedule([this] { sample(); }));
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001829}
1830
Ady Abraham2492a022020-07-24 11:09:55 -07001831nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
Marin Shalamanov045b7002021-01-07 16:56:24 +01001832 if (const auto display = getDefaultDisplayDeviceLocked()) {
1833 return display->getVsyncPeriodFromHWC();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001834 }
1835
Marin Shalamanov045b7002021-01-07 16:56:24 +01001836 return 0;
Dominik Laskowski83b88212018-12-11 13:34:06 -08001837}
1838
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001839void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
1840 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Ady Abraham248bce82021-09-16 14:29:59 -07001841 const std::string tracePeriod = [vsyncPeriod]() {
1842 if (ATRACE_ENABLED() && vsyncPeriod) {
1843 std::stringstream ss;
1844 ss << "(" << *vsyncPeriod << ")";
1845 return ss.str();
1846 }
1847 return std::string();
1848 }();
1849 ATRACE_FORMAT("onComposerHalVsync%s", tracePeriod.c_str());
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001850
Steven Thomas3cfac282017-02-06 12:29:30 -08001851 Mutex::Autolock lock(mStateLock);
Ady Abrahame1166472021-07-15 10:56:06 -07001852 const auto displayId = getHwComposer().toPhysicalDisplayId(hwcDisplayId);
1853 if (displayId) {
1854 const auto token = getPhysicalDisplayTokenLocked(*displayId);
1855 const auto display = getDisplayDeviceLocked(token);
Marin Shalamanov045b7002021-01-07 16:56:24 +01001856 display->onVsync(timestamp);
1857 }
1858
Dominik Laskowski075d3172018-05-24 15:50:06 -07001859 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001860 return;
1861 }
1862
Ady Abrahame1166472021-07-15 10:56:06 -07001863 const bool isActiveDisplay =
1864 displayId && getPhysicalDisplayTokenLocked(*displayId) == mActiveDisplayToken;
1865 if (!isActiveDisplay) {
1866 // For now, we don't do anything with non active display vsyncs.
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001867 return;
1868 }
1869
Alec Mourif8e689c2019-05-20 18:32:22 -07001870 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001871 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001872 if (periodFlushed) {
Dominik Laskowski08d05c22020-07-22 00:05:08 -07001873 modulateVsync(&VsyncModulator::onRefreshRateChangeCompleted);
Alec Mouri754c98a2019-03-18 18:53:42 -07001874 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001875}
1876
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001877void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001878 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1879 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001880}
1881
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001882void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
1883 hal::Connection connection) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07001884 const bool connected = connection == hal::Connection::CONNECTED;
1885 ALOGI("%s HAL display %" PRIu64, connected ? "Connecting" : "Disconnecting", hwcDisplayId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001886
Steven Thomasb02664d2017-07-26 18:48:28 -07001887 // Only lock if we're not on the main thread. This function is normally
1888 // called on a hwbinder thread, but for the primary display it's called on
1889 // the main thread with the state lock already held, so don't attempt to
1890 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001891 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001892
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001893 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001894
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001895 if (std::this_thread::get_id() == mMainThreadId) {
1896 // Process all pending hot plug events immediately if we are on the main thread.
1897 processDisplayHotplugEventsLocked();
1898 }
1899
Lloyd Piqueba04e622017-12-14 17:11:26 -08001900 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001901}
1902
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001903void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
1904 hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001905 Mutex::Autolock lock(mStateLock);
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001906 mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001907
1908 if (timeline.refreshRequired) {
1909 scheduleComposite(FrameHint::kNone);
1910 }
Ady Abraham7159f572019-10-11 11:10:18 -07001911}
1912
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001913void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +01001914 // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001915 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1916}
1917
Dominik Laskowski0deb06e2021-04-16 23:18:31 -07001918void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001919 Mutex::Autolock lock(mStateLock);
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001920 scheduleComposite(FrameHint::kNone);
Steven Thomas3cfac282017-02-06 12:29:30 -08001921}
1922
Yichi Chen3401b562022-01-17 15:42:35 +08001923void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
Ady Abrahame9befd72022-02-24 17:24:44 -08001924 ATRACE_CALL();
1925 mScheduler->forceNextResync();
Yichi Chen3401b562022-01-17 15:42:35 +08001926}
1927
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001928void SurfaceFlinger::setVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001929 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001930
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001931 // On main thread to avoid race conditions with display power state.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001932 static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001933 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham9ba25122019-06-03 17:10:55 -07001934
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001935 if (const auto display = getDefaultDisplayDeviceLocked();
1936 display && display->isPoweredOn()) {
Ady Abraham4f960d12021-10-13 16:59:49 -07001937 setHWCVsyncEnabled(display->getPhysicalId(), mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001938 }
Dominik Laskowski8b01cc02020-07-14 19:02:41 -07001939 }));
Mathias Agopian86303202012-07-24 22:46:10 -07001940}
1941
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001942SurfaceFlinger::FenceWithFenceTime SurfaceFlinger::previousFrameFence() {
Ady Abrahamccf4b472021-05-11 19:53:01 -07001943 const auto now = systemTime();
1944 const auto vsyncPeriod = mScheduler->getDisplayStatInfo(now).vsyncPeriod;
1945 const bool expectedPresentTimeIsTheNextVsync = mExpectedPresentTime - now <= vsyncPeriod;
1946 return expectedPresentTimeIsTheNextVsync ? mPreviousPresentFences[0]
1947 : mPreviousPresentFences[1];
Alec Mouri6d414b52020-03-17 11:18:05 -07001948}
1949
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001950bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001951 ATRACE_CALL();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001952 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001953
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001954 if (fence == FenceTime::NO_FENCE) {
Ady Abraham11579302019-09-19 12:35:58 -07001955 return false;
1956 }
1957
Dan Stoza59083052020-04-28 10:13:20 -07001958 const status_t status = fence->wait(graceTimeMs);
1959 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1960 // which calls wait(0) again internally
1961 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001962}
1963
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001964nsecs_t SurfaceFlinger::previousFramePresentTime() {
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001965 const std::shared_ptr<FenceTime>& fence = previousFrameFence().fenceTime;
Alec Mouri6d414b52020-03-17 11:18:05 -07001966
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07001967 if (fence == FenceTime::NO_FENCE) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001968 return Fence::SIGNAL_TIME_INVALID;
1969 }
1970
1971 return fence->getSignalTime();
1972}
1973
Ady Abraham56b42a42020-12-28 16:48:48 -08001974nsecs_t SurfaceFlinger::calculateExpectedPresentTime(DisplayStatInfo stats) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001975 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham8cb21882020-08-26 18:22:05 -07001976 return mVsyncModulator->getVsyncConfig().sfOffset > 0 ? stats.vsyncTime
1977 : stats.vsyncTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001978}
1979
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001980bool SurfaceFlinger::commit(nsecs_t frameTime, int64_t vsyncId, nsecs_t expectedVsyncTime)
1981 FTL_FAKE_GUARD(kMainThreadContext) {
Matt Buckleyef51fba2021-10-12 19:30:12 +00001982 // we set this once at the beginning of commit to ensure consistency throughout the whole frame
1983 mPowerHintSessionData.sessionEnabled = mPowerAdvisor.usePowerHintSession();
1984 if (mPowerHintSessionData.sessionEnabled) {
1985 mPowerHintSessionData.commitStart = systemTime();
1986 }
1987
Dan Stoza28d46a52020-04-28 09:54:54 -07001988 // calculate the expected present time once and use the cached
1989 // value throughout this frame to make sure all layers are
1990 // seeing this same value.
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001991 if (expectedVsyncTime >= frameTime) {
1992 mExpectedPresentTime = expectedVsyncTime;
Snild Dolkow819636c2021-01-22 14:42:08 +01001993 } else {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001994 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(frameTime);
Snild Dolkow819636c2021-01-22 14:42:08 +01001995 mExpectedPresentTime = calculateExpectedPresentTime(stats);
1996 }
1997
1998 const nsecs_t lastScheduledPresentTime = mScheduledPresentTime;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001999 mScheduledPresentTime = expectedVsyncTime;
Dan Stoza28d46a52020-04-28 09:54:54 -07002000
Matt Buckleyef51fba2021-10-12 19:30:12 +00002001 if (mPowerHintSessionData.sessionEnabled) {
2002 mPowerAdvisor.setTargetWorkDuration(mExpectedPresentTime -
2003 mPowerHintSessionData.commitStart);
2004 }
Ady Abraham893c99d2021-04-30 16:00:23 -07002005 const auto vsyncIn = [&] {
2006 if (!ATRACE_ENABLED()) return 0.f;
2007 return (mExpectedPresentTime - systemTime()) / 1e6f;
2008 }();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002009 ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId, vsyncIn,
2010 mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
Ady Abraham893c99d2021-04-30 16:00:23 -07002011
Dan Stoza28d46a52020-04-28 09:54:54 -07002012 // When Backpressure propagation is enabled we want to give a small grace period
2013 // for the present fence to fire instead of just giving up on this frame to handle cases
2014 // where present fence is just about to get signaled.
2015 const int graceTimeForPresentFenceMs =
John Reck2ec53912020-07-07 16:53:55 -07002016 (mPropagateBackpressureClientComposition || !mHadClientComposition) ? 1 : 0;
Dan Stoza28d46a52020-04-28 09:54:54 -07002017
2018 // Pending frames may trigger backpressure propagation.
2019 const TracedOrdinal<bool> framePending = {"PrevFramePending",
2020 previousFramePending(graceTimeForPresentFenceMs)};
2021
2022 // Frame missed counts for metrics tracking.
2023 // A frame is missed if the prior frame is still pending. If no longer pending,
2024 // then we still count the frame as missed if the predicted present time
2025 // was further in the past than when the fence actually fired.
2026
2027 // Add some slop to correct for drift. This should generally be
2028 // smaller than a typical frame duration, but should not be so small
2029 // that it reports reasonable drift as a missed frame.
Ady Abrahame90dd522020-12-29 12:08:45 -08002030 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(systemTime());
Dan Stoza28d46a52020-04-28 09:54:54 -07002031 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
2032 const nsecs_t previousPresentTime = previousFramePresentTime();
2033 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
2034 framePending ||
2035 (previousPresentTime >= 0 &&
Snild Dolkow819636c2021-01-22 14:42:08 +01002036 (lastScheduledPresentTime <
Dan Stoza28d46a52020-04-28 09:54:54 -07002037 previousPresentTime - frameMissedSlop))};
2038 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
2039 mHadDeviceComposition && frameMissed};
2040 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
2041 mHadClientComposition && frameMissed};
2042
2043 if (frameMissed) {
2044 mFrameMissedCount++;
2045 mTimeStats->incrementMissedFrames();
Dan Stoza28d46a52020-04-28 09:54:54 -07002046 }
2047
2048 if (hwcFrameMissed) {
2049 mHwcFrameMissedCount++;
2050 }
2051
2052 if (gpuFrameMissed) {
2053 mGpuFrameMissedCount++;
2054 }
2055
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002056 // If we are in the middle of a mode change and the fence hasn't
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002057 // fired yet just wait for the next commit.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002058 if (mSetActiveModePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002059 if (framePending) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07002060 mScheduler->scheduleFrame();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002061 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002062 }
2063
2064 // We received the present fence from the HWC, so we assume it successfully updated
Marin Shalamanova7fe3042021-01-29 21:02:08 +01002065 // the mode, hence we update SF.
2066 mSetActiveModePending = false;
yuhui.zhang087d3742021-12-11 15:23:52 +08002067 {
2068 Mutex::Autolock lock(mStateLock);
2069 updateInternalStateWithChangedMode();
2070 }
Dan Stoza28d46a52020-04-28 09:54:54 -07002071 }
2072
John Reck2ec53912020-07-07 16:53:55 -07002073 if (framePending) {
Dan Stoza28d46a52020-04-28 09:54:54 -07002074 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002075 scheduleCommit(FrameHint::kNone);
2076 return false;
Dan Stoza28d46a52020-04-28 09:54:54 -07002077 }
2078 }
2079
Dan Stoza28d46a52020-04-28 09:54:54 -07002080 if (mTracingEnabledChanged) {
Vishnu Nair7891e962021-11-11 12:07:21 -08002081 mLayerTracingEnabled = mLayerTracing.isEnabled();
Dan Stoza28d46a52020-04-28 09:54:54 -07002082 mTracingEnabledChanged = false;
2083 }
2084
Ady Abraham29d0da32020-07-16 18:39:33 -07002085 if (mRefreshRateOverlaySpinner) {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07002086 Mutex::Autolock lock(mStateLock);
2087 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002088 display->animateRefreshRateOverlay();
Ady Abraham29d0da32020-07-16 18:39:33 -07002089 }
2090 }
2091
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002092 // Composite if transactions were committed, or if requested by HWC.
2093 bool mustComposite = mMustComposite.exchange(false);
Dan Stoza28d46a52020-04-28 09:54:54 -07002094 {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002095 mFrameTimeline->setSfWakeUp(vsyncId, frameTime, Fps::fromPeriodNsecs(stats.vsyncPeriod));
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07002096
chaviw6b9ffea2021-11-08 09:25:48 -06002097 bool needsTraversal = false;
2098 if (clearTransactionFlags(eTransactionFlushNeeded)) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08002099 needsTraversal |= commitCreatedLayers();
2100 needsTraversal |= flushTransactionQueues(vsyncId);
chaviw6b9ffea2021-11-08 09:25:48 -06002101 }
2102
2103 const bool shouldCommit =
2104 (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2105 if (shouldCommit) {
2106 commitTransactions();
2107 }
2108
2109 if (transactionFlushNeeded()) {
2110 setTransactionFlags(eTransactionFlushNeeded);
2111 }
2112
2113 mustComposite |= shouldCommit;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002114 mustComposite |= latchBuffers();
2115
chaviw6b9ffea2021-11-08 09:25:48 -06002116 // This has to be called after latchBuffers because we want to include the layers that have
2117 // been latched in the commit callback
2118 if (!needsTraversal) {
2119 // Invoke empty transaction callbacks early.
2120 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2121 } else {
2122 // Invoke OnCommit callbacks.
2123 mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2124 }
2125
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002126 updateLayerGeometry();
Dan Stoza28d46a52020-04-28 09:54:54 -07002127 }
2128
2129 // Layers need to get updated (in the previous line) before we can use them for
2130 // choosing the refresh rate.
2131 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2132 // and may eventually call to ~Layer() if it holds the last reference
2133 {
2134 Mutex::Autolock _l(mStateLock);
2135 mScheduler->chooseRefreshRateForContent();
yuhui.zhang087d3742021-12-11 15:23:52 +08002136 setActiveModeInHwcIfNeeded();
Dan Stoza28d46a52020-04-28 09:54:54 -07002137 }
2138
Dan Stoza28d46a52020-04-28 09:54:54 -07002139 updateCursorAsync();
2140 updateInputFlinger();
2141
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002142 if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2143 // This will block and tracing should only be enabled for debugging.
2144 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
2145 }
2146
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002147 persistDisplayBrightness(mustComposite);
Alec Mouricdf16792021-12-10 13:16:06 -08002148
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002149 return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
Dan Stoza28d46a52020-04-28 09:54:54 -07002150}
2151
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002152void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
2153 FTL_FAKE_GUARD(kMainThreadContext) {
Ady Abraham302ebed2022-03-07 16:03:41 -08002154 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002155
Matt Buckleyef51fba2021-10-12 19:30:12 +00002156 if (mPowerHintSessionData.sessionEnabled) {
2157 mPowerHintSessionData.compositeStart = systemTime();
2158 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07002159
Lloyd Piqueab039b52019-02-13 14:22:42 -08002160 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002161 const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002162 refreshArgs.outputs.reserve(displays.size());
2163 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002164 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2165 }
2166 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002167 if (auto layerFE = layer->getCompositionEngineLayerFE())
2168 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002169 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002170 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
Alec Mouri5c9c9602020-09-01 15:10:40 -07002171 for (auto layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002172 if (auto layerFE = layer->getCompositionEngineLayerFE())
2173 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002174 }
2175
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002176 refreshArgs.outputColorSetting = useColorManagement
2177 ? mDisplayColorSetting
2178 : compositionengine::OutputColorSetting::kUnmanaged;
2179 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2180 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002181
2182 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002183 refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002184 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002185 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002186
2187 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2188 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2189 mDrawingState.colorMatrixChanged = false;
2190 }
2191
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002192 refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002193
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07002194 if (mDebugFlashDelay != 0) {
2195 refreshArgs.devOptForceClientComposition = true;
2196 refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002197 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002198
Ady Abraham43065bd2021-12-10 17:22:15 -08002199 const auto expectedPresentTime = mExpectedPresentTime.load();
2200 const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
Ady Abrahamcaba2982021-06-16 16:45:04 -07002201 const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2202 refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -07002203 refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
Dominik Laskowski756b7892021-08-04 12:53:59 -07002204 refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
Ady Abraham43065bd2021-12-10 17:22:15 -08002205 refreshArgs.expectedPresentTime = expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -07002206
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002207 // Store the present time just before calling to the composition engine so we could notify
2208 // the scheduler.
2209 const auto presentTime = systemTime();
2210
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002211 mCompositionEngine->present(refreshArgs);
Matt Buckleyef51fba2021-10-12 19:30:12 +00002212
2213 if (mPowerHintSessionData.sessionEnabled) {
2214 mPowerHintSessionData.presentEnd = systemTime();
2215 }
2216
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002217 mTimeStats->recordFrameDuration(frameTime, systemTime());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002218
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07002219 if (mScheduler->onPostComposition(presentTime)) {
2220 scheduleComposite(FrameHint::kNone);
2221 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002222
Jorim Jaggi9c03b502020-11-24 23:51:31 +01002223 postFrame();
2224 postComposition();
2225
Midas Chien50f52e22020-09-26 17:57:42 +08002226 const bool prevFrameHadClientComposition = mHadClientComposition;
Alec Mouri8f7a0102020-04-15 12:11:10 -07002227
Vishnu Nair9cf89262022-02-26 09:17:49 -08002228 mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
2229 TimeStats::ClientCompositionRecord clientCompositionRecord;
2230 for (const auto& [_, display] : displays) {
2231 const auto& state = display->getCompositionDisplay()->getState();
2232 mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
2233 mHadDeviceComposition |= state.usesDeviceComposition;
2234 mReusedClientComposition |= state.reusedClientComposition;
2235 clientCompositionRecord.predicted |=
2236 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2237 clientCompositionRecord.predictionSucceeded |=
2238 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
Alec Mouri8f7a0102020-04-15 12:11:10 -07002239 }
2240
Vishnu Nair9cf89262022-02-26 09:17:49 -08002241 clientCompositionRecord.hadClientComposition = mHadClientComposition;
2242 clientCompositionRecord.reused = mReusedClientComposition;
2243 clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
2244 mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2245
Yichi Chen28dee2c2020-07-06 21:24:14 +08002246 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002247 const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
2248 modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002249
David Sodman7e4ae112018-02-09 15:02:28 -08002250 mLayersWithQueuedFrames.clear();
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002251 if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
Vishnu Nair00b90132021-11-05 14:03:40 -07002252 // This will block and should only be used for debugging.
Vishnu Nairb64a3b42022-01-13 15:29:32 -08002253 mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
Vishnu Nairdf529052019-06-07 14:53:14 -07002254 }
Robert Carr167bdde2021-07-28 11:26:51 -07002255
2256 mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07002257 mVisibleRegionsDirty = false;
Lloyd Piqueab039b52019-02-13 14:22:42 -08002258
2259 if (mCompositionEngine->needsAnotherUpdate()) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002260 scheduleCommit(FrameHint::kNone);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002261 }
Matt Buckleyef51fba2021-10-12 19:30:12 +00002262
2263 // calculate total render time for performance hinting if adpf cpu hint is enabled,
2264 if (mPowerHintSessionData.sessionEnabled) {
2265 const nsecs_t flingerDuration =
2266 (mPowerHintSessionData.presentEnd - mPowerHintSessionData.commitStart);
2267 mPowerAdvisor.sendActualWorkDuration(flingerDuration, mPowerHintSessionData.presentEnd);
2268 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002269}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002270
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07002271void SurfaceFlinger::updateLayerGeometry() {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002272 ATRACE_CALL();
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07002273
Vishnu Nair4351ad52019-02-11 14:13:02 -08002274 if (mVisibleRegionsDirty) {
2275 computeLayerBounds();
2276 }
2277
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002278 for (auto& layer : mLayersPendingRefresh) {
2279 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002280 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002281 invalidateLayerStack(layer, visibleReg);
2282 }
2283 mLayersPendingRefresh.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002284}
2285
Ana Krulece588e312018-09-18 12:32:24 -07002286void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2287 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002288 // Update queue of past composite+present times and determine the
2289 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002290 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002291 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002292 while (!getBE().mCompositePresentTimes.empty()) {
2293 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002294 // Cached values should have been updated before calling this method,
2295 // which helps avoid duplicate syscalls.
2296 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2297 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2298 break;
2299 }
2300 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002301 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002302 }
2303
2304 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002305 while (getBE().mCompositePresentTimes.size() > 16) {
2306 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002307 }
2308
Ana Krulece588e312018-09-18 12:32:24 -07002309 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002310}
2311
Ana Krulece588e312018-09-18 12:32:24 -07002312void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2313 nsecs_t compositeToPresentLatency) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002314 // Avoid division by 0 by defaulting to 60Hz
2315 const auto vsyncPeriod = stats.vsyncPeriod ?: (60_Hz).getPeriodNsecs();
2316
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002317 // Integer division and modulo round toward 0 not -inf, so we need to
2318 // treat negative and positive offsets differently.
Ady Abraham8287e852020-08-12 14:44:58 -07002319 nsecs_t idealLatency = (mVsyncConfiguration->getCurrentConfigs().late.sfOffset > 0)
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002320 ? (vsyncPeriod -
2321 (mVsyncConfiguration->getCurrentConfigs().late.sfOffset % vsyncPeriod))
2322 : ((-mVsyncConfiguration->getCurrentConfigs().late.sfOffset) % vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002323
Ady Abraham8287e852020-08-12 14:44:58 -07002324 // Just in case mVsyncConfiguration->getCurrentConfigs().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002325 if (idealLatency <= 0) {
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002326 idealLatency = vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002327 }
2328
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002329 // Snap the latency to a value that removes scheduling jitter from the
2330 // composition and present times, which often have >1ms of jitter.
2331 // Reducing jitter is important if an app attempts to extrapolate
2332 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002333 // Snapping also allows an app to precisely calculate
Ady Abraham8287e852020-08-12 14:44:58 -07002334 // mVsyncConfiguration->getCurrentConfigs().late.sf with (presentLatency % interval).
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002335 const nsecs_t bias = vsyncPeriod / 2;
2336 const int64_t extraVsyncs = ((compositeToPresentLatency - idealLatency + bias) / vsyncPeriod);
Ady Abraham8d7e7842022-02-03 01:42:45 +00002337 const nsecs_t snappedCompositeToPresentLatency =
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002338 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002339
David Sodman99974d22017-11-28 12:04:33 -08002340 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002341 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
Ady Abraham3b9e60a2022-02-17 21:43:53 +00002342 getBE().mCompositorTiming.interval = vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002343 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002344}
2345
John Reck49d9ad32022-02-23 19:03:31 -05002346bool SurfaceFlinger::isHdrLayer(Layer* layer) const {
2347 if (!isHdrDataspace(layer->getDataSpace())) {
2348 return false;
2349 }
2350 if (mIgnoreHdrCameraLayers) {
2351 auto buffer = layer->getBuffer();
2352 if (buffer && (buffer->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2353 return false;
2354 }
2355 }
2356 return true;
2357}
2358
ramindani06e518e2022-03-14 18:47:53 +00002359ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2360 bool isPrimary) const {
2361 const auto id = PhysicalDisplayId::tryCast(displayId);
2362 if (!id) {
2363 return ui::ROTATION_0;
2364 }
2365 if (getHwComposer().getComposer()->isSupported(
2366 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2367 switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2368 case Hwc2::AidlTransform::ROT_90:
2369 return ui::ROTATION_90;
2370 case Hwc2::AidlTransform::ROT_180:
2371 return ui::ROTATION_180;
2372 case Hwc2::AidlTransform::ROT_270:
2373 return ui::ROTATION_270;
2374 default:
2375 return ui::ROTATION_0;
2376 }
2377 }
2378
2379 if (isPrimary) {
2380 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2381 switch (primary_display_orientation(Values::ORIENTATION_0)) {
2382 case Values::ORIENTATION_90:
2383 return ui::ROTATION_90;
2384 case Values::ORIENTATION_180:
2385 return ui::ROTATION_180;
2386 case Values::ORIENTATION_270:
2387 return ui::ROTATION_270;
2388 default:
2389 break;
2390 }
2391 }
2392 return ui::ROTATION_0;
2393}
2394
Marin Shalamanov53fc11d2020-11-20 14:00:13 +01002395void SurfaceFlinger::postComposition() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002396 ATRACE_CALL();
2397 ALOGV("postComposition");
2398
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002399 const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002400
David Sodman73beded2017-11-15 11:56:06 -08002401 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002402 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002403 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002404 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002405 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002406 ->getRenderSurface()
2407 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002408 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002409 } else {
2410 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2411 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002412
David Sodman73beded2017-11-15 11:56:06 -08002413 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002414 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002415 mPreviousPresentFences[0].fence =
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002416 display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002417 mPreviousPresentFences[0].fenceTime =
2418 std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
2419
2420 getBE().mDisplayTimeline.push(mPreviousPresentFences[0].fenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002421
Vishnu Nair9a69a042021-06-18 13:19:49 -07002422 nsecs_t now = systemTime();
2423
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002424 // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2425 // information from previous' frame classification is already available when sending jank info
2426 // to clients, so they get jank classification as early as possible.
Vishnu Nair9a69a042021-06-18 13:19:49 -07002427 mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00002428 glCompositionDoneFenceTime);
Jorim Jaggi8d34c902020-12-16 21:43:07 +01002429
Vishnu Nair9a69a042021-06-18 13:19:49 -07002430 const DisplayStatInfo stats = mScheduler->getDisplayStatInfo(now);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002431
Lloyd Piqueab039b52019-02-13 14:22:42 -08002432 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2433 // be sampled a little later than when we started doing work for this frame,
2434 // but that should be okay since updateCompositorTiming has snapping logic.
2435 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002436 mPreviousPresentFences[0].fenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002437 CompositorTiming compositorTiming;
2438 {
David Sodman99974d22017-11-28 12:04:33 -08002439 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2440 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002441 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002442
Robert Carrc747ad02021-06-11 14:01:24 -07002443 for (const auto& layer: mLayersWithQueuedFrames) {
Alec Mouri1dc4bfa2021-10-01 16:31:08 -07002444 layer->onPostComposition(display, glCompositionDoneFenceTime,
2445 mPreviousPresentFences[0].fenceTime, compositorTiming);
Vishnu Nair9a69a042021-06-18 13:19:49 -07002446 layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
Robert Carrc747ad02021-06-11 14:01:24 -07002447 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002448
John Reck88270902021-03-18 11:27:35 -04002449 std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2450 hdrInfoListeners;
Robert Carr167bdde2021-07-28 11:26:51 -07002451 bool haveNewListeners = false;
Alec Mouriadebf5c2021-01-05 12:57:36 -08002452 {
2453 Mutex::Autolock lock(mStateLock);
2454 if (mFpsReporter) {
2455 mFpsReporter->dispatchLayerFps();
2456 }
Galia Peycheva8f04b302021-04-27 13:25:38 +02002457
2458 if (mTunnelModeEnabledReporter) {
2459 mTunnelModeEnabledReporter->updateTunnelModeStatus();
2460 }
John Reck88270902021-03-18 11:27:35 -04002461 hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07002462 for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2463 if (reporter && reporter->hasListeners()) {
2464 if (const auto display = getDisplayDeviceLocked(displayId)) {
2465 hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
John Reck88270902021-03-18 11:27:35 -04002466 }
2467 }
2468 }
Robert Carr167bdde2021-07-28 11:26:51 -07002469 haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2470 mAddingHDRLayerInfoListener = false;
John Reck88270902021-03-18 11:27:35 -04002471 }
2472
Robert Carr167bdde2021-07-28 11:26:51 -07002473 if (haveNewListeners || mSomeDataspaceChanged || mVisibleRegionsWereDirtyThisFrame) {
2474 for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2475 HdrLayerInfoReporter::HdrLayerInfo info;
2476 int32_t maxArea = 0;
2477 mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2478 const auto layerFe = layer->getCompositionEngineLayerFE();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002479 if (layer->isVisible() && compositionDisplay->includesLayer(layerFe)) {
John Reck49d9ad32022-02-23 19:03:31 -05002480 if (isHdrLayer(layer)) {
Robert Carr167bdde2021-07-28 11:26:51 -07002481 const auto* outputLayer =
2482 compositionDisplay->getOutputLayerForLayer(layerFe);
2483 if (outputLayer) {
2484 info.numberOfHdrLayers++;
2485 const auto displayFrame = outputLayer->getState().displayFrame;
2486 const int32_t area = displayFrame.width() * displayFrame.height();
2487 if (area > maxArea) {
2488 maxArea = area;
2489 info.maxW = displayFrame.width();
2490 info.maxH = displayFrame.height();
2491 }
John Reckdb1a16b2021-07-09 13:05:52 -04002492 }
John Reck88270902021-03-18 11:27:35 -04002493 }
2494 }
Robert Carr167bdde2021-07-28 11:26:51 -07002495 });
2496 listener->dispatchHdrLayerInfo(info);
2497 }
Alec Mouriadebf5c2021-01-05 12:57:36 -08002498 }
2499
Robert Carr167bdde2021-07-28 11:26:51 -07002500 mSomeDataspaceChanged = false;
2501 mVisibleRegionsWereDirtyThisFrame = false;
2502
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002503 mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07002504 mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
Robert Carr3d1047b2021-09-20 18:22:32 -07002505 mTransactionCallbackInvoker.clearCompletedTransactions();
Valerie Hau4b678442020-04-14 10:50:42 -07002506
Ady Abrahamed3290f2021-05-17 15:12:14 -07002507 if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002508 mPreviousPresentFences[0].fenceTime->isValid()) {
2509 mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002510 }
2511
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002512 const bool isDisplayConnected =
2513 display && getHwComposer().isConnected(display->getPhysicalId());
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002514
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002515 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002516 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002517 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002518 }
2519 }
2520
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002521 if (mAnimCompositionPending) {
2522 mAnimCompositionPending = false;
2523
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002524 if (mPreviousPresentFences[0].fenceTime->isValid()) {
2525 mAnimFrameTracker.setActualPresentFence(mPreviousPresentFences[0].fenceTime);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002526 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002527 // The HWC doesn't support present fences, so use the refresh
2528 // timestamp instead.
Marin Shalamanov045b7002021-01-07 16:56:24 +01002529 const nsecs_t presentTime = display->getRefreshTimestamp();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002530 mAnimFrameTracker.setActualPresentTime(presentTime);
2531 }
2532 mAnimFrameTracker.advanceFrame();
2533 }
Dan Stozab90cf072015-03-05 11:05:59 -08002534
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002535 mTimeStats->incrementTotalFrames();
Vishnu Nair9b079a22020-01-21 14:36:08 -08002536
Ady Abraham6c1b7ac2021-03-31 16:56:03 -07002537 mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002538
Alec Mouri717bcb62020-02-10 17:07:19 -08002539 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2540 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2541 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2542
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002543 if (isDisplayConnected && !display->isPoweredOn()) {
Lars Svenssond9e54692021-12-21 07:41:57 +01002544 getRenderEngine().cleanupPostRender();
Dan Stozab90cf072015-03-05 11:05:59 -08002545 return;
2546 }
2547
2548 nsecs_t currentTime = systemTime();
2549 if (mHasPoweredOff) {
2550 mHasPoweredOff = false;
2551 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002552 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002553 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002554 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2555 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002556 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002557 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002558 }
David Sodman4a36e932017-11-07 14:29:47 -08002559 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002560 }
David Sodman4a36e932017-11-07 14:29:47 -08002561 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002562
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002563 // Cleanup any outstanding resources due to rendering a prior frame.
2564 getRenderEngine().cleanupPostRender();
2565
Dan Stoza436ccf32018-06-21 12:10:12 -07002566 {
2567 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002568 if (mTexturePool.size() < mTexturePoolSize) {
2569 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002570 const size_t offset = mTexturePool.size();
2571 mTexturePool.resize(mTexturePoolSize);
2572 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2573 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002574 } else if (mTexturePool.size() > mTexturePoolSize) {
2575 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2576 const size_t offset = mTexturePoolSize;
2577 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2578 mTexturePool.resize(mTexturePoolSize);
2579 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002580 }
2581 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002582
Dan Stoza45de5ba2019-04-25 14:12:09 -07002583 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2584 // side-effect of getTotalSize(), so we check that again here
2585 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002586 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002587 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2588 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002589}
2590
chaviw79468ab2021-10-27 11:11:24 -05002591FloatRect SurfaceFlinger::getMaxDisplayBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002592 const ui::Size maxSize = [this] {
2593 ftl::FakeGuard guard(mStateLock);
Vishnu Nairf6f56952022-03-01 20:29:46 -08002594
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002595 // The LayerTraceGenerator tool runs without displays.
2596 if (mDisplays.empty()) return ui::Size{5000, 5000};
Vishnu Nairf6f56952022-03-01 20:29:46 -08002597
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002598 return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
2599 [](ui::Size size, const auto& pair) -> ui::Size {
2600 const auto& display = pair.second;
2601 return {std::max(size.getWidth(), display->getWidth()),
2602 std::max(size.getHeight(), display->getHeight())};
2603 });
2604 }();
chaviwb09c6552021-08-12 17:20:43 -05002605
2606 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
2607 // to ensure it's bigger than an actual display will be.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002608 const float xMax = maxSize.getWidth() * 10.f;
2609 const float yMax = maxSize.getHeight() * 10.f;
2610
2611 return {-xMax, -yMax, xMax, yMax};
chaviw79468ab2021-10-27 11:11:24 -05002612}
2613
2614void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002615 const FloatRect maxBounds = getMaxDisplayBounds();
chaviwb09c6552021-08-12 17:20:43 -05002616 for (const auto& layer : mDrawingState.layersSortedByZ) {
2617 layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002618 }
2619}
2620
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002621void SurfaceFlinger::postFrame() {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002622 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002623 if (display && getHwComposer().isConnected(display->getPhysicalId())) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002624 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002625 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2626 logFrameStats();
2627 }
2628 }
2629}
2630
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002631void SurfaceFlinger::commitTransactions() {
Mathias Agopian841cde52012-03-01 15:44:37 -08002632 ATRACE_CALL();
2633
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002634 // Keep a copy of the drawing state (that is going to be overwritten
2635 // by commitTransactionsLocked) outside of mStateLock so that the side
2636 // effects of the State assignment don't happen with mStateLock held,
2637 // which can cause deadlocks.
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002638 State drawingState(mDrawingState);
2639
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002640 Mutex::Autolock lock(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002641 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642
Mathias Agopianca4d3602011-05-19 15:38:14 -07002643 // Here we're guaranteed that some transaction flags are set
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002644 // so we can call commitTransactionsLocked unconditionally.
2645 // We clear the flags with mStateLock held to guarantee that
2646 // mCurrentState won't change until the transaction is committed.
Dominik Laskowski08d05c22020-07-22 00:05:08 -07002647 modulateVsync(&VsyncModulator::onTransactionCommit);
Dominik Laskowski9e168db2021-05-27 16:05:12 -07002648 commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
Mathias Agopiandea20b12011-05-03 17:04:02 -07002649
Mathias Agopianca4d3602011-05-19 15:38:14 -07002650 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -07002651}
2652
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002653std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
2654 PhysicalDisplayId displayId) const {
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002655 std::vector<HWComposer::HWCDisplayMode> hwcModes;
2656 std::optional<hal::HWDisplayId> activeModeHwcId;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002657
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002658 int attempt = 0;
2659 constexpr int kMaxAttempts = 3;
2660 do {
2661 hwcModes = getHwComposer().getModes(displayId);
2662 activeModeHwcId = getHwComposer().getActiveMode(displayId);
2663 LOG_ALWAYS_FATAL_IF(!activeModeHwcId, "HWC returned no active mode");
2664
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002665 const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
2666 return mode.hwcId == *activeModeHwcId;
2667 };
2668
2669 if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
2670 break;
2671 }
2672 } while (++attempt < kMaxAttempts);
2673
2674 LOG_ALWAYS_FATAL_IF(attempt == kMaxAttempts,
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002675 "After %d attempts HWC still returns an active mode which is not"
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002676 " supported. Active mode ID = %" PRIu64 ". Supported modes = %s",
Marin Shalamanovd3b5c5d2021-02-11 18:26:14 +01002677 kMaxAttempts, *activeModeHwcId, base::Join(hwcModes, ", ").c_str());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002678
2679 DisplayModes oldModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002680 if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
2681 oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
Marin Shalamanov045b7002021-01-07 16:56:24 +01002682 }
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002683
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002684 ui::DisplayModeId nextModeId = 1 +
2685 std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
2686 [](ui::DisplayModeId max, const auto& pair) {
2687 return std::max(max, pair.first.value());
2688 });
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002689
2690 DisplayModes newModes;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002691 for (const auto& hwcMode : hwcModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002692 const DisplayModeId id{nextModeId++};
2693 newModes.try_emplace(id,
2694 DisplayMode::Builder(hwcMode.hwcId)
2695 .setId(id)
2696 .setPhysicalDisplayId(displayId)
2697 .setResolution({hwcMode.width, hwcMode.height})
2698 .setVsyncPeriod(hwcMode.vsyncPeriod)
2699 .setDpiX(hwcMode.dpiX)
2700 .setDpiY(hwcMode.dpiY)
2701 .setGroup(hwcMode.configGroup)
2702 .build());
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002703 }
2704
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002705 const bool sameModes =
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002706 std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002707 [](const auto& lhs, const auto& rhs) {
2708 return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002709 });
2710
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002711 // Keep IDs if modes have not changed.
2712 const auto& modes = sameModes ? oldModes : newModes;
2713 const DisplayModePtr activeMode =
2714 std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
2715 return pair.second->getHwcId() == activeModeHwcId;
2716 })->second;
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +01002717
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002718 return {modes, activeMode};
Marin Shalamanov045b7002021-01-07 16:56:24 +01002719}
2720
Lloyd Piqueba04e622017-12-14 17:11:26 -08002721void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2722 for (const auto& event : mPendingHotplugEvents) {
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002723 std::optional<DisplayIdentificationInfo> info =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002724 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002725
Dominik Laskowski075d3172018-05-24 15:50:06 -07002726 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002727 continue;
2728 }
2729
Marin Shalamanova524a092020-07-27 21:39:55 +02002730 const auto displayId = info->id;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002731 const auto it = mPhysicalDisplayTokens.find(displayId);
2732
Peiyong Line9d809e2020-04-14 13:10:48 -07002733 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002734 auto [supportedModes, activeMode] = loadDisplayModes(displayId);
Marin Shalamanova903d032020-12-29 20:35:13 +01002735
Dominik Laskowski55c85402020-01-21 16:25:47 -08002736 if (it == mPhysicalDisplayTokens.end()) {
2737 ALOGV("Creating display %s", to_string(displayId).c_str());
2738
Dominik Laskowski075d3172018-05-24 15:50:06 -07002739 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002740 state.physical = {.id = displayId,
2741 .type = getHwComposer().getDisplayConnectionType(displayId),
2742 .hwcDisplayId = event.hwcDisplayId,
Marin Shalamanova903d032020-12-29 20:35:13 +01002743 .deviceProductInfo = std::move(info->deviceProductInfo),
2744 .supportedModes = std::move(supportedModes),
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002745 .activeMode = std::move(activeMode)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002746 state.isSecure = true; // All physical displays are currently considered secure.
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002747 state.displayName = std::move(info->name);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002748
2749 sp<IBinder> token = new BBinder();
2750 mCurrentState.displays.add(token, state);
2751 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002752 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002753 } else {
2754 ALOGV("Recreating display %s", to_string(displayId).c_str());
2755
2756 const auto token = it->second;
2757 auto& state = mCurrentState.displays.editValueFor(token);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002758 state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId
Marin Shalamanova903d032020-12-29 20:35:13 +01002759 state.physical->supportedModes = std::move(supportedModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002760 state.physical->activeMode = std::move(activeMode);
Marin Shalamanovf8c63722020-10-06 13:11:21 +02002761 if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
2762 state.physical->deviceProductInfo = std::move(info->deviceProductInfo);
2763 }
Steven Thomaseb6d2052018-03-20 15:40:48 -07002764 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002765 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002766 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002767
Dominik Laskowski55c85402020-01-21 16:25:47 -08002768 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 if (index >= 0) {
2770 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2771 mInterceptor->saveDisplayDeletion(state.sequenceId);
2772 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002773 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002774 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002775 }
2776
2777 processDisplayChangesLocked();
2778 }
2779
2780 mPendingHotplugEvents.clear();
2781}
2782
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002783void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Marin Shalamanov9cf9e512020-12-02 13:28:06 +01002784 ALOGI("Dispatching display hotplug event displayId=%s, connected=%d",
2785 to_string(displayId).c_str(), connected);
Dominik Laskowski98041832019-08-01 18:35:59 -07002786 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2787 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002788}
2789
Lloyd Pique99d3da52018-01-22 17:48:03 -08002790sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002791 const wp<IBinder>& displayToken,
2792 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002793 const DisplayDeviceState& state,
2794 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002795 const sp<IGraphicBufferProducer>& producer) {
Marin Shalamanov12c9e5a2021-01-07 00:25:35 +01002796 DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002797 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002798 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002799 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002800 creationArgs.hasWideColorGamut = false;
2801 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002802
Dominik Laskowski55c85402020-01-21 16:25:47 -08002803 if (const auto& physical = state.physical) {
2804 creationArgs.connectionType = physical->type;
Marin Shalamanova903d032020-12-29 20:35:13 +01002805 creationArgs.supportedModes = physical->supportedModes;
Ady Abraham3efa3942021-06-24 19:01:25 -07002806 creationArgs.activeModeId = physical->activeMode->getId();
ramindani32cf0602022-03-02 02:30:29 +00002807 const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
2808 getKernelIdleTimerProperties(compositionDisplay->getId());
2809
Ady Abraham3efa3942021-06-24 19:01:25 -07002810 scheduler::RefreshRateConfigs::Config config =
2811 {.enableFrameRateOverride = android::sysprop::enable_frame_rate_override(false),
2812 .frameRateMultipleThreshold =
Ady Abraham9a2ea342021-09-03 17:32:34 -07002813 base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
ramindani32cf0602022-03-02 02:30:29 +00002814 .idleTimerTimeout = idleTimerTimeoutMs,
2815 .kernelIdleTimerController = kernelIdleTimerController};
Ady Abraham3efa3942021-06-24 19:01:25 -07002816 creationArgs.refreshRateConfigs =
2817 std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
2818 creationArgs.activeModeId, config);
Dominik Laskowski55c85402020-01-21 16:25:47 -08002819 }
2820
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002821 if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
2822 creationArgs.isPrimary = id == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002823
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002824 if (useColorManagement) {
2825 std::vector<ColorMode> modes = getHwComposer().getColorModes(*id);
2826 for (ColorMode colorMode : modes) {
2827 if (isWideColorMode(colorMode)) {
2828 creationArgs.hasWideColorGamut = true;
2829 }
2830
2831 std::vector<RenderIntent> renderIntents =
2832 getHwComposer().getRenderIntents(*id, colorMode);
2833 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002834 }
2835 }
tangrobin6753a022018-08-10 10:58:54 +08002836 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002837
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002838 if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
2839 getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
2840 creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002841 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002842
Lloyd Pique90c115d2018-09-18 21:39:42 -07002843 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002844 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002845 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002846
Lloyd Pique99d3da52018-01-22 17:48:03 -08002847 // Make sure that composition can never be stalled by a virtual display
2848 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002849 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002850 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002851 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2852 }
2853
Dominik Laskowski718f9602019-11-09 20:01:35 -08002854 creationArgs.physicalOrientation =
ramindani06e518e2022-03-14 18:47:53 +00002855 getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
2856 ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
Chia-I Wua02871c2018-08-27 14:38:23 -07002857
Lloyd Pique99d3da52018-01-22 17:48:03 -08002858 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002859 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002860
Lloyd Pique9370a482019-10-03 17:58:30 -07002861 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002862
Ady Abraham8565ad22021-06-22 17:45:44 -07002863 nativeWindowSurface->preallocateBuffers();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002864
2865 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002866 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002867 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002868 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002869 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002870 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002871 display->getCompositionDisplay()->setColorProfile(
2872 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2873 RenderIntent::COLORIMETRIC,
2874 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002875 if (!state.isVirtual()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002876 FTL_FAKE_GUARD(kMainThreadContext,
2877 display->setActiveMode(state.physical->activeMode->getId()));
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002878 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002879 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002880
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002881 display->setLayerStack(state.layerStack);
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002882 display->setProjection(state.orientation, state.layerStackSpaceRect,
2883 state.orientedDisplaySpaceRect);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002884 display->setDisplayName(state.displayName);
Vishnu Naira119aaa2021-09-24 07:19:35 -07002885 display->setFlags(state.flags);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002886
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002887 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002888}
2889
Marin Shalamanovae685592020-02-12 17:12:22 +01002890void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2891 const DisplayDeviceState& state) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002892 ui::Size resolution(0, 0);
Marin Shalamanovae685592020-02-12 17:12:22 +01002893 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2894 if (state.physical) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002895 resolution = state.physical->activeMode->getResolution();
Marin Shalamanovae685592020-02-12 17:12:22 +01002896 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2897 } else if (state.surface != nullptr) {
Marin Shalamanov045b7002021-01-07 16:56:24 +01002898 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
Marin Shalamanovae685592020-02-12 17:12:22 +01002899 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
Marin Shalamanov045b7002021-01-07 16:56:24 +01002900 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
Marin Shalamanovae685592020-02-12 17:12:22 +01002901 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002902 int format;
2903 status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002904 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002905 pixelFormat = static_cast<ui::PixelFormat>(format);
Marin Shalamanovae685592020-02-12 17:12:22 +01002906 } else {
2907 // Virtual displays without a surface are dormant:
2908 // they have external state (layer stack, projection,
2909 // etc.) but no internal state (i.e. a DisplayDevice).
2910 return;
2911 }
2912
2913 compositionengine::DisplayCreationArgsBuilder builder;
2914 if (const auto& physical = state.physical) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002915 builder.setId(physical->id);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002916 } else {
Dominik Laskowski263eec42021-07-21 23:13:24 -07002917 builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
Marin Shalamanovae685592020-02-12 17:12:22 +01002918 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002919
Marin Shalamanov045b7002021-01-07 16:56:24 +01002920 builder.setPixels(resolution);
Marin Shalamanovae685592020-02-12 17:12:22 +01002921 builder.setIsSecure(state.isSecure);
Marin Shalamanovae685592020-02-12 17:12:22 +01002922 builder.setPowerAdvisor(&mPowerAdvisor);
Marin Shalamanovae685592020-02-12 17:12:22 +01002923 builder.setName(state.displayName);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002924 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
Alec Mouridd8bf2d2021-05-08 16:36:33 -07002925 compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
Marin Shalamanovae685592020-02-12 17:12:22 +01002926
2927 sp<compositionengine::DisplaySurface> displaySurface;
2928 sp<IGraphicBufferProducer> producer;
2929 sp<IGraphicBufferProducer> bqProducer;
2930 sp<IGraphicBufferConsumer> bqConsumer;
2931 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2932
Marin Shalamanovae685592020-02-12 17:12:22 +01002933 if (state.isVirtual()) {
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002934 const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
2935 LOG_FATAL_IF(!displayId);
2936 auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
2937 bqProducer, bqConsumer, state.displayName);
2938 displaySurface = surface;
2939 producer = std::move(surface);
Marin Shalamanovae685592020-02-12 17:12:22 +01002940 } else {
2941 ALOGE_IF(state.surface != nullptr,
2942 "adding a supported display, but rendering "
2943 "surface is provided (%p), ignoring it",
2944 state.surface.get());
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002945 const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
2946 LOG_FATAL_IF(!displayId);
2947 displaySurface =
2948 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
Dominik Laskowskib0054a22022-03-03 09:03:06 -08002949 state.physical->activeMode->getResolution(),
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002950 ui::Size(maxGraphicsWidth, maxGraphicsHeight));
Marin Shalamanovae685592020-02-12 17:12:22 +01002951 producer = bqProducer;
2952 }
2953
Marin Shalamanov700e6392020-02-12 20:22:26 +01002954 LOG_FATAL_IF(!displaySurface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002955 const auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay),
2956 state, displaySurface, producer);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002957 mDisplays.emplace(displayToken, display);
Ady Abraham3efa3942021-06-24 19:01:25 -07002958 if (display->isPrimary()) {
2959 initScheduler(display);
2960 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01002961 if (!state.isVirtual()) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002962 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002963 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002964}
2965
2966void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002967 auto display = getDisplayDeviceLocked(displayToken);
2968 if (display) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002969 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08002970
2971 if (display->isVirtual()) {
2972 releaseVirtualDisplay(display->getVirtualId());
2973 } else {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02002974 dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
Marin Shalamanovae685592020-02-12 17:12:22 +01002975 }
2976 }
2977
2978 mDisplays.erase(displayToken);
Vishnu Nairf78589c2020-12-02 18:36:03 -08002979
2980 if (display && display->isVirtual()) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07002981 static_cast<void>(mScheduler->schedule([display = std::move(display)] {
Vishnu Nairf78589c2020-12-02 18:36:03 -08002982 // Destroy the display without holding the mStateLock.
2983 // This is a temporary solution until we can manage transaction queues without
2984 // holding the mStateLock.
2985 // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
2986 // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
2987 // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
2988 // ends up running on the main thread causing a deadlock since setTransactionstate
2989 // will try to acquire the mStateLock. Instead we extend the lifetime of
2990 // DisplayDevice and destroy it in the main thread without holding the mStateLock.
2991 // The display will be disconnected and removed from the mDisplays list so it will
2992 // not be accessible.
2993 }));
2994 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002995}
2996
2997void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2998 const DisplayDeviceState& currentState,
2999 const DisplayDeviceState& drawingState) {
3000 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3001 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003002
3003 // Recreate the DisplayDevice if the surface or sequence ID changed.
Marin Shalamanov700e6392020-02-12 20:22:26 +01003004 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov23c31af2020-09-09 15:01:47 +02003005 getRenderEngine().cleanFramebufferCache();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003006
Marin Shalamanovae685592020-02-12 17:12:22 +01003007 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3008 display->disconnect();
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003009 if (display->isVirtual()) {
3010 releaseVirtualDisplay(display->getVirtualId());
3011 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003012 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003013
Marin Shalamanovae685592020-02-12 17:12:22 +01003014 mDisplays.erase(displayToken);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003015
Marin Shalamanov700e6392020-02-12 20:22:26 +01003016 if (const auto& physical = currentState.physical) {
3017 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3018 }
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003019
Marin Shalamanovae685592020-02-12 17:12:22 +01003020 processDisplayAdded(displayToken, currentState);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08003021
Marin Shalamanov700e6392020-02-12 20:22:26 +01003022 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02003023 const auto display = getDisplayDeviceLocked(displayToken);
3024 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003025
3026 // TODO(b/175678251) Call a listener instead.
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07003027 if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
Ady Abraham3efa3942021-06-24 19:01:25 -07003028 updateInternalDisplayVsyncLocked(display);
Marin Shalamanovf7f6b3c2020-12-09 13:19:38 +01003029 }
Marin Shalamanov700e6392020-02-12 20:22:26 +01003030 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003031 return;
3032 }
3033
3034 if (const auto display = getDisplayDeviceLocked(displayToken)) {
3035 if (currentState.layerStack != drawingState.layerStack) {
3036 display->setLayerStack(currentState.layerStack);
3037 }
Evan Rosky2239b372021-05-20 13:43:47 -07003038 if (currentState.flags != drawingState.flags) {
3039 display->setFlags(currentState.flags);
3040 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003041 if ((currentState.orientation != drawingState.orientation) ||
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02003042 (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3043 (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3044 display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3045 currentState.orientedDisplaySpaceRect);
Ady Abraham1273ac12021-08-26 17:31:53 -07003046 if (isDisplayActiveLocked(display)) {
3047 mActiveDisplayTransformHint = display->getTransformHint();
Arthur Hungb6aa9a02021-06-09 14:23:01 +08003048 }
Marin Shalamanovae685592020-02-12 17:12:22 +01003049 }
3050 if (currentState.width != drawingState.width ||
3051 currentState.height != drawingState.height) {
3052 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07003053
Ady Abrahamed3290f2021-05-17 15:12:14 -07003054 if (isDisplayActiveLocked(display)) {
3055 onActiveDisplaySizeChanged(display);
Marin Shalamanovae685592020-02-12 17:12:22 +01003056 }
3057 }
3058 }
3059}
Ady Abraham3efa3942021-06-24 19:01:25 -07003060void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07003061 mVsyncConfiguration->reset();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003062 const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
Ady Abrahamed3290f2021-05-17 15:12:14 -07003063 updatePhaseConfiguration(refreshRate);
3064 mRefreshRateStats->setRefreshRate(refreshRate);
Ady Abrahamed3290f2021-05-17 15:12:14 -07003065}
Marin Shalamanovae685592020-02-12 17:12:22 +01003066
Lloyd Pique347200f2017-12-14 17:00:15 -08003067void SurfaceFlinger::processDisplayChangesLocked() {
3068 // here we take advantage of Vector's copy-on-write semantics to
3069 // improve performance by skipping the transaction entirely when
3070 // know that the lists are identical
3071 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3072 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3073 if (!curr.isIdenticalTo(draw)) {
3074 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08003075
3076 // find the displays that were removed
3077 // (ie: in drawing state but not in current state)
3078 // also handle displays that changed
3079 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01003080 for (size_t i = 0; i < draw.size(); i++) {
3081 const wp<IBinder>& displayToken = draw.keyAt(i);
3082 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003083 if (j < 0) {
3084 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01003085 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08003086 } else {
3087 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01003088 const DisplayDeviceState& currentState = curr[j];
3089 const DisplayDeviceState& drawingState = draw[i];
3090 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08003091 }
Lloyd Pique347200f2017-12-14 17:00:15 -08003092 }
3093
3094 // find displays that were added
3095 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01003096 for (size_t i = 0; i < curr.size(); i++) {
3097 const wp<IBinder>& displayToken = curr.keyAt(i);
3098 if (draw.indexOfKey(displayToken) < 0) {
3099 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08003100 }
3101 }
3102 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08003103
3104 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08003105}
3106
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003107void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3108 // Commit display transactions.
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07003109 const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3110 if (displayTransactionNeeded) {
3111 processDisplayChangesLocked();
3112 processDisplayHotplugEventsLocked();
3113 }
Robert Carrb552ff52021-06-11 13:35:54 -07003114 mForceTransactionDisplayChange = displayTransactionNeeded;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115
Robert Carre450fb52021-06-11 13:21:09 -07003116 if (mSomeChildrenChanged) {
3117 mVisibleRegionsDirty = true;
3118 mSomeChildrenChanged = false;
3119 }
3120
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003121 // Update transform hint.
Vishnu Nair6213bd92020-05-08 17:42:25 -07003122 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003123 // Layers and/or displays have changed, so update the transform hint for each layer.
Mathias Agopian84300952012-11-21 16:02:13 -08003124 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08003125 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08003126 // the hint is set before we acquire a buffer from the surface texture.
3127 //
3128 // NOTE: layer transactions have taken place already, so we use their
3129 // drawing state. However, SurfaceFlinger's own transaction has not
3130 // happened yet, so we must use the current state layer list
3131 // (soon to become the drawing state list).
3132 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003133 sp<const DisplayDevice> hintDisplay;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003134 ui::LayerStack layerStack;
3135
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003136 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08003137 // NOTE: we rely on the fact that layers are sorted by
3138 // layerStack first (so we don't have to traverse the list
3139 // of displays for every layer).
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003140 if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3141 layerStack = filter.layerStack;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003142 hintDisplay = nullptr;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003143
3144 // Find the display that includes the layer.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003145 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003146 if (!display->getCompositionDisplay()->includesLayer(filter)) {
3147 continue;
Mathias Agopian84300952012-11-21 16:02:13 -08003148 }
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003149
3150 // Pick the primary display if another display mirrors the layer.
3151 if (hintDisplay) {
3152 hintDisplay = nullptr;
3153 break;
3154 }
3155
3156 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003157 }
3158 }
Chet Haase91d25932013-04-11 15:24:55 -07003159
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003160 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003161 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3162 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003163
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003164 // could be null when this layer is using a layerStack
3165 // that is not visible on any display. Also can occur at
3166 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003167 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003168 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003169
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003170 layer->updateTransformHint(hintDisplay->getTransformHint());
Robert Carr2047fae2016-11-28 14:09:09 -08003171 });
Mathias Agopian84300952012-11-21 16:02:13 -08003172 }
3173
Robert Carr1f0a16a2016-10-24 16:27:39 -07003174 if (mLayersAdded) {
3175 mLayersAdded = false;
3176 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003177 mVisibleRegionsDirty = true;
3178 }
3179
3180 // some layers might have been removed, so
3181 // we need to update the regions they're exposing.
3182 if (mLayersRemoved) {
3183 mLayersRemoved = false;
3184 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003185 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003186 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003187 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003188 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003189 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003190 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003191 }
Robert Carr2047fae2016-11-28 14:09:09 -08003192 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193 }
3194
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003195 doCommitTransactions();
3196 signalSynchronousTransactions(CountDownLatch::eSyncTransaction);
3197 mAnimTransactionPending = false;
Riley Andrews03414a12014-07-01 14:22:59 -07003198}
3199
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003200void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003201 ATRACE_CALL();
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003202 if (!mInputFlinger) {
Vishnu Nair42a27b52021-11-18 15:35:22 -08003203 return;
3204 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003205
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003206 std::vector<WindowInfo> windowInfos;
3207 std::vector<DisplayInfo> displayInfos;
3208 bool updateWindowInfo = false;
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003209 if (mVisibleRegionsDirty || mInputInfoChanged) {
3210 mInputInfoChanged = false;
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003211 updateWindowInfo = true;
3212 buildWindowInfos(windowInfos, displayInfos);
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003213 }
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003214 if (!updateWindowInfo && mInputWindowCommands.empty()) {
3215 return;
3216 }
3217 BackgroundExecutor::getInstance().execute([updateWindowInfo,
3218 windowInfos = std::move(windowInfos),
3219 displayInfos = std::move(displayInfos),
3220 inputWindowCommands =
3221 std::move(mInputWindowCommands),
3222 inputFlinger = mInputFlinger, this]() {
3223 ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3224 if (updateWindowInfo) {
3225 mWindowInfosListenerInvoker->windowInfosChanged(windowInfos, displayInfos,
3226 inputWindowCommands.syncInputWindows);
3227 } else if (inputWindowCommands.syncInputWindows) {
3228 // If the caller requested to sync input windows, but there are no
3229 // changes to input windows, notify immediately.
3230 windowInfosReported();
3231 }
3232 for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3233 inputFlinger->setFocusedWindow(focusRequest);
3234 }
3235 });
Jaineel Mehtaac331c52021-11-29 21:38:10 +00003236
Arthur Hung6cbb9752019-09-05 16:38:18 +08003237 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003238}
3239
Alec Mouricdf16792021-12-10 13:16:06 -08003240void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3241 const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3242 Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3243 if (!supportsDisplayBrightnessCommand) {
3244 return;
3245 }
3246
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003247 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Alec Mouricdf16792021-12-10 13:16:06 -08003248 if (const auto brightness = display->getStagedBrightness(); brightness) {
3249 if (!needsComposite) {
3250 const status_t error =
3251 getHwComposer()
3252 .setDisplayBrightness(display->getPhysicalId(), *brightness,
3253 Hwc2::Composer::DisplayBrightnessOptions{
3254 .applyImmediately = true})
3255 .get();
3256
3257 ALOGE_IF(error != NO_ERROR,
3258 "Error setting display brightness for display %s: %d (%s)",
3259 display->getDebugName().c_str(), error, strerror(error));
3260 }
3261 display->persistBrightness(needsComposite);
3262 }
3263 }
3264}
3265
Vishnu Nair03ccbd62021-12-01 17:21:16 -08003266void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3267 std::vector<DisplayInfo>& outDisplayInfos) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003268 ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
3269
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003270 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003271 const auto layerStack = display->getLayerStack();
3272 const auto info = display->getInputInfo();
3273
3274 const auto [it, emplaced] = displayInputInfos.try_emplace(layerStack, info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003275 if (emplaced) {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003276 continue;
3277 }
Prabir Pradhand0aba782021-12-14 00:44:21 -08003278
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003279 // If the layer stack is mirrored on multiple displays, the first display that is configured
3280 // to receive input takes precedence.
3281 auto& otherInfo = it->second;
3282 if (otherInfo.receivesInput) {
Prabir Pradhan977e7c32022-02-15 04:55:52 -08003283 ALOGW_IF(display->receivesInput(),
3284 "Multiple displays claim to accept input for the same layer stack: %u",
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003285 layerStack.id);
3286 } else {
3287 otherInfo = info;
Prabir Pradhand0aba782021-12-14 00:44:21 -08003288 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07003289 }
Robert Carr720e5062018-07-30 17:45:14 -07003290
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003291 static size_t sNumWindowInfos = 0;
3292 outWindowInfos.reserve(sNumWindowInfos);
3293 sNumWindowInfos = 0;
3294
Robert Carr720e5062018-07-30 17:45:14 -07003295 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
[1;3C2b9fc252021-02-04 16:16:50 -08003296 if (!layer->needsInputInfo()) return;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003297
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003298 // Do not create WindowInfos for windows on displays that cannot receive input.
3299 if (const auto opt = displayInputInfos.get(layer->getLayerStack())) {
3300 const auto& info = opt->get();
3301 outWindowInfos.push_back(layer->fillInputInfo(info.transform, info.isSecure));
Vishnu Nair16a938f2021-09-24 07:14:54 -07003302 }
Robert Carr720e5062018-07-30 17:45:14 -07003303 });
Prabir Pradhand0aba782021-12-14 00:44:21 -08003304
Dominik Laskowski9f410f02022-01-08 16:22:46 -08003305 sNumWindowInfos = outWindowInfos.size();
3306
3307 outDisplayInfos.reserve(displayInputInfos.size());
3308 for (const auto& [_, info] : displayInputInfos) {
3309 outDisplayInfos.push_back(info.info);
Prabir Pradhand0aba782021-12-14 00:44:21 -08003310 }
Robert Carr720e5062018-07-30 17:45:14 -07003311}
3312
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003313void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003314 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003315 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02003316 if (HalDisplayId::tryCast(display->getId())) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003317 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07003318 }
3319 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08003320
3321 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07003322}
3323
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003324void SurfaceFlinger::requestDisplayMode(DisplayModePtr mode, DisplayModeEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08003325 // If this is called from the main thread mStateLock must be locked before
3326 // Currently the only way to call this function from the main thread is from
Ady Abraham62a0be22020-12-08 16:54:10 -08003327 // Scheduler::chooseRefreshRateForContent
Ady Abraham8a82ba62020-01-17 12:43:17 -08003328
3329 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003330
3331 const auto display = getDefaultDisplayDeviceLocked();
3332 if (!display || mBootStage != BootStage::FINISHED) {
3333 return;
3334 }
3335 ATRACE_CALL();
3336
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003337 if (!display->refreshRateConfigs().isModeAllowed(mode->getId())) {
3338 ALOGV("Skipping disallowed mode %d", mode->getId().value());
Marin Shalamanova63f9ae2021-11-03 15:05:16 +01003339 return;
3340 }
3341
Dominik Laskowskib0054a22022-03-03 09:03:06 -08003342 setDesiredActiveMode({std::move(mode), event});
Ady Abraham2139f732019-11-13 18:56:40 -08003343}
3344
Ady Abraham62a0be22020-12-08 16:54:10 -08003345void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3346 PhysicalDisplayId displayId = [&]() {
3347 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3348 return getDefaultDisplayDeviceLocked()->getPhysicalId();
3349 }();
3350
3351 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3352}
3353
Ady Abraham3efa3942021-06-24 19:01:25 -07003354void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003355 if (mScheduler) {
Ady Abrahamac2bf482021-07-20 10:59:51 -07003356 // If the scheduler is already initialized, this means that we received
3357 // a hotplug(connected) on the primary display. In that case we should
3358 // update the scheduler with the most recent display information.
3359 ALOGW("Scheduler already initialized, updating instead");
3360 mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003361 return;
3362 }
Ady Abraham3efa3942021-06-24 19:01:25 -07003363 const auto currRefreshRate = display->getActiveMode()->getFps();
Marin Shalamanova903d032020-12-29 20:35:13 +01003364 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(*mTimeStats, currRefreshRate,
3365 hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003366
Marin Shalamanova903d032020-12-29 20:35:13 +01003367 mVsyncConfiguration = getFactory().createVsyncConfiguration(currRefreshRate);
Ady Abraham23ea9da2021-07-14 16:32:56 -07003368 mVsyncModulator = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
Ady Abraham9e16a482019-12-03 17:19:41 -08003369
Dominik Laskowski068173d2021-08-11 17:22:59 -07003370 using Feature = scheduler::Feature;
3371 scheduler::FeatureFlags features;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003372
Dominik Laskowski068173d2021-08-11 17:22:59 -07003373 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3374 features |= Feature::kContentDetection;
3375 }
3376 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3377 features |= Feature::kTracePredictedVsync;
3378 }
3379 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
Ady Abrahamde549d42022-01-26 19:19:17 -08003380 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003381 features |= Feature::kPresentFences;
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003382 }
3383
Dominik Laskowski068173d2021-08-11 17:22:59 -07003384 mScheduler = std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),
3385 static_cast<ISchedulerCallback&>(*this),
3386 features);
3387 {
3388 auto configs = display->holdRefreshRateConfigs();
ramindani32cf0602022-03-02 02:30:29 +00003389 if (configs->kernelIdleTimerController().has_value()) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07003390 features |= Feature::kKernelIdleTimer;
3391 }
3392
3393 mScheduler->createVsyncSchedule(features);
3394 mScheduler->setRefreshRateConfigs(std::move(configs));
3395 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -07003396 setVsyncEnabled(false);
3397 mScheduler->startTimers();
3398
Ady Abraham9c53ee72020-07-22 21:16:18 -07003399 const auto configs = mVsyncConfiguration->getCurrentConfigs();
Marin Shalamanova903d032020-12-29 20:35:13 +01003400 const nsecs_t vsyncPeriod = currRefreshRate.getPeriodNsecs();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003401 mAppConnectionHandle =
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -07003402 mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
Ady Abraham9c53ee72020-07-22 21:16:18 -07003403 /*workDuration=*/configs.late.appWorkDuration,
3404 /*readyDuration=*/configs.late.sfWorkDuration,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003405 impl::EventThread::InterceptVSyncsCallback());
3406 mSfConnectionHandle =
Ady Abraham55fa7272020-09-30 19:19:27 -07003407 mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
3408 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3409 /*readyDuration=*/configs.late.sfWorkDuration,
3410 [this](nsecs_t timestamp) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003411 mInterceptor->saveVSyncEvent(timestamp);
3412 });
3413
Dominik Laskowski756b7892021-08-04 12:53:59 -07003414 mScheduler->initVsync(mScheduler->getVsyncDispatch(), *mFrameTimeline->getTokenManager(),
3415 configs.late.sfWorkDuration);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003416
3417 mRegionSamplingThread =
Ady Abraham562c2712021-05-07 15:10:42 -07003418 new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouria9a68a62021-03-04 19:14:50 -08003419 mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01003420 // Dispatch a mode change request for the primary display on scheduler
Alec Mouri60aee1c2019-10-28 16:18:59 -07003421 // initialization, so that the EventThreads always contain a reference to a
3422 // prior configuration.
3423 //
3424 // This is a bit hacky, but this avoids a back-pointer into the main SF
3425 // classes from EventThread, and there should be no run-time binder cost
3426 // anyway since there are no connected apps at this point.
Ady Abraham690f4612021-07-01 23:24:03 -07003427 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, display->getActiveMode());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003428}
3429
Marin Shalamanov5801c942020-12-17 17:00:13 +01003430void SurfaceFlinger::updatePhaseConfiguration(const Fps& refreshRate) {
3431 mVsyncConfiguration->setRefreshRateFps(refreshRate);
Ady Abraham55fa7272020-09-30 19:19:27 -07003432 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
Marin Shalamanov5801c942020-12-17 17:00:13 +01003433 refreshRate.getPeriodNsecs());
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003434}
3435
Ady Abraham55fa7272020-09-30 19:19:27 -07003436void SurfaceFlinger::setVsyncConfig(const VsyncModulator::VsyncConfig& config,
3437 nsecs_t vsyncPeriod) {
Ady Abraham9c53ee72020-07-22 21:16:18 -07003438 mScheduler->setDuration(mAppConnectionHandle,
3439 /*workDuration=*/config.appWorkDuration,
3440 /*readyDuration=*/config.sfWorkDuration);
3441 mScheduler->setDuration(mSfConnectionHandle,
Ady Abraham55fa7272020-09-30 19:19:27 -07003442 /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
3443 /*readyDuration=*/config.sfWorkDuration);
Dominik Laskowski756b7892021-08-04 12:53:59 -07003444 mScheduler->setDuration(config.sfWorkDuration);
Dominik Laskowski08d05c22020-07-22 00:05:08 -07003445}
3446
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003447void SurfaceFlinger::doCommitTransactions() {
Robert Carr6a160312021-05-17 12:08:20 -07003448 ATRACE_CALL();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003449
Lloyd Pique58e24a32019-08-01 15:50:14 -07003450 if (!mLayersPendingRemoval.isEmpty()) {
3451 // Notify removed layers now that they can't be drawn from
3452 for (const auto& l : mLayersPendingRemoval) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003453 // Ensure any buffers set to display on any children are released.
3454 if (l->isRemovedFromCurrentState()) {
3455 l->latchAndReleaseBuffer();
3456 }
3457
3458 // If the layer has been removed and has no parent, then it will not be reachable
3459 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3460 // ensure we can copy its current to drawing state.
3461 if (!l->getParent()) {
3462 mOffscreenLayers.emplace(l.get());
3463 }
3464 }
3465 mLayersPendingRemoval.clear();
3466 }
3467
3468 // If this transaction is part of a window animation then the next frame
3469 // we composite should be considered an animation as well.
3470 mAnimCompositionPending = mAnimTransactionPending;
3471
3472 mDrawingState = mCurrentState;
3473 // clear the "changed" flags in current state
3474 mCurrentState.colorMatrixChanged = false;
3475
Robert Carra70e91c2021-06-11 13:59:52 -07003476 if (mVisibleRegionsDirty) {
3477 for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
3478 rootLayer->commitChildList();
3479 }
Andrei Stanciudadac5a2020-08-05 17:02:34 +03003480 }
Robert Carra70e91c2021-06-11 13:59:52 -07003481
Lloyd Pique58e24a32019-08-01 15:50:14 -07003482 commitOffscreenLayers();
Robert Carr6a0382d2021-07-01 15:57:17 -07003483 if (mNumClones > 0) {
3484 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
3485 }
Lloyd Pique58e24a32019-08-01 15:50:14 -07003486}
3487
chaviw74d90ad2019-04-26 14:45:26 -07003488void SurfaceFlinger::commitOffscreenLayers() {
3489 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003490 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003491 if (layer->clearTransactionFlags(eTransactionNeeded)) {
3492 layer->doTransaction(0);
3493 layer->commitChildList();
3494 }
chaviw74d90ad2019-04-26 14:45:26 -07003495 });
3496 }
3497}
3498
Chia-I Wuab0c3192017-08-01 11:29:00 -07003499void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08003500 for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003501 auto display = displayDevice->getCompositionDisplay();
Dominik Laskowski29fa1462021-04-27 15:51:50 -07003502 if (display->includesLayer(layer->getOutputFilter())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003503 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003504 }
3505 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003506}
3507
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003508bool SurfaceFlinger::latchBuffers() {
Ady Abraham09bd3922019-04-08 10:44:56 -07003509 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003510
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003511 const nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512
Mathias Agopian4fec8732012-06-29 14:12:52 -07003513 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003514 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003515 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003516
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003517 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3518
Eric Penner51c59cd2014-07-28 19:51:58 -07003519 // Store the set of layers that need updates. This set must not change as
3520 // buffers are being latched, as this could result in a deadlock.
3521 // Example: Two producers share the same command stream and:
3522 // 1.) Layer 0 is latched
3523 // 2.) Layer 0 gets a new frame
3524 // 2.) Layer 1 gets a new frame
3525 // 3.) Layer 1 is latched.
3526 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3527 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003528 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003529 if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
3530 const uint32_t flags = layer->doTransaction(0);
3531 if (flags & Layer::eVisibleRegion) {
3532 mVisibleRegionsDirty = true;
3533 }
3534 }
Robert Carrb552ff52021-06-11 13:35:54 -07003535
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003536 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003537 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003538 if (layer->shouldPresentNow(expectedPresentTime)) {
Alec Mouri5c9c9602020-09-01 15:10:40 -07003539 mLayersWithQueuedFrames.emplace(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003540 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003541 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003542 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003543 }
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003544 } else {
Dan Stozaee44edd2015-03-23 15:50:23 -07003545 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003546 }
Robert Carr2047fae2016-11-28 14:09:09 -08003547 });
Robert Carrb552ff52021-06-11 13:35:54 -07003548 mForceTransactionDisplayChange = false;
Robert Carr2047fae2016-11-28 14:09:09 -08003549
chaviw49a108c2019-08-12 11:23:06 -07003550 // The client can continue submitting buffers for offscreen layers, but they will not
3551 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3552 // layers to ensure dequeueBuffer doesn't block indefinitely.
3553 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003554 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003555 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3556 }
3557
Lloyd Piquef2c79392018-12-20 16:23:33 -08003558 if (!mLayersWithQueuedFrames.empty()) {
3559 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3560 // writes to Layer current state. See also b/119481871
3561 Mutex::Autolock lock(mStateLock);
3562
Alec Mouri2f7d9ae2020-11-30 19:32:33 -08003563 for (const auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003564 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003565 mLayersPendingRefresh.push_back(layer);
Lloyd Piquef2c79392018-12-20 16:23:33 -08003566 newDataLatched = true;
3567 }
Vishnu Nair1b700192022-02-04 10:09:47 -08003568 layer->useSurfaceDamage();
Mike Stroyan0cd76192017-04-20 12:10:48 -06003569 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003570 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003571
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003572 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003573
3574 // If we will need to wake up at some time in the future to deal with a
3575 // queued frame that shouldn't be displayed during this vsync period, wake
3576 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003577 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07003578 scheduleCommit(FrameHint::kNone);
Dan Stoza6b9454d2014-11-07 16:00:59 -08003579 }
3580
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003581 // enter boot animation on first buffer latch
3582 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3583 ALOGI("Enter boot animation");
3584 mBootStage = BootStage::BOOTANIMATION;
3585 }
3586
Robert Carr6a0382d2021-07-01 15:57:17 -07003587 if (mNumClones > 0) {
3588 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
3589 }
chaviw74b03172019-08-19 11:09:03 -07003590
Dan Stoza6b9454d2014-11-07 16:00:59 -08003591 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003592 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003593}
3594
Robert Carrc0df3122019-04-11 13:18:21 -07003595status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003596 const sp<Layer>& layer, const wp<Layer>& parent,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003597 bool addToRoot, uint32_t* outTransformHint) {
arthurhungdba591c2021-02-08 17:28:49 +08003598 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
3599 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
3600 ISurfaceComposer::MAX_LAYERS);
3601 return NO_MEMORY;
Dan Stoza7d89d062015-04-30 13:29:25 -07003602 }
3603
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003604 {
3605 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
3606 mCreatedLayers.emplace_back(layer, parent, addToRoot);
3607 }
arthurhungdba591c2021-02-08 17:28:49 +08003608
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003609 layer->updateTransformHint(mActiveDisplayTransformHint);
arthurhungdba591c2021-02-08 17:28:49 +08003610 if (outTransformHint) {
Ady Abraham1273ac12021-08-26 17:31:53 -07003611 *outTransformHint = mActiveDisplayTransformHint;
arthurhungdba591c2021-02-08 17:28:49 +08003612 }
Mathias Agopian96f08192010-06-02 23:28:45 -07003613 // attach this layer to the client
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003614 if (client != nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003615 client->attachLayer(handle, layer);
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08003616 }
Mathias Agopian4f113742011-05-03 16:21:41 -07003617
Vishnu Nair0fc7af52022-01-13 08:11:34 -08003618 setTransactionFlags(eTransactionNeeded);
3619 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003620}
3621
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003622uint32_t SurfaceFlinger::getTransactionFlags() const {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003623 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003624}
3625
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003626uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
3627 return mTransactionFlags.fetch_and(~mask) & mask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628}
3629
Dominik Laskowski94000c42022-03-17 12:55:14 -07003630void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003631 const sp<IBinder>& applyToken, FrameHint frameHint) {
Dominik Laskowski9e168db2021-05-27 16:05:12 -07003632 modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003633
3634 if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07003635 scheduleCommit(frameHint);
Dominik Laskowski94000c42022-03-17 12:55:14 -07003636 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003637}
3638
Ady Abraham9dada822022-02-03 10:26:59 -08003639bool SurfaceFlinger::stopTransactionProcessing(
3640 const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
3641 applyTokensWithUnsignaledTransactions) const {
3642 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3643 // if we are in LatchUnsignaledConfig::AutoSingleLayer
3644 // then we should have only one applyToken for processing.
3645 // so we can stop further transactions on this applyToken.
3646 return !applyTokensWithUnsignaledTransactions.empty();
3647 }
3648
3649 return false;
3650}
3651
ramindani9eff2492022-03-23 00:28:26 +00003652int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
3653 std::vector<TransactionState>& transactions,
3654 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
3655 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
3656 return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3657 applyTokensWithUnsignaledTransactions,
3658 /*tryApplyUnsignaled*/ true);
3659}
3660
Robert Carr79dc06a2022-02-22 15:28:59 -08003661int SurfaceFlinger::flushPendingTransactionQueues(
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003662 std::vector<TransactionState>& transactions,
Robert Carr79dc06a2022-02-22 15:28:59 -08003663 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003664 std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
3665 bool tryApplyUnsignaled) {
Robert Carr79dc06a2022-02-22 15:28:59 -08003666 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003667 auto it = mPendingTransactionQueues.begin();
3668 while (it != mPendingTransactionQueues.end()) {
3669 auto& [applyToken, transactionQueue] = *it;
3670 while (!transactionQueue.empty()) {
3671 if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
3672 ATRACE_NAME("stopTransactionProcessing");
3673 break;
3674 }
3675
3676 auto& transaction = transactionQueue.front();
3677 const auto ready =
3678 transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3679 transaction.isAutoTimestamp,
3680 transaction.desiredPresentTime,
3681 transaction.originUid, transaction.states,
3682 bufferLayersReadyToPresent, transactions.size(),
3683 tryApplyUnsignaled);
3684 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
3685 if (ready == TransactionReadiness::NotReady) {
3686 setTransactionFlags(eTransactionFlushNeeded);
3687 break;
3688 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003689 if (ready == TransactionReadiness::NotReadyBarrier) {
3690 transactionsPendingBarrier++;
3691 setTransactionFlags(eTransactionFlushNeeded);
3692 break;
3693 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003694 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003695 const bool frameNumberChanged = state.bufferData->flags.test(
3696 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003697 if (frameNumberChanged) {
3698 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3699 } else {
3700 // Barrier function only used for BBQ which always includes a frame number
3701 bufferLayersReadyToPresent[state.surface] =
3702 std::numeric_limits<uint64_t>::max();
3703 }
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003704 });
3705 const bool appliedUnsignaled = (ready == TransactionReadiness::ReadyUnsignaled);
3706 if (appliedUnsignaled) {
3707 applyTokensWithUnsignaledTransactions.insert(transaction.applyToken);
3708 }
3709
3710 transactions.emplace_back(std::move(transaction));
3711 transactionQueue.pop();
3712 }
3713
3714 if (transactionQueue.empty()) {
3715 it = mPendingTransactionQueues.erase(it);
3716 mTransactionQueueCV.broadcast();
3717 } else {
3718 it = std::next(it, 1);
3719 }
3720 }
Robert Carr79dc06a2022-02-22 15:28:59 -08003721 return transactionsPendingBarrier;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003722}
3723
Vishnu Nair7891e962021-11-11 12:07:21 -08003724bool SurfaceFlinger::flushTransactionQueues(int64_t vsyncId) {
Valerie Haufce31b82019-04-30 16:41:14 -07003725 // to prevent onHandleDestroyed from being called while the lock is held,
3726 // we must keep a copy of the transactions (specifically the composer
3727 // states) around outside the scope of the lock
ramindani4d48f902021-09-20 21:07:45 +00003728 std::vector<TransactionState> transactions;
Vishnu Nair12f62a02021-02-03 16:23:16 -08003729 // Layer handles that have transactions with buffers that are ready to be applied.
Robert Carr79dc06a2022-02-22 15:28:59 -08003730 std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
Ady Abraham9dada822022-02-03 10:26:59 -08003731 std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
Valerie Haufce31b82019-04-30 16:41:14 -07003732 {
Vishnu Nair12f62a02021-02-03 16:23:16 -08003733 Mutex::Autolock _l(mStateLock);
3734 {
3735 Mutex::Autolock _l(mQueueLock);
Ady Abraham9dada822022-02-03 10:26:59 -08003736
Robert Carr79dc06a2022-02-22 15:28:59 -08003737 int lastTransactionsPendingBarrier = 0;
3738 int transactionsPendingBarrier = 0;
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003739 // First collect transactions from the pending transaction queues.
3740 // We are not allowing unsignaled buffers here as we want to
3741 // collect all the transactions from applyTokens that are ready first.
Robert Carr79dc06a2022-02-22 15:28:59 -08003742 transactionsPendingBarrier =
3743 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3744 applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003745
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003746 // Second, collect transactions from the transaction queue.
3747 // Here as well we are not allowing unsignaled buffers for the same
3748 // reason as above.
Vishnu Nair12f62a02021-02-03 16:23:16 -08003749 while (!mTransactionQueue.empty()) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08003750 auto& transaction = mTransactionQueue.front();
Ady Abraham9dada822022-02-03 10:26:59 -08003751 const bool pendingTransactions =
3752 mPendingTransactionQueues.find(transaction.applyToken) !=
Vishnu Nair12f62a02021-02-03 16:23:16 -08003753 mPendingTransactionQueues.end();
Ady Abraham9dada822022-02-03 10:26:59 -08003754 const auto ready = [&]() REQUIRES(mStateLock) {
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003755 if (pendingTransactions) {
3756 ATRACE_NAME("pendingTransactions");
Ady Abraham9dada822022-02-03 10:26:59 -08003757 return TransactionReadiness::NotReady;
3758 }
3759
3760 return transactionIsReadyToBeApplied(transaction.frameTimelineInfo,
3761 transaction.isAutoTimestamp,
3762 transaction.desiredPresentTime,
3763 transaction.originUid, transaction.states,
3764 bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003765 transactions.size(),
3766 /*tryApplyUnsignaled*/ false);
Ady Abraham9dada822022-02-03 10:26:59 -08003767 }();
Ady Abraham16f48f12022-02-14 21:54:59 -08003768 ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
Robert Carr79dc06a2022-02-22 15:28:59 -08003769 if (ready != TransactionReadiness::Ready) {
3770 if (ready == TransactionReadiness::NotReadyBarrier) {
3771 transactionsPendingBarrier++;
3772 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08003773 mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
Vishnu Nair12f62a02021-02-03 16:23:16 -08003774 } else {
Vishnu Nair83df0342021-03-30 11:50:44 -07003775 transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
Xiang Wang76236e12022-03-22 17:25:30 +00003776 const bool frameNumberChanged = state.bufferData->flags.test(
3777 BufferData::BufferDataChange::frameNumberChanged);
Robert Carr79dc06a2022-02-22 15:28:59 -08003778 if (frameNumberChanged) {
3779 bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
3780 } else {
3781 // Barrier function only used for BBQ which always includes a frame number.
3782 // This value only used for barrier logic.
3783 bufferLayersReadyToPresent[state.surface] =
3784 std::numeric_limits<uint64_t>::max();
3785 }
Xiang Wang76236e12022-03-22 17:25:30 +00003786 });
Ady Abraham9dada822022-02-03 10:26:59 -08003787 transactions.emplace_back(std::move(transaction));
Valerie Haufce31b82019-04-30 16:41:14 -07003788 }
ramindani4d48f902021-09-20 21:07:45 +00003789 mTransactionQueue.pop_front();
Ady Abrahame46243a2021-02-23 19:33:49 -08003790 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
Valerie Haufce31b82019-04-30 16:41:14 -07003791 }
Arthur Hung58144272021-01-16 03:43:53 +00003792
Robert Carr79dc06a2022-02-22 15:28:59 -08003793 // Transactions with a buffer pending on a barrier may be on a different applyToken
3794 // than the transaction which satisfies our barrier. In fact this is the exact use case
3795 // that the primitive is designed for. This means we may first process
3796 // the barrier dependent transaction, determine it ineligible to complete
3797 // and then satisfy in a later inner iteration of flushPendingTransactionQueues.
3798 // The barrier dependent transaction was eligible to be presented in this frame
3799 // but we would have prevented it without case. To fix this we continually
3800 // loop through flushPendingTransactionQueues until we perform an iteration
3801 // where the number of transactionsPendingBarrier doesn't change. This way
3802 // we can continue to resolve dependency chains of barriers as far as possible.
3803 while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
3804 lastTransactionsPendingBarrier = transactionsPendingBarrier;
3805 transactionsPendingBarrier =
3806 flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3807 applyTokensWithUnsignaledTransactions,
3808 /*tryApplyUnsignaled*/ false);
3809 }
3810
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003811 // We collected all transactions that could apply without latching unsignaled buffers.
3812 // If we are allowing latch unsignaled of some form, now it's the time to go over the
3813 // transactions that were not applied and try to apply them unsignaled.
3814 if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
ramindani9eff2492022-03-23 00:28:26 +00003815 flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
3816 applyTokensWithUnsignaledTransactions);
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003817 }
3818
Vishnu Nair7891e962021-11-11 12:07:21 -08003819 return applyTransactions(transactions, vsyncId);
Arthur Hung58144272021-01-16 03:43:53 +00003820 }
ramindani4d48f902021-09-20 21:07:45 +00003821 }
3822}
3823
Vishnu Nair7891e962021-11-11 12:07:21 -08003824bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
3825 int64_t vsyncId) {
ramindani4d48f902021-09-20 21:07:45 +00003826 bool needsTraversal = false;
3827 // Now apply all transactions.
Robert Carrff7663b2022-02-08 12:46:49 -08003828 for (auto& transaction : transactions) {
ramindani4d48f902021-09-20 21:07:45 +00003829 needsTraversal |=
3830 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
3831 transaction.displays, transaction.flags,
3832 transaction.inputWindowCommands,
3833 transaction.desiredPresentTime, transaction.isAutoTimestamp,
3834 transaction.buffer, transaction.postTime,
3835 transaction.permissions, transaction.hasListenerCallbacks,
3836 transaction.listenerCallbacks, transaction.originPid,
3837 transaction.originUid, transaction.id);
3838 if (transaction.transactionCommittedSignal) {
3839 mTransactionCommittedSignals.emplace_back(
3840 std::move(transaction.transactionCommittedSignal));
3841 }
3842 }
Vishnu Nair7891e962021-11-11 12:07:21 -08003843
Dominik Laskowski46471e62022-01-14 15:34:03 -08003844 if (mTransactionTracing) {
3845 mTransactionTracing->addCommittedTransactions(transactions, vsyncId);
Vishnu Nair7891e962021-11-11 12:07:21 -08003846 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07003847 return needsTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003848}
3849
3850bool SurfaceFlinger::transactionFlushNeeded() {
Arthur Hung58144272021-01-16 03:43:53 +00003851 Mutex::Autolock _l(mQueueLock);
Robert Carr79bf8a92021-03-11 16:24:28 -08003852 return !mPendingTransactionQueues.empty() || !mTransactionQueue.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003853}
3854
Ady Abraham8db10102021-03-15 17:19:23 -07003855bool SurfaceFlinger::frameIsEarly(nsecs_t expectedPresentTime, int64_t vsyncId) const {
3856 // The amount of time SF can delay a frame if it is considered early based
3857 // on the VsyncModulator::VsyncConfig::appWorkDuration
3858 constexpr static std::chrono::nanoseconds kEarlyLatchMaxThreshold = 100ms;
3859
3860 const auto currentVsyncPeriod = mScheduler->getDisplayStatInfo(systemTime()).vsyncPeriod;
3861 const auto earlyLatchVsyncThreshold = currentVsyncPeriod / 2;
3862
3863 const auto prediction = mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
3864 if (!prediction.has_value()) {
3865 return false;
3866 }
3867
3868 if (std::abs(prediction->presentTime - expectedPresentTime) >=
3869 kEarlyLatchMaxThreshold.count()) {
3870 return false;
3871 }
3872
3873 return prediction->presentTime >= expectedPresentTime &&
3874 prediction->presentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
3875}
Ady Abraham9dada822022-02-03 10:26:59 -08003876bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
Ady Abraham2739e832022-02-14 17:42:00 -08003877 size_t numStates, size_t totalTXapplied) const {
Ady Abraham9dada822022-02-03 10:26:59 -08003878 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
3879 ALOGV("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
3880 return false;
3881 }
Ady Abraham8db10102021-03-15 17:19:23 -07003882
Ady Abraham9dada822022-02-03 10:26:59 -08003883 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
3884 ALOGV("%s: true (LatchUnsignaledConfig::Always)", __func__);
3885 return true;
3886 }
3887
3888 // We only want to latch unsignaled when a single layer is updated in this
3889 // transaction (i.e. not a blast sync transaction).
3890 if (numStates != 1) {
3891 ALOGV("%s: false (numStates=%zu)", __func__, numStates);
3892 return false;
3893 }
3894
Ady Abraham2739e832022-02-14 17:42:00 -08003895 if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
3896 if (totalTXapplied > 0) {
3897 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; totalTXapplied=%zu)",
3898 __func__, totalTXapplied);
3899 return false;
3900 }
3901
3902 // We don't want to latch unsignaled if are in early / client composition
3903 // as it leads to jank due to RenderEngine waiting for unsignaled buffer
3904 // or window animations being slow.
3905 const auto isDefaultVsyncConfig = mVsyncModulator->isVsyncConfigDefault();
3906 if (!isDefaultVsyncConfig) {
3907 ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
3908 __func__);
3909 return false;
3910 }
Ady Abraham9dada822022-02-03 10:26:59 -08003911 }
3912
3913 if (!layer->simpleBufferUpdate(state)) {
3914 ALOGV("%s: false (!simpleBufferUpdate)", __func__);
3915 return false;
3916 }
3917
3918 ALOGV("%s: true", __func__);
3919 return true;
3920}
3921
3922auto SurfaceFlinger::transactionIsReadyToBeApplied(
Ady Abraham43752eb2021-03-04 16:24:25 -08003923 const FrameTimelineInfo& info, bool isAutoTimestamp, int64_t desiredPresentTime,
Ady Abraham5690bda2021-03-12 15:01:18 -08003924 uid_t originUid, const Vector<ComposerState>& states,
Robert Carr79dc06a2022-02-22 15:28:59 -08003925 const std::unordered_map<
3926 sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003927 size_t totalTXapplied, bool tryApplyUnsignaled) const -> TransactionReadiness {
Ady Abraham3bea4252021-11-30 23:18:13 +00003928 ATRACE_FORMAT("transactionIsReadyToBeApplied vsyncId: %" PRId64, info.vsyncId);
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003929 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003930 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3931 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003932 if (!isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
Marissa Wall17b4e452018-12-26 16:32:34 -08003933 desiredPresentTime < expectedPresentTime + s2ns(1)) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003934 ATRACE_NAME("not current");
Ady Abraham9dada822022-02-03 10:26:59 -08003935 return TransactionReadiness::NotReady;
Marissa Wall17b4e452018-12-26 16:32:34 -08003936 }
3937
Ady Abraham5690bda2021-03-12 15:01:18 -08003938 if (!mScheduler->isVsyncValid(expectedPresentTime, originUid)) {
3939 ATRACE_NAME("!isVsyncValid");
Ady Abraham9dada822022-02-03 10:26:59 -08003940 return TransactionReadiness::NotReady;
Ady Abraham5690bda2021-03-12 15:01:18 -08003941 }
3942
Ady Abraham8db10102021-03-15 17:19:23 -07003943 // If the client didn't specify desiredPresentTime, use the vsyncId to determine the expected
3944 // present time of this transaction.
3945 if (isAutoTimestamp && frameIsEarly(expectedPresentTime, info.vsyncId)) {
3946 ATRACE_NAME("frameIsEarly");
Ady Abraham9dada822022-02-03 10:26:59 -08003947 return TransactionReadiness::NotReady;
Ady Abraham8db10102021-03-15 17:19:23 -07003948 }
3949
Ady Abraham9dada822022-02-03 10:26:59 -08003950 bool fenceUnsignaled = false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003951 for (const ComposerState& state : states) {
3952 const layer_state_t& s = state.state;
Ady Abrahamf20c1922020-12-21 18:39:01 -08003953 sp<Layer> layer = nullptr;
3954 if (s.surface) {
Vishnu Nairf9096652021-07-20 18:49:42 -07003955 layer = fromHandle(s.surface).promote();
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003956 } else if (s.hasBufferChanges()) {
Ady Abrahamf20c1922020-12-21 18:39:01 -08003957 ALOGW("Transaction with buffer, but no Layer?");
3958 continue;
3959 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -08003960 if (!layer) {
3961 continue;
3962 }
Ady Abraham43752eb2021-03-04 16:24:25 -08003963
Robert Carr79dc06a2022-02-22 15:28:59 -08003964 if (s.hasBufferChanges() && s.bufferData->hasBarrier &&
3965 ((layer->getDrawingState().frameNumber) < s.bufferData->barrierFrameNumber)) {
3966 const bool willApplyBarrierFrame =
3967 (bufferLayersReadyToPresent.find(s.surface) != bufferLayersReadyToPresent.end()) &&
3968 (bufferLayersReadyToPresent.at(s.surface) >= s.bufferData->barrierFrameNumber);
3969 if (!willApplyBarrierFrame) {
3970 ATRACE_NAME("NotReadyBarrier");
3971 return TransactionReadiness::NotReadyBarrier;
3972 }
3973 }
3974
Ady Abrahame1bfaac2022-02-22 21:32:08 -08003975 const bool allowLatchUnsignaled = tryApplyUnsignaled &&
Ady Abraham9dada822022-02-03 10:26:59 -08003976 shouldLatchUnsignaled(layer, s, states.size(), totalTXapplied);
Ady Abraham16f48f12022-02-14 21:54:59 -08003977 ATRACE_FORMAT("%s allowLatchUnsignaled=%s", layer->getName().c_str(),
3978 allowLatchUnsignaled ? "true" : "false");
Ady Abraham9dada822022-02-03 10:26:59 -08003979
3980 const bool acquireFenceChanged = s.bufferData &&
3981 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
3982 s.bufferData->acquireFence;
3983 fenceUnsignaled = fenceUnsignaled ||
3984 (acquireFenceChanged &&
3985 s.bufferData->acquireFence->getStatus() == Fence::Status::Unsignaled);
3986
3987 if (fenceUnsignaled && !allowLatchUnsignaled) {
3988 ATRACE_NAME("fence unsignaled");
3989 return TransactionReadiness::NotReady;
3990 }
3991
Vishnu Nairddf9b5c2021-03-29 18:53:41 -07003992 if (s.hasBufferChanges()) {
Ady Abraham29d16cb2021-03-08 13:19:21 -08003993 // If backpressure is enabled and we already have a buffer to commit, keep the
3994 // transaction in the queue.
Robert Carr79dc06a2022-02-22 15:28:59 -08003995 const bool hasPendingBuffer = bufferLayersReadyToPresent.find(s.surface) !=
3996 bufferLayersReadyToPresent.end();
Ady Abraham29d16cb2021-03-08 13:19:21 -08003997 if (layer->backpressureEnabled() && hasPendingBuffer && isAutoTimestamp) {
Ady Abraham2f43b202021-03-12 12:34:52 -08003998 ATRACE_NAME("hasPendingBuffer");
Ady Abraham9dada822022-02-03 10:26:59 -08003999 return TransactionReadiness::NotReady;
Ady Abraham29d16cb2021-03-08 13:19:21 -08004000 }
Marissa Wall713b63f2018-10-17 15:42:43 -07004001 }
4002 }
Ady Abraham9dada822022-02-03 10:26:59 -08004003 return fenceUnsignaled ? TransactionReadiness::ReadyUnsignaled : TransactionReadiness::Ready;
Marissa Wall713b63f2018-10-17 15:42:43 -07004004}
4005
arthurhungf1b7c7b2021-03-03 17:42:23 +08004006void SurfaceFlinger::queueTransaction(TransactionState& state) {
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004007 Mutex::Autolock lock(mQueueLock);
Ady Abrahame46243a2021-02-23 19:33:49 -08004008
arthurhungf1b7c7b2021-03-03 17:42:23 +08004009 // Generate a CountDownLatch pending state if this is a synchronous transaction.
4010 if ((state.flags & eSynchronous) || state.inputWindowCommands.syncInputWindows) {
4011 state.transactionCommittedSignal = std::make_shared<CountDownLatch>(
Arthur Hung2274a312021-04-28 15:13:06 +00004012 (state.inputWindowCommands.syncInputWindows
4013 ? (CountDownLatch::eSyncInputWindows | CountDownLatch::eSyncTransaction)
4014 : CountDownLatch::eSyncTransaction));
arthurhungf1b7c7b2021-03-03 17:42:23 +08004015 }
4016
ramindani4d48f902021-09-20 21:07:45 +00004017 mTransactionQueue.emplace_back(state);
Ady Abrahame46243a2021-02-23 19:33:49 -08004018 ATRACE_INT("TransactionQueue", mTransactionQueue.size());
4019
Ady Abrahame46243a2021-02-23 19:33:49 -08004020 const auto schedule = [](uint32_t flags) {
Ady Abraham8cbd3072021-03-15 16:39:06 -07004021 if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4022 if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
Ady Abrahame46243a2021-02-23 19:33:49 -08004023 return TransactionSchedule::Late;
4024 }(state.flags);
4025
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07004026 const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4027
4028 setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken, frameHint);
Ady Abrahame46243a2021-02-23 19:33:49 -08004029}
4030
arthurhungf1b7c7b2021-03-03 17:42:23 +08004031void SurfaceFlinger::waitForSynchronousTransaction(
4032 const CountDownLatch& transactionCommittedSignal) {
4033 // applyTransactionState is called on the main SF thread. While a given process may wish
4034 // to wait on synchronous transactions, the main SF thread should apply the transaction and
4035 // set the value to notify this after committed.
Ady Abrahame9ebce02022-02-03 12:05:06 -08004036 if (!transactionCommittedSignal.wait_until(
4037 std::chrono::nanoseconds(mAnimationTransactionTimeout))) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004038 ALOGE("setTransactionState timed out!");
Ady Abrahame46243a2021-02-23 19:33:49 -08004039 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004040}
Ady Abrahame46243a2021-02-23 19:33:49 -08004041
Arthur Hung2274a312021-04-28 15:13:06 +00004042void SurfaceFlinger::signalSynchronousTransactions(const uint32_t flag) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004043 for (auto it = mTransactionCommittedSignals.begin();
4044 it != mTransactionCommittedSignals.end();) {
Arthur Hung2274a312021-04-28 15:13:06 +00004045 if ((*it)->countDown(flag)) {
arthurhungf1b7c7b2021-03-03 17:42:23 +08004046 it = mTransactionCommittedSignals.erase(it);
4047 } else {
4048 it++;
Ady Abrahame46243a2021-02-23 19:33:49 -08004049 }
4050 }
4051}
4052
chaviw308ddba2020-08-11 16:23:51 -07004053status_t SurfaceFlinger::setTransactionState(
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10004054 const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004055 const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4056 const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
Ady Abrahamf0c56492020-12-17 18:04:15 -08004057 bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004058 const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07004059 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08004060
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004061 uint32_t permissions =
Robert Carrde6d7b42022-01-07 18:23:06 -08004062 callingThreadHasUnscopedSurfaceFlingerAccess() ?
4063 layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004064 // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
4065 // permissions.
Robert Carrde6d7b42022-01-07 18:23:06 -08004066 if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004067 callingThreadHasRotateSurfaceFlingerAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004068 permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004069 }
4070
Leon Scroggins9a20f722021-12-28 14:43:12 +00004071 if (callingThreadHasInternalSystemWindowAccess()) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004072 permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
Leon Scroggins9a20f722021-12-28 14:43:12 +00004073 }
4074
Robert Carrde6d7b42022-01-07 18:23:06 -08004075 if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
Ady Abraham8cbd3072021-03-15 16:39:06 -07004076 (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
4077 ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
4078 flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
arthurhungf1b7c7b2021-03-03 17:42:23 +08004079 }
4080
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004081 const int64_t postTime = systemTime();
4082
4083 IPCThreadState* ipc = IPCThreadState::self();
4084 const int originPid = ipc->getCallingPid();
4085 const int originUid = ipc->getCallingUid();
arthurhungf1b7c7b2021-03-03 17:42:23 +08004086 TransactionState state{frameTimelineInfo, states,
4087 displays, flags,
4088 applyToken, inputWindowCommands,
4089 desiredPresentTime, isAutoTimestamp,
4090 uncacheBuffer, postTime,
4091 permissions, hasListenerCallbacks,
4092 listenerCallbacks, originPid,
4093 originUid, transactionId};
Vishnu Nair83df0342021-03-30 11:50:44 -07004094
4095 // Check for incoming buffer updates and increment the pending buffer count.
4096 state.traverseStatesWithBuffers([&](const layer_state_t& state) {
4097 mBufferCountTracker.increment(state.surface->localBinder());
4098 });
Vishnu Nair7891e962021-11-11 12:07:21 -08004099
Dominik Laskowski46471e62022-01-14 15:34:03 -08004100 if (mTransactionTracing) {
4101 mTransactionTracing->addQueuedTransaction(state);
Vishnu Nair7891e962021-11-11 12:07:21 -08004102 }
arthurhungf1b7c7b2021-03-03 17:42:23 +08004103 queueTransaction(state);
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004104
arthurhungf1b7c7b2021-03-03 17:42:23 +08004105 // Check the pending state to make sure the transaction is synchronous.
4106 if (state.transactionCommittedSignal) {
4107 waitForSynchronousTransaction(*state.transactionCommittedSignal);
Arthur Hung58144272021-01-16 03:43:53 +00004108 }
4109
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004110 return NO_ERROR;
4111}
Marissa Wall713b63f2018-10-17 15:42:43 -07004112
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004113bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrff7663b2022-02-08 12:46:49 -08004114 Vector<ComposerState>& states,
Arthur Hung58144272021-01-16 03:43:53 +00004115 const Vector<DisplayState>& displays, uint32_t flags,
4116 const InputWindowCommands& inputWindowCommands,
4117 const int64_t desiredPresentTime, bool isAutoTimestamp,
4118 const client_cache_t& uncacheBuffer,
Vishnu Nair24e3bba2021-02-23 14:19:36 -08004119 const int64_t postTime, uint32_t permissions,
Arthur Hung58144272021-01-16 03:43:53 +00004120 bool hasListenerCallbacks,
4121 const std::vector<ListenerCallbacks>& listenerCallbacks,
4122 int originPid, int originUid, uint64_t transactionId) {
Zhuoyao Zhang3d3540d2021-01-14 05:14:54 +00004123 uint32_t transactionFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08004124 for (const DisplayState& display : displays) {
4125 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07004126 }
4127
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004128 // start and end registration for listeners w/ no surface so they can get their callback. Note
4129 // that listeners with SurfaceControls will start registration during setClientStateLocked
4130 // below.
Valerie Hau9dab9732019-08-20 09:29:25 -07004131 for (const auto& listener : listenerCallbacks) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004132 mTransactionCallbackInvoker.addEmptyTransaction(listener);
Marissa Walld600d572019-03-26 15:38:50 -07004133 }
4134
Marissa Walle2ffb422018-10-12 11:33:52 -07004135 uint32_t clientStateFlags = 0;
Robert Carrff7663b2022-02-08 12:46:49 -08004136 for (int i = 0; i < states.size(); i++) {
4137 ComposerState& state = states.editItemAt(i);
4138 clientStateFlags |= setClientStateLocked(frameTimelineInfo, state, desiredPresentTime,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004139 isAutoTimestamp, postTime, permissions);
Ady Abraham5def7332020-05-29 16:13:47 -07004140 if ((flags & eAnimation) && state.state.surface) {
Dominik Laskowski068173d2021-08-11 17:22:59 -07004141 if (const auto layer = fromHandle(state.state.surface).promote()) {
4142 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
Ady Abrahamf0c56492020-12-17 18:04:15 -08004143 mScheduler->recordLayerHistory(layer.get(),
4144 isAutoTimestamp ? 0 : desiredPresentTime,
Dominik Laskowski068173d2021-08-11 17:22:59 -07004145 LayerUpdateType::AnimationTX);
Ady Abraham5def7332020-05-29 16:13:47 -07004146 }
4147 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07004148 }
4149
Marissa Walle2ffb422018-10-12 11:33:52 -07004150 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08004151
Robert Carrde6d7b42022-01-07 18:23:06 -08004152 if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) {
Vishnu Nair958da932020-08-21 17:12:37 -07004153 transactionFlags |= addInputWindowCommands(inputWindowCommands);
4154 } else if (!inputWindowCommands.empty()) {
4155 ALOGE("Only privileged callers are allowed to send input commands.");
4156 }
chaviw273171b2018-12-26 11:46:30 -08004157
Marissa Wall947d34e2019-03-29 14:03:53 -07004158 if (uncacheBuffer.isValid()) {
4159 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004160 }
4161
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02004162 // If a synchronous transaction is explicitly requested without any changes, force a transaction
4163 // anyway. This can be used as a flush mechanism for previous async transactions.
4164 // Empty animation transaction can be used to simulate back-pressure, so also force a
4165 // transaction for empty animation transactions.
4166 if (transactionFlags == 0 &&
4167 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07004168 transactionFlags = eTransactionNeeded;
4169 }
4170
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004171 bool needsTraversal = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08004172 if (transactionFlags) {
Arthur Hung1bedccb2020-09-24 10:09:25 +00004173 if (mInterceptor->isEnabled()) {
4174 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags,
Pablo Gamito7eb7ee72020-08-05 10:57:05 +00004175 originPid, originUid, transactionId);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004176 }
4177
Arthur Hung58144272021-01-16 03:43:53 +00004178 // We are on the main thread, we are about to preform a traversal. Clear the traversal bit
4179 // so we don't have to wake up again next frame to preform an unnecessary traversal.
4180 if (transactionFlags & eTraversalNeeded) {
4181 transactionFlags = transactionFlags & (~eTraversalNeeded);
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004182 needsTraversal = true;
Arthur Hung1bedccb2020-09-24 10:09:25 +00004183 }
Arthur Hung58144272021-01-16 03:43:53 +00004184 if (transactionFlags) {
4185 setTransactionFlags(transactionFlags);
Arthur Hung1bedccb2020-09-24 10:09:25 +00004186 }
4187
Jamie Gennis2d5e2302012-10-15 18:24:43 -07004188 if (flags & eAnimation) {
4189 mAnimTransactionPending = true;
4190 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004191 }
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004192
4193 return needsTraversal;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004194}
4195
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004196uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4197 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4198 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07004199
Mathias Agopiane57f2922012-08-09 16:29:12 -07004200 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004201 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4202
4203 const uint32_t what = s.what;
4204 if (what & DisplayState::eSurfaceChanged) {
4205 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4206 state.surface = s.surface;
4207 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07004208 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004209 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004210 if (what & DisplayState::eLayerStackChanged) {
4211 if (state.layerStack != s.layerStack) {
4212 state.layerStack = s.layerStack;
4213 flags |= eDisplayTransactionNeeded;
4214 }
4215 }
Evan Rosky2239b372021-05-20 13:43:47 -07004216 if (what & DisplayState::eFlagsChanged) {
4217 if (state.flags != s.flags) {
4218 state.flags = s.flags;
4219 flags |= eDisplayTransactionNeeded;
4220 }
4221 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004222 if (what & DisplayState::eDisplayProjectionChanged) {
4223 if (state.orientation != s.orientation) {
4224 state.orientation = s.orientation;
4225 flags |= eDisplayTransactionNeeded;
4226 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004227 if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4228 state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004229 flags |= eDisplayTransactionNeeded;
4230 }
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004231 if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4232 state.layerStackSpaceRect = s.layerStackSpaceRect;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07004233 flags |= eDisplayTransactionNeeded;
4234 }
4235 }
4236 if (what & DisplayState::eDisplaySizeChanged) {
4237 if (state.width != s.width) {
4238 state.width = s.width;
4239 flags |= eDisplayTransactionNeeded;
4240 }
4241 if (state.height != s.height) {
4242 state.height = s.height;
4243 flags |= eDisplayTransactionNeeded;
4244 }
4245 }
4246
Mathias Agopiane57f2922012-08-09 16:29:12 -07004247 return flags;
4248}
4249
Steven Thomasd4071902020-03-24 16:02:53 -07004250bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004251 IPCThreadState* ipc = IPCThreadState::self();
4252 const int pid = ipc->getCallingPid();
4253 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07004254 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07004255 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4256 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004257 return false;
4258 }
4259 return true;
4260}
4261
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004262uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
Robert Carrde6d7b42022-01-07 18:23:06 -08004263 ComposerState& composerState,
Vishnu Naircd52e2d2021-10-18 08:42:46 -07004264 int64_t desiredPresentTime, bool isAutoTimestamp,
4265 int64_t postTime, uint32_t permissions) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004266 layer_state_t& s = composerState.state;
4267 s.sanitize(permissions);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004268
4269 std::vector<ListenerCallbacks> filteredListeners;
Valerie Hau9dab9732019-08-20 09:29:25 -07004270 for (auto& listener : s.listeners) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004271 // Starts a registration but separates the callback ids according to callback type. This
4272 // allows the callback invoker to send on latch callbacks earlier.
Valerie Hau9dab9732019-08-20 09:29:25 -07004273 // note that startRegistration will not re-register if the listener has
4274 // already be registered for a prior surface control
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004275
4276 ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4277 if (!onCommitCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004278 filteredListeners.push_back(onCommitCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004279 }
4280
4281 ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4282 if (!onCompleteCallbacks.callbackIds.empty()) {
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004283 filteredListeners.push_back(onCompleteCallbacks);
Vishnu Nairfc46c1e2021-04-21 08:31:32 -07004284 }
Valerie Hau9dab9732019-08-20 09:29:25 -07004285 }
4286
arthurhungdba591c2021-02-08 17:28:49 +08004287 const uint64_t what = s.what;
4288 uint32_t flags = 0;
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004289 sp<Layer> layer = nullptr;
4290 if (s.surface) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08004291 layer = fromHandle(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08004292 } else {
4293 // The client may provide us a null handle. Treat it as if the layer was removed.
4294 ALOGW("Attempt to set client state with a null layer handle");
4295 }
chaviw8b3871a2017-11-01 17:41:01 -07004296 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07004297 for (auto& [listener, callbackIds] : s.listeners) {
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004298 mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07004299 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07004300 }
chaviw8b3871a2017-11-01 17:41:01 -07004301 return 0;
4302 }
4303
Valerie Hau871d6352020-01-29 08:44:02 -08004304 // Only set by BLAST adapter layers
4305 if (what & layer_state_t::eProducerDisconnect) {
4306 layer->onDisconnect();
4307 }
4308
chaviw8b3871a2017-11-01 17:41:01 -07004309 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07004310 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07004311 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004312 }
chaviw8b3871a2017-11-01 17:41:01 -07004313 }
4314 if (what & layer_state_t::eLayerChanged) {
4315 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004316 const auto& p = layer->getParent();
chaviw8b3871a2017-11-01 17:41:01 -07004317 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004318 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004319 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004320 mCurrentState.layersSortedByZ.removeAt(idx);
4321 mCurrentState.layersSortedByZ.add(layer);
4322 // we need traversal (state changed)
4323 // AND transaction (list changed)
4324 flags |= eTransactionNeeded|eTraversalNeeded;
4325 }
chaviw8b3871a2017-11-01 17:41:01 -07004326 } else {
4327 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004328 flags |= eTransactionNeeded|eTraversalNeeded;
4329 }
4330 }
chaviw8b3871a2017-11-01 17:41:01 -07004331 }
4332 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004333 // NOTE: index needs to be calculated before we update the state
Rob Carrc6d2d2b2021-10-25 16:51:49 +00004334 const auto& p = layer->getParent();
Robert Carrbc384962021-01-27 15:44:50 -08004335 const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4336 s.relativeLayerSurfaceControl->getHandle() : nullptr;
Robert Carr503c7042017-09-27 15:06:08 -07004337 if (p == nullptr) {
4338 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrbc384962021-01-27 15:44:50 -08004339 if (layer->setRelativeLayer(relativeHandle, s.z) &&
Pablo Gamito11dcc222020-09-12 15:49:39 +00004340 idx >= 0) {
Robert Carr503c7042017-09-27 15:06:08 -07004341 mCurrentState.layersSortedByZ.removeAt(idx);
4342 mCurrentState.layersSortedByZ.add(layer);
4343 // we need traversal (state changed)
4344 // AND transaction (list changed)
4345 flags |= eTransactionNeeded|eTraversalNeeded;
4346 }
4347 } else {
Robert Carrbc384962021-01-27 15:44:50 -08004348 if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
Robert Carr503c7042017-09-27 15:06:08 -07004349 flags |= eTransactionNeeded|eTraversalNeeded;
4350 }
chaviw8b3871a2017-11-01 17:41:01 -07004351 }
4352 }
4353 if (what & layer_state_t::eSizeChanged) {
4354 if (layer->setSize(s.w, s.h)) {
4355 flags |= eTraversalNeeded;
4356 }
4357 }
4358 if (what & layer_state_t::eAlphaChanged) {
4359 if (layer->setAlpha(s.alpha))
4360 flags |= eTraversalNeeded;
4361 }
4362 if (what & layer_state_t::eColorChanged) {
4363 if (layer->setColor(s.color))
4364 flags |= eTraversalNeeded;
4365 }
Peiyong Lind3788632018-09-18 16:01:31 -07004366 if (what & layer_state_t::eColorTransformChanged) {
4367 if (layer->setColorTransform(s.colorTransform)) {
4368 flags |= eTraversalNeeded;
4369 }
4370 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004371 if (what & layer_state_t::eBackgroundColorChanged) {
4372 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4373 flags |= eTraversalNeeded;
4374 }
4375 }
chaviw8b3871a2017-11-01 17:41:01 -07004376 if (what & layer_state_t::eMatrixChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004377 if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004378 }
4379 if (what & layer_state_t::eTransparentRegionChanged) {
4380 if (layer->setTransparentRegionHint(s.transparentRegion))
4381 flags |= eTraversalNeeded;
4382 }
4383 if (what & layer_state_t::eFlagsChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004384 if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004385 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004386 if (what & layer_state_t::eCornerRadiusChanged) {
4387 if (layer->setCornerRadius(s.cornerRadius))
4388 flags |= eTraversalNeeded;
4389 }
Galia Peycheva33713f72021-05-27 10:24:20 +02004390 if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08004391 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4392 }
Galia Peychevae11d5752021-01-22 13:50:16 +00004393 if (what & layer_state_t::eBlurRegionsChanged) {
Lucas Dupinc3800b82020-10-02 16:24:48 -07004394 if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4395 }
chaviw8b3871a2017-11-01 17:41:01 -07004396 if (what & layer_state_t::eLayerStackChanged) {
4397 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4398 // We only allow setting layer stacks for top level layers,
4399 // everything else inherits layer stack from its parent.
4400 if (layer->hasParent()) {
4401 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004402 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004403 } else if (idx < 0) {
4404 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004405 "that also does not appear in the top level layer list. Something"
4406 " has gone wrong.",
4407 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07004408 } else if (layer->setLayerStack(s.layerStack)) {
4409 mCurrentState.layersSortedByZ.removeAt(idx);
4410 mCurrentState.layersSortedByZ.add(layer);
4411 // we need traversal (state changed)
4412 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07004413 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07004414 }
4415 }
Marissa Wall61c58622018-07-18 10:12:20 -07004416 if (what & layer_state_t::eTransformChanged) {
4417 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4418 }
4419 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4420 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4421 flags |= eTraversalNeeded;
4422 }
4423 if (what & layer_state_t::eCropChanged) {
4424 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4425 }
Marissa Wall61c58622018-07-18 10:12:20 -07004426 if (what & layer_state_t::eDataspaceChanged) {
4427 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4428 }
4429 if (what & layer_state_t::eHdrMetadataChanged) {
4430 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4431 }
4432 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4433 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4434 }
4435 if (what & layer_state_t::eApiChanged) {
4436 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4437 }
4438 if (what & layer_state_t::eSidebandStreamChanged) {
4439 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4440 }
Robert Carr720e5062018-07-30 17:45:14 -07004441 if (what & layer_state_t::eInputInfoChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004442 layer->setInputInfo(*s.windowInfoHandle->getInfo());
4443 flags |= eTraversalNeeded;
Robert Carr720e5062018-07-30 17:45:14 -07004444 }
Vishnu Nairadf632b2021-01-07 14:05:08 -08004445 std::optional<nsecs_t> dequeueBufferTimestamp;
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004446 if (what & layer_state_t::eMetadataChanged) {
Vishnu Nairadf632b2021-01-07 14:05:08 -08004447 dequeueBufferTimestamp = s.metadata.getInt64(METADATA_DEQUEUE_TIME);
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004448
4449 if (const int32_t gameMode = s.metadata.getInt32(METADATA_GAME_MODE, -1); gameMode != -1) {
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004450 // The transaction will be received on the Task layer and needs to be applied to all
4451 // child layers. Child layers that are added at a later point will obtain the game mode
4452 // info through addChild().
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004453 layer->setGameModeForTree(static_cast<GameMode>(gameMode));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00004454 }
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004455
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004456 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4457 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004458 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4459 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4460 flags |= eTraversalNeeded;
4461 }
4462 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07004463 if (what & layer_state_t::eShadowRadiusChanged) {
4464 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
4465 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01004466 if (what & layer_state_t::eFrameRateSelectionPriority) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004467 if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
Ana Krulecc84d09b2019-11-02 23:10:29 +01004468 flags |= eTraversalNeeded;
4469 }
4470 }
Steven Thomas3172e202020-01-06 19:25:30 -08004471 if (what & layer_state_t::eFrameRateChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004472 const auto compatibility =
4473 Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
4474 const auto strategy =
4475 Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
Marin Shalamanovc5986772021-03-16 16:09:49 +01004476
Robert Carrde6d7b42022-01-07 18:23:06 -08004477 if (layer->setFrameRate(
4478 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
4479 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08004480 }
Steven Thomas3172e202020-01-06 19:25:30 -08004481 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07004482 if (what & layer_state_t::eFixedTransformHintChanged) {
4483 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
4484 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
4485 }
4486 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -08004487 if (what & layer_state_t::eAutoRefreshChanged) {
4488 layer->setAutoRefresh(s.autoRefresh);
4489 }
Sally Qi421ffb02022-03-21 19:41:33 -07004490 if (what & layer_state_t::eDimmingEnabledChanged) {
4491 if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
4492 }
Winson Chunga30f7c92021-06-29 15:42:56 -07004493 if (what & layer_state_t::eTrustedOverlayChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004494 if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
4495 flags |= eTraversalNeeded;
Winson Chunga30f7c92021-06-29 15:42:56 -07004496 }
4497 }
John Reckcdb4ed72021-02-04 13:39:33 -05004498 if (what & layer_state_t::eStretchChanged) {
4499 if (layer->setStretchEffect(s.stretchEffect)) {
4500 flags |= eTraversalNeeded;
4501 }
4502 }
chaviwf3f40fe2021-04-27 15:54:02 -05004503 if (what & layer_state_t::eBufferCropChanged) {
4504 if (layer->setBufferCrop(s.bufferCrop)) {
4505 flags |= eTraversalNeeded;
4506 }
4507 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07004508 if (what & layer_state_t::eDestinationFrameChanged) {
4509 if (layer->setDestinationFrame(s.destinationFrame)) {
4510 flags |= eTraversalNeeded;
4511 }
4512 }
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004513 if (what & layer_state_t::eDropInputModeChanged) {
Robert Carrde6d7b42022-01-07 18:23:06 -08004514 if (layer->setDropInputMode(s.dropInputMode)) {
4515 flags |= eTraversalNeeded;
4516 mInputInfoChanged = true;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07004517 }
4518 }
Vishnu Nair14d76922019-08-05 08:41:20 -07004519 // This has to happen after we reparent children because when we reparent to null we remove
4520 // child layers from current state and remove its relative z. If the children are reparented in
4521 // the same transaction, then we have to make sure we reparent the children first so we do not
4522 // lose its relative z order.
4523 if (what & layer_state_t::eReparent) {
4524 bool hadParent = layer->hasParent();
Pablo Gamito11dcc222020-09-12 15:49:39 +00004525 auto parentHandle = (s.parentSurfaceControlForChild)
4526 ? s.parentSurfaceControlForChild->getHandle()
4527 : nullptr;
4528 if (layer->reparent(parentHandle)) {
Vishnu Nair14d76922019-08-05 08:41:20 -07004529 if (!hadParent) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07004530 layer->setIsAtRoot(false);
Vishnu Nair14d76922019-08-05 08:41:20 -07004531 mCurrentState.layersSortedByZ.remove(layer);
4532 }
4533 flags |= eTransactionNeeded | eTraversalNeeded;
4534 }
4535 }
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004536 std::vector<sp<CallbackHandle>> callbackHandles;
4537 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
4538 for (auto& [listener, callbackIds] : filteredListeners) {
4539 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4540 }
4541 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07004542
Vishnu Nairdbbe3852022-01-12 20:22:11 -08004543 if (what & layer_state_t::eBufferChanged) {
4544 std::shared_ptr<renderengine::ExternalTexture> buffer =
4545 getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName());
4546 if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp,
4547 dequeueBufferTimestamp, frameTimelineInfo)) {
4548 flags |= eTraversalNeeded;
4549 }
Ady Abraham8db10102021-03-15 17:19:23 -07004550 } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
4551 layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
Marissa Wallebc2c052019-01-16 19:16:55 -08004552 }
Ady Abraham22c7b5c2020-09-22 19:33:40 -07004553
Jiakai Zhanga5505cb2021-11-09 11:46:30 +00004554 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
Marissa Walle2ffb422018-10-12 11:33:52 -07004555 // Do not put anything that updates layer state or modifies flags after
4556 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004557 return flags;
4558}
4559
chaviw273171b2018-12-26 11:46:30 -08004560uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
Arthur Hung58144272021-01-16 03:43:53 +00004561 bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
Vishnu Naire798b472020-07-23 13:52:21 -07004562 return hasChanges ? eTraversalNeeded : 0;
chaviw273171b2018-12-26 11:46:30 -08004563}
4564
Vishnu Nair84125ac2021-12-02 08:47:48 -08004565status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
4566 const sp<IBinder>& mirrorFromHandle, sp<IBinder>* outHandle,
4567 int32_t* outLayerId) {
chaviwfe94a222019-08-21 13:52:59 -07004568 if (!mirrorFromHandle) {
4569 return NAME_NOT_FOUND;
4570 }
4571
4572 sp<Layer> mirrorLayer;
4573 sp<Layer> mirrorFrom;
chaviwfe94a222019-08-21 13:52:59 -07004574 {
4575 Mutex::Autolock _l(mStateLock);
Vishnu Nairf9096652021-07-20 18:49:42 -07004576 mirrorFrom = fromHandle(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07004577 if (!mirrorFrom) {
4578 return NAME_NOT_FOUND;
4579 }
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004580 status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07004581 if (result != NO_ERROR) {
4582 return result;
4583 }
4584
Robert Carr6a0382d2021-07-01 15:57:17 -07004585 mirrorLayer->setClonedChild(mirrorFrom->createClone());
chaviwfe94a222019-08-21 13:52:59 -07004586 }
4587
Ady Abraham9f0a4002020-10-05 15:47:26 -07004588 *outLayerId = mirrorLayer->sequence;
Dominik Laskowski46471e62022-01-14 15:34:03 -08004589 if (mTransactionTracing) {
4590 mTransactionTracing->onMirrorLayerAdded((*outHandle)->localBinder(), mirrorLayer->sequence,
4591 args.name, mirrorFrom->sequence);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004592 }
4593 return addClientLayer(args.client, *outHandle, mirrorLayer /* layer */, nullptr /* parent */,
Vishnu Nair858a3b42022-01-12 20:42:28 -08004594 false /* addToRoot */, nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07004595}
4596
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004597status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
Ady Abraham9f0a4002020-10-05 15:47:26 -07004598 const sp<IBinder>& parentHandle, int32_t* outLayerId,
4599 const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
Robert Carrc0df3122019-04-11 13:18:21 -07004600 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4601 "Expected only one of parentLayer or parentHandle to be non-null. "
4602 "Programmer error?");
4603
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004604 status_t result = NO_ERROR;
4605
4606 sp<Layer> layer;
4607
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004608 switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004609 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004610 case ISurfaceComposerClient::eFXSurfaceBufferState: {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004611 result = createBufferStateLayer(args, outHandle, &layer);
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004612 std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
4613 if (pendingBufferCounter) {
4614 std::string counterName = layer->getPendingBufferCounterName();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004615 mBufferCountTracker.add((*outHandle)->localBinder(), counterName,
Vishnu Nair8eda69e2021-02-26 10:42:10 -08004616 pendingBufferCounter);
4617 }
4618 } break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08004619 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004620 result = createEffectLayer(args, outHandle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004621 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004622 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004623 result = createContainerLayer(args, outHandle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004624 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004625 default:
4626 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004627 break;
4628 }
4629
Dan Stoza7d89d062015-04-30 13:29:25 -07004630 if (result != NO_ERROR) {
4631 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004632 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004633
Vishnu Nair858a3b42022-01-12 20:42:28 -08004634 bool addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
Garfield Tandbc93d72021-10-26 18:28:57 -07004635 wp<Layer> parent(parentHandle != nullptr ? fromHandle(parentHandle) : parentLayer);
4636 if (parentHandle != nullptr && parent == nullptr) {
4637 ALOGE("Invalid parent handle %p.", parentHandle.get());
4638 addToRoot = false;
4639 }
4640 if (parentLayer != nullptr) {
4641 addToRoot = false;
4642 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004643
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004644 int parentId = -1;
4645 // We can safely promote the layer in binder thread because we have a strong reference
4646 // to the layer's handle inside this scope or we were passed in a sp reference to the layer.
4647 sp<Layer> parentSp = parent.promote();
4648 if (parentSp != nullptr) {
4649 parentId = parentSp->getSequence();
4650 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08004651 if (mTransactionTracing) {
4652 mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), layer->sequence, args.name,
4653 args.flags, parentId);
Vishnu Nair84125ac2021-12-02 08:47:48 -08004654 }
Vishnu Nair0cc69e12021-11-18 09:05:49 -08004655
Vishnu Nair047fb332021-12-09 09:54:36 -08004656 result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
4657 if (result != NO_ERROR) {
4658 return result;
4659 }
4660
Ady Abraham9f0a4002020-10-05 15:47:26 -07004661 *outLayerId = layer->sequence;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004662 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004663}
4664
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004665status_t SurfaceFlinger::createBufferQueueLayer(LayerCreationArgs& args, PixelFormat& format,
Evan Roskya1f1e152019-01-24 16:17:46 -08004666 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004667 sp<IGraphicBufferProducer>* gbp,
4668 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004669 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004670 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004671 case PIXEL_FORMAT_TRANSPARENT:
4672 case PIXEL_FORMAT_TRANSLUCENT:
4673 format = PIXEL_FORMAT_RGBA_8888;
4674 break;
4675 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004676 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004677 break;
4678 }
4679
chaviwb4c6e582019-08-16 14:35:07 -07004680 sp<BufferQueueLayer> layer;
chaviwb4c6e582019-08-16 14:35:07 -07004681 args.textureName = getNewTexture();
4682 {
4683 // Grab the SF state lock during this since it's the only safe way to access
4684 // RenderEngine when creating a BufferLayerConsumer
4685 // TODO: Check if this lock is still needed here
4686 Mutex::Autolock lock(mStateLock);
4687 layer = getFactory().createBufferQueueLayer(args);
4688 }
4689
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004690 status_t err = layer->setDefaultBufferProperties(0, 0, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004691 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004692 *handle = layer->getHandle();
4693 *gbp = layer->getProducer();
4694 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004695 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004696
Marissa Wallfd668622018-05-10 10:21:13 -07004697 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004698 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004699}
4700
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004701status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004702 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07004703 args.textureName = getNewTexture();
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004704 *outLayer = getFactory().createBufferStateLayer(args);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004705 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004706 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004707}
4708
Vishnu Nair84125ac2021-12-02 08:47:48 -08004709status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004710 sp<Layer>* outLayer) {
4711 *outLayer = getFactory().createEffectLayer(args);
4712 *handle = (*outLayer)->getHandle();
4713 return NO_ERROR;
4714}
4715
Vishnu Nair84125ac2021-12-02 08:47:48 -08004716status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
Evan Roskya1f1e152019-01-24 16:17:46 -08004717 sp<Layer>* outLayer) {
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08004718 *outLayer = getFactory().createContainerLayer(args);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004719 *handle = (*outLayer)->getHandle();
4720 return NO_ERROR;
4721}
4722
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004723void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004724 mLayersPendingRemoval.add(layer);
4725 mLayersRemoved = true;
4726 setTransactionFlags(eTransactionNeeded);
4727}
4728
Vishnu Nairf9096652021-07-20 18:49:42 -07004729void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004730 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004731 // If a layer has a parent, we allow it to out-live it's handle
4732 // with the idea that the parent holds a reference and will eventually
4733 // be cleaned up. However no one cleans up the top-level so we do so
4734 // here.
Vishnu Nair14d218b2021-07-13 13:57:39 -07004735 if (layer->isAtRoot()) {
4736 layer->setIsAtRoot(false);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004737 mCurrentState.layersSortedByZ.remove(layer);
4738 }
4739 markLayerPendingRemovalLocked(layer);
Vishnu Nairf9096652021-07-20 18:49:42 -07004740 mBufferCountTracker.remove(handle);
Robert Carr695d5282018-12-18 15:27:58 -08004741 layer.clear();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004742 if (mTransactionTracing) {
4743 mTransactionTracing->onHandleRemoved(handle);
Vishnu Nair047fb332021-12-09 09:54:36 -08004744 }
Rob Carr4bba3702018-10-08 21:53:30 +00004745}
4746
Mathias Agopianb60314a2012-04-10 22:09:54 -07004747// ---------------------------------------------------------------------------
4748
Andy McFadden13a082e2012-08-24 10:16:42 -07004749void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004750 const auto display = getDefaultDisplayDeviceLocked();
4751 if (!display) return;
4752
4753 const sp<IBinder> token = display->getDisplayToken().promote();
4754 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004755
Jesse Hall01e29052013-02-19 16:13:35 -08004756 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004757 Vector<ComposerState> state;
4758 Vector<DisplayState> displays;
4759 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004760 d.what = DisplayState::eDisplayProjectionChanged |
4761 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004762 d.token = token;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07004763 d.layerStack = ui::DEFAULT_LAYER_STACK;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004764 d.orientation = ui::ROTATION_0;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02004765 d.orientedDisplaySpaceRect.makeInvalid();
4766 d.layerStackSpaceRect.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004767 d.width = 0;
4768 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004769 displays.add(d);
Arthur Hung58144272021-01-16 03:43:53 +00004770
Vishnu Nair9a69a042021-06-18 13:19:49 -07004771 nsecs_t now = systemTime();
Vishnu Nair7891e962021-11-11 12:07:21 -08004772
4773 int64_t transactionId = (((int64_t)mPid) << 32) | mUniqueTransactionId++;
Arthur Hung58144272021-01-16 03:43:53 +00004774 // It should be on the main thread, apply it directly.
4775 applyTransactionState(FrameTimelineInfo{}, state, displays, 0, mInputWindowCommands,
Vishnu Nair9a69a042021-06-18 13:19:49 -07004776 /* desiredPresentTime */ now, true, {}, /* postTime */ now, true, false,
Vishnu Nair7891e962021-11-11 12:07:21 -08004777 {}, mPid, getuid(), transactionId);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004778
Peiyong Lin65248e02020-04-18 21:15:07 -07004779 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004780 const nsecs_t vsyncPeriod = display->refreshRateConfigs().getActiveMode()->getVsyncPeriod();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004781 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Ady Abraham1273ac12021-08-26 17:31:53 -07004782 mActiveDisplayTransformHint = display->getTransformHint();
Brian Andersond0010582017-03-07 13:20:31 -08004783 // Use phase of 0 since phase is not known.
4784 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004785 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004786 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004787}
4788
4789void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004790 // Async since we may be called from the main thread.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004791 static_cast<void>(
4792 mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004793}
4794
Peiyong Lin65248e02020-04-18 21:15:07 -07004795void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004796 if (display->isVirtual()) {
Dominik Laskowski6c7b36e2022-03-03 08:27:58 -08004797 ALOGE("%s: Invalid operation on virtual display", __func__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004798 return;
4799 }
4800
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004801 const auto displayId = display->getPhysicalId();
4802 ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004803
Peiyong Lin65248e02020-04-18 21:15:07 -07004804 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004805 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004806 return;
4807 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004808
Ady Abraham4f960d12021-10-13 16:59:49 -07004809 const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
4810 if (activeDisplay != display && display->isInternal() && activeDisplay &&
4811 activeDisplay->isPoweredOn()) {
4812 ALOGW("Trying to change power mode on non active display while the active display is ON");
4813 }
4814
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004815 display->setPowerMode(mode);
4816
Lloyd Pique4dccc412018-01-22 17:21:36 -08004817 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004818 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004819 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004820 const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Peiyong Lin65248e02020-04-18 21:15:07 -07004821 if (currentMode == hal::PowerMode::OFF) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004822 // Turn on the display
Ady Abrahamed3290f2021-05-17 15:12:14 -07004823 if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
Ady Abrahamdb036a82021-07-16 14:18:34 -07004824 onActiveDisplayChangedLocked(display);
Ady Abrahamed3290f2021-05-17 15:12:14 -07004825 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004826 // Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
4827 // We can merge the syscall later.
4828 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
4829 ALOGW("Couldn't set uclamp.min on display on: %s\n", strerror(errno));
4830 }
Martin Liu4a322352020-03-24 21:30:38 +08004831 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4832 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4833 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004834 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004835 if (isDisplayActiveLocked(display) && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham4f960d12021-10-13 16:59:49 -07004836 setHWCVsyncEnabled(displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004837 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004838 mScheduler->resyncToHardwareVsync(true, refreshRate);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004839 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004840
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004841 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004842 mHasPoweredOff = true;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07004843 scheduleComposite(FrameHint::kActive);
Peiyong Lin65248e02020-04-18 21:15:07 -07004844 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004845 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004846 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4847 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004848 }
Wei Wang23aa5a62021-06-04 15:56:57 -07004849 if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
4850 ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
4851 }
Ady Abrahamadc914c2021-10-13 17:04:27 -07004852 if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004853 mScheduler->disableHardwareVsync(true);
4854 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004855 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004856
Ady Abraham27c70212019-06-11 10:52:26 -07004857 // Make sure HWVsync is disabled before turning off the display
Ady Abraham4f960d12021-10-13 16:59:49 -07004858 setHWCVsyncEnabled(displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004859
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004860 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004861 mVisibleRegionsDirty = true;
4862 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004863 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004864 // Update display while dozing
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004865 getHwComposer().setPowerMode(displayId, mode);
Ady Abrahamadc914c2021-10-13 17:04:27 -07004866 if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004867 mScheduler->onScreenAcquired(mAppConnectionHandle);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08004868 mScheduler->resyncToHardwareVsync(true, refreshRate);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004869 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004870 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004871 // Leave display going to doze
Ady Abrahamadc914c2021-10-13 17:04:27 -07004872 if (isDisplayActiveLocked(display)) {
Ana Krulecc2870422019-01-29 19:00:58 -08004873 mScheduler->disableHardwareVsync(true);
4874 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004875 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004876 getHwComposer().setPowerMode(displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004877 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004878 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004879 getHwComposer().setPowerMode(displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004880 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004881
Ady Abrahamadc914c2021-10-13 17:04:27 -07004882 if (isDisplayActiveLocked(display)) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004883 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004884 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004885 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004886 }
4887
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02004888 ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004889}
4890
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004891void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004892 auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004893 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004894 if (!display) {
4895 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4896 displayToken.get());
4897 } else if (display->isVirtual()) {
4898 ALOGW("Attempt to set power mode %d for virtual display", mode);
4899 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004900 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004901 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07004902 });
4903
4904 future.wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004905}
4906
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004907status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004908 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004909
Mathias Agopianbd115332013-04-18 16:41:04 -07004910 IPCThreadState* ipc = IPCThreadState::self();
4911 const int pid = ipc->getCallingPid();
4912 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004913
Mathias Agopianbd115332013-04-18 16:41:04 -07004914 if ((uid != AID_SHELL) &&
4915 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004916 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4917 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004918 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004919 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004920 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham8cb21882020-08-26 18:22:05 -07004921 {"--dispsync"s, dumper([this](std::string& s) { mScheduler->dumpVsync(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004922 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004923 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4924 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4925 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4926 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
Dan Stoza269dc4d2021-01-15 15:07:43 -08004927 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004928 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4929 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004930 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004931 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07004932 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004933 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004934
Dominik Laskowskic2867142019-01-21 11:33:38 -08004935 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004936
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004937 bool dumpLayers = true;
4938 {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08004939 TimedLock lock(mStateLock, s2ns(1), __func__);
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004940 if (!lock.locked()) {
4941 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4942 strerror(-lock.status), lock.status);
4943 }
4944
4945 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4946 (it->second)(args, asProto, result);
4947 dumpLayers = false;
4948 } else if (!asProto) {
4949 dumpAllLocked(args, result);
4950 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004951 }
4952
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004953 if (dumpLayers) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004954 LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
chaviw0a398992021-08-13 10:13:01 -05004955 LayersTraceProto* layersTrace = traceFileProto.add_entry();
4956 LayersProto layersProto = dumpProtoFromMainThread();
4957 layersTrace->mutable_layers()->Swap(&layersProto);
4958 dumpDisplayProto(*layersTrace);
4959
Dominik Laskowski46470112019-08-02 13:13:11 -07004960 if (asProto) {
chaviw0a398992021-08-13 10:13:01 -05004961 result.append(traceFileProto.SerializeAsString());
Dominik Laskowski46470112019-08-02 13:13:11 -07004962 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004963 // Dump info that we need to access from the main thread
chaviwa2b9fab2021-09-08 14:46:30 -05004964 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
Dominik Laskowski46470112019-08-02 13:13:11 -07004965 result.append(LayerProtoParser::layerTreeToString(layerTree));
4966 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004967 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004968 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004969 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004971 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004972 return NO_ERROR;
4973}
4974
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004975status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
Vishnu Nair7891e962021-11-11 12:07:21 -08004976 if (asProto) {
Vishnu Nair00b90132021-11-05 14:03:40 -07004977 mLayerTracing.writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08004978 if (mTransactionTracing) {
4979 mTransactionTracing->writeToFile();
4980 }
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004981 }
4982
4983 return doDump(fd, DumpArgs(), asProto);
4984}
4985
Dominik Laskowskic2867142019-01-21 11:33:38 -08004986void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004987 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004988 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004989}
4990
Dominik Laskowskic2867142019-01-21 11:33:38 -08004991void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Ady Abraham2492a022020-07-24 11:09:55 -07004992 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004993
Dominik Laskowskic2867142019-01-21 11:33:38 -08004994 if (args.size() > 1) {
4995 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004996 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004997 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004998 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004999 }
Robert Carr2047fae2016-11-28 14:09:09 -08005000 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08005001 } else {
5002 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005003 }
5004}
5005
Dominik Laskowskic2867142019-01-21 11:33:38 -08005006void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005007 const bool clearAll = args.size() < 2;
5008 const auto name = clearAll ? String8() : String8(args[1]);
5009
Edgar Arriaga844fa672020-01-16 14:21:42 -08005010 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005011 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07005012 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005013 }
Robert Carr2047fae2016-11-28 14:09:09 -08005014 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08005015
Svetoslavd85084b2014-03-20 10:28:31 -07005016 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08005017}
5018
Dominik Laskowskic2867142019-01-21 11:33:38 -08005019void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5020 mTimeStats->parseArgs(asProto, args, result);
5021}
5022
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07005023void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5024 mFrameTimeline->parseArgs(args, result);
5025}
5026
Jamie Gennis6547ff42013-07-16 20:12:42 -07005027void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08005028 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07005029 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08005030 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07005031
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005032 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07005033}
5034
Yiwei Zhang5434a782018-12-05 18:06:32 -08005035void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005036 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07005037
Yiwei Zhang5434a782018-12-05 18:06:32 -08005038 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5039 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005040 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5041 getHwComposer().getMaxVirtualDisplayDimension());
Yiwei Zhang5434a782018-12-05 18:06:32 -08005042 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5043 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5044 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08005045 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07005046}
5047
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005048void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07005049 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005050
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005051 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005052 result.append("\n");
5053
Ady Abraham8287e852020-08-12 14:44:58 -07005054 mVsyncConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005055 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07005056 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ady Abraham2492a022020-07-24 11:09:55 -07005057 dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005058
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005059 StringAppendF(&result, "(mode override by backdoor: %s)\n\n",
5060 mDebugDisplayModeSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07005061
Ana Krulecc2870422019-01-29 19:00:58 -08005062 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham8cb21882020-08-26 18:22:05 -07005063 mScheduler->dumpVsync(result);
Ady Abraham4f960d12021-10-13 16:59:49 -07005064 StringAppendF(&result, "mHWCVsyncPendingState=%s mLastHWCVsyncState=%s\n",
5065 to_string(mHWCVsyncPendingState).c_str(), to_string(mLastHWCVsyncState).c_str());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005066}
5067
Dan Stoza269dc4d2021-01-15 15:07:43 -08005068void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5069 for (const auto& [token, display] : mDisplays) {
5070 const auto compositionDisplay = display->getCompositionDisplay();
5071 compositionDisplay->dumpPlannerInfo(args, result);
5072 }
5073}
5074
Yiwei Zhang5434a782018-12-05 18:06:32 -08005075void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
5076 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08005077 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
5078 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005079 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005080 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005081 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005082 }
David Sodman4a36e932017-11-07 14:29:47 -08005083 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08005084 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08005085 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005086 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
5087 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08005088}
5089
Yiwei Zhang5434a782018-12-05 18:06:32 -08005090void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
5091 result.append("Layer frame timestamps:\n");
Josh Chienedaa9132020-12-04 18:30:46 +08005092 // Traverse all layers to dump frame-events for each layer
5093 mCurrentState.traverseInZOrder(
5094 [&] (Layer* layer) { layer->dumpFrameEvents(result); });
Brian Andersond6927fb2016-07-23 23:37:30 -07005095}
5096
Yiwei Zhang5434a782018-12-05 18:06:32 -08005097void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005098 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005099 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005100 if (!displayId) {
5101 continue;
5102 }
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005103 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07005104 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005105 continue;
5106 }
5107
Yiwei Zhang5434a782018-12-05 18:06:32 -08005108 StringAppendF(&result,
5109 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5110 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005111 uint8_t port;
5112 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07005113 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005114 result.append("no identification data\n");
5115 continue;
5116 }
5117
5118 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005119 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005120 continue;
5121 }
5122
5123 const auto edid = parseEdid(data);
5124 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005125 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005126 continue;
5127 }
5128
Yiwei Zhang5434a782018-12-05 18:06:32 -08005129 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005130 result.append(edid->displayName.data(), edid->displayName.length());
5131 result.append("\"\n");
5132 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005133}
5134
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005135void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5136 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07005137 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07005138 uint8_t port;
5139 DisplayIdentificationData data;
5140
5141 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5142 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5143 result.append(reinterpret_cast<const char*>(data.data()), data.size());
5144 }
5145}
5146
Yiwei Zhang5434a782018-12-05 18:06:32 -08005147void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07005148 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005149 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5150 StringAppendF(&result, "DisplayColorSetting: %s\n",
5151 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005152
5153 // TODO: print out if wide-color mode is active or not
5154
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005155 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005156 const auto displayId = PhysicalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005157 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005158 continue;
5159 }
5160
Yiwei Zhang5434a782018-12-05 18:06:32 -08005161 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005162 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005163 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08005164 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005165 }
5166
Lloyd Pique32cbe282018-10-19 13:09:22 -07005167 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005168 StringAppendF(&result, " Current color mode: %s (%d)\n",
5169 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005170 }
5171 result.append("\n");
5172}
5173
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005174LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07005175 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08005176 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005177 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08005178 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08005179
chaviw1d044282017-09-27 12:19:28 -07005180 return layersProto;
5181}
5182
chaviw0a398992021-08-13 10:13:01 -05005183void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005184 for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
chaviw0a398992021-08-13 10:13:01 -05005185 DisplayProto* displayProto = layersTraceProto.add_displays();
5186 displayProto->set_id(display->getId().value);
5187 displayProto->set_name(display->getDisplayName());
5188 displayProto->set_layer_stack(display->getLayerStack().id);
5189 LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5190 [&]() { return displayProto->mutable_size(); });
5191 LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5192 return displayProto->mutable_layer_stack_space_rect();
5193 });
5194 LayerProtoHelper::writeTransformToProto(display->getTransform(),
5195 displayProto->mutable_transform());
Vishnu Nair791d48a2021-12-02 16:55:13 -08005196 displayProto->set_is_virtual(display->isVirtual());
chaviw0a398992021-08-13 10:13:01 -05005197 }
5198}
5199
Alec Mouri6b9e9912020-01-21 10:50:24 -08005200void SurfaceFlinger::dumpHwc(std::string& result) const {
5201 getHwComposer().dump(result);
5202}
5203
Vishnu Nair0f085c62019-08-30 08:49:12 -07005204void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5205 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5206 // it.
5207 LayerProto* rootProto = layersProto.add_layers();
5208 const int32_t offscreenRootLayerId = INT32_MAX - 2;
5209 rootProto->set_id(offscreenRootLayerId);
5210 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07005211 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005212
5213 for (Layer* offscreenLayer : mOffscreenLayers) {
5214 // Add layer as child of the fake root
5215 rootProto->add_children(offscreenLayer->sequence);
5216
5217 // Add layer
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005218 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005219 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07005220 }
5221}
5222
Vishnu Nair8406fd72019-07-30 11:29:31 -07005223LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005224 return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07005225}
5226
Vishnu Nair0f085c62019-08-30 08:49:12 -07005227void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005228 auto future = mScheduler->schedule([this] {
5229 std::string result;
5230 for (Layer* offscreenLayer : mOffscreenLayers) {
5231 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5232 [&](Layer* layer) { layer->dumpCallingUidPid(result); });
5233 }
5234 return result;
5235 });
5236
Vishnu Nair0f085c62019-08-30 08:49:12 -07005237 result.append("Offscreen Layers:\n");
Dominik Laskowski756b7892021-08-04 12:53:59 -07005238 result.append(future.get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07005239}
5240
Dominik Laskowskic2867142019-01-21 11:33:38 -08005241void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
5242 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005243 Colorizer colorizer(colorize);
5244
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005245 // figure out if we're stuck somewhere
5246 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005247 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005248 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
5249
5250 /*
Andy McFadden4803b742012-09-24 19:07:20 -07005251 * Dump library configuration.
5252 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005253
5254 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005255 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005256 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005257 appendSfConfigString(result);
Andy McFadden4803b742012-09-24 19:07:20 -07005258 result.append("\n");
5259
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07005260 result.append("\nDisplay identification data:\n");
5261 dumpDisplayIdentificationData(result);
5262
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06005263 result.append("\nWide-Color information:\n");
5264 dumpWideColorInfo(result);
5265
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005266 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005267 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005268 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005269 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005270 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005271
Andy McFadden41d67d72014-04-25 16:58:34 -07005272 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07005273 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005274 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005275 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005276 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005277
Dan Stozab90cf072015-03-05 11:05:59 -08005278 dumpStaticScreenStats(result);
5279 result.append("\n");
5280
Alec Mouri40189b02019-03-05 15:07:54 -08005281 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5282 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5283 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005284
Andy McFadden4803b742012-09-24 19:07:20 -07005285 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005286 * Dump the visible layer list
5287 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005288 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07005289 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005290 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005291
Chia-I Wu2f884132018-09-13 15:17:58 -07005292 {
Lloyd Pique207def92019-02-28 16:09:52 -08005293 StringAppendF(&result, "Composition layers\n");
5294 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08005295 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08005296 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08005297
5298 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
5299 layer->getDebugName() ? layer->getDebugName()
5300 : "<unknown>");
5301 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08005302 });
5303 }
5304
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005305 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005306 * Dump Display state
5307 */
5308
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005309 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005310 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005311 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005312 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005313 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005314 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005315 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005316
5317 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07005318 * Dump CompositionEngine state
5319 */
5320
5321 mCompositionEngine->dump(result);
5322
5323 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005324 * Dump SurfaceFlinger global state
5325 */
5326
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005327 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005328 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005329 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005330
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005331 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005332
Robert Carrbeba6f02021-02-10 21:06:27 -08005333 result.append("ClientCache state:\n");
5334 ClientCache::getInstance().dump(result);
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005335 DebugEGLImageTracker::getInstance()->dump(result);
5336
Dominik Laskowski075d3172018-05-24 15:50:06 -07005337 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005338 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5339 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08005340 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
5341 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005342 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005343 StringAppendF(&result,
5344 " transaction-flags : %08x\n"
5345 " gpu_to_cpu_unsupported : %d\n",
5346 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005347
Marin Shalamanov045b7002021-01-07 16:56:24 +01005348 if (const auto display = getDefaultDisplayDeviceLocked()) {
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005349 std::string fps, xDpi, yDpi;
Marin Shalamanov045b7002021-01-07 16:56:24 +01005350 if (const auto activeMode = display->getActiveMode()) {
5351 fps = to_string(activeMode->getFps());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08005352
5353 const auto dpi = activeMode->getDpi();
5354 xDpi = base::StringPrintf("%.2f", dpi.x);
5355 yDpi = base::StringPrintf("%.2f", dpi.y);
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005356 } else {
5357 fps = "unknown";
5358 xDpi = "unknown";
5359 yDpi = "unknown";
5360 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005361 StringAppendF(&result,
Marin Shalamanov9afcbd82020-08-19 12:34:59 +02005362 " refresh-rate : %s\n"
5363 " x-dpi : %s\n"
5364 " y-dpi : %s\n",
5365 fps.c_str(), xDpi.c_str(), yDpi.c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005366 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005367
Yiwei Zhang5434a782018-12-05 18:06:32 -08005368 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005369
Dan Stozae22aec72016-08-01 13:20:59 -07005370 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005371 * Tracing state
5372 */
Vishnu Nair00b90132021-11-05 14:03:40 -07005373 mLayerTracing.dump(result);
Dominik Laskowski46471e62022-01-14 15:34:03 -08005374
5375 result.append("\nTransaction tracing: ");
5376 if (mTransactionTracing) {
5377 result.append("enabled\n");
5378 mTransactionTracing->dump(result);
5379 } else {
5380 result.append("disabled\n");
5381 }
5382 result.push_back('\n');
Yichi Chenadc69612018-09-15 14:51:18 +08005383
5384 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005385 * HWC layer minidump
5386 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005387 for (const auto& [token, display] : mDisplays) {
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02005388 const auto displayId = HalDisplayId::tryCast(display->getId());
Dominik Laskowski075d3172018-05-24 15:50:06 -07005389 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005390 continue;
5391 }
5392
Siddharth Kapoorecc45ae2021-09-06 19:03:06 +08005393 StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
5394 (isDisplayActiveLocked(display) ? "active" : "inactive"));
Dan Stozae22aec72016-08-01 13:20:59 -07005395 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005396
5397 const DisplayDevice& ref = *display;
5398 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07005399 result.append("\n");
5400 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005401
Ady Abraham2790e9f2021-04-28 13:14:20 -07005402 {
5403 DumpArgs plannerArgs;
5404 plannerArgs.add(); // first argument is ignored
5405 plannerArgs.add(String16("--layers"));
5406 dumpPlannerInfo(plannerArgs, result);
5407 }
5408
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005409 /*
5410 * Dump HWComposer state
5411 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005412 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005413 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005414 colorizer.reset(result);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005415 const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005416 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Ady Abrahamc4acf512022-02-18 17:11:59 -08005417 dumpHwc(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005418
5419 /*
5420 * Dump gralloc state
5421 */
5422 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5423 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005424
rnleea2ecd832021-07-29 13:58:30 -07005425 /*
5426 * Dump flag/property manager state
5427 */
Robert Carr9b623c32022-03-21 15:55:22 -07005428 mFlagManager.dump(result);
rnleea2ecd832021-07-29 13:58:30 -07005429
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005430 result.append(mTimeStats->miniDump());
5431 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005432}
5433
chaviw17ac24b2021-01-28 18:50:05 -08005434mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
5435 if (saturation == 1) {
5436 return mat4();
Chia-I Wu28f320b2018-05-03 11:02:56 -07005437 }
5438
chaviw17ac24b2021-01-28 18:50:05 -08005439 float3 luminance{0.213f, 0.715f, 0.072f};
5440 luminance *= 1.0f - saturation;
5441 mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
5442 vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
5443 vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
5444 vec4{0.0f, 0.0f, 0.0f, 1.0f});
5445 return saturationMatrix;
5446}
5447
5448void SurfaceFlinger::updateColorMatrixLocked() {
5449 mat4 colorMatrix =
5450 mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
5451
Chia-I Wu28f320b2018-05-03 11:02:56 -07005452 if (mCurrentState.colorMatrix != colorMatrix) {
5453 mCurrentState.colorMatrix = colorMatrix;
5454 mCurrentState.colorMatrixChanged = true;
5455 setTransactionFlags(eTransactionNeeded);
5456 }
5457}
5458
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005459status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005460#pragma clang diagnostic push
5461#pragma clang diagnostic error "-Wswitch-enum"
5462 switch (static_cast<ISurfaceComposerTag>(code)) {
5463 // These methods should at minimum make sure that the client requested
5464 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005465 case BOOT_FINISHED:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005466 case GET_HDR_CAPABILITIES:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005467 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
Galia Peycheva5492cb52019-10-30 14:13:16 +01005468 case GET_GAME_CONTENT_TYPE_SUPPORT:
Ady Abraham8532d012019-05-08 14:50:56 -07005469 case GET_DISPLAYED_CONTENT_SAMPLE:
Steven Thomasd4071902020-03-24 16:02:53 -07005470 case SET_GLOBAL_SHADOW_SETTINGS:
5471 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005472 // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
5473 // permission dynamically. Don't use the permission cache for this check.
5474 bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
Steven Thomasd4071902020-03-24 16:02:53 -07005475 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005476 IPCThreadState* ipc = IPCThreadState::self();
5477 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5478 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005479 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005480 }
Robert Carr1db73f62016-12-21 12:58:51 -08005481 return OK;
5482 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005483 // Used by apps to hook Choreographer to SurfaceFlinger.
5484 case CREATE_DISPLAY_EVENT_CONNECTION:
5485 // The following calls are currently used by clients that do not
5486 // request necessary permissions. However, they do not expose any secret
5487 // information, so it is OK to pass them.
5488 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005489 case GET_ACTIVE_COLOR_MODE:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005490 case GET_ACTIVE_DISPLAY_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005491 case GET_DISPLAY_COLOR_MODES:
Marin Shalamanova7fe3042021-01-29 21:02:08 +01005492 case GET_DISPLAY_MODES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005493 // Calling setTransactionState is safe, because you need to have been
5494 // granted a reference to Client* and Handle* to do anything with it.
5495 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005496 case CREATE_CONNECTION:
Steven Thomas62a4cf82020-01-31 12:04:03 -08005497 // setFrameRate() is deliberately available for apps to call without any
5498 // special permissions.
5499 case SET_FRAME_RATE:
Leon Scroggins IIIe5cff632021-12-29 11:53:36 -05005500 case GET_DISPLAY_DECORATION_SUPPORT:
Huihong Luo02186fb2022-02-23 14:21:54 -08005501 case SET_FRAME_TIMELINE_INFO: {
Ady Abraham564f9de2021-02-03 18:34:33 -08005502 // This is not sensitive information, so should not require permission control.
Ana Krulec13be8ad2018-08-21 02:43:56 +00005503 return OK;
5504 }
Andy Yu8c38b252022-01-15 01:13:19 -08005505 case SET_OVERRIDE_FRAME_RATE: {
5506 const int uid = IPCThreadState::self()->getCallingUid();
5507 if (uid == AID_ROOT || uid == AID_SYSTEM) {
5508 return OK;
5509 }
5510 return PERMISSION_DENIED;
5511 }
Huihong Luo07e72362022-02-14 14:26:04 -08005512 case CREATE_DISPLAY:
5513 case DESTROY_DISPLAY:
5514 case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
5515 case GET_PHYSICAL_DISPLAY_IDS:
5516 case GET_PHYSICAL_DISPLAY_TOKEN:
Huihong Luo37396db2022-02-15 10:43:00 -08005517 case SET_POWER_MODE:
Huihong Luo0a81aa32022-02-22 16:02:36 -08005518 case GET_SUPPORTED_FRAME_TIMESTAMPS:
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08005519 case GET_DISPLAY_STATE:
5520 case GET_DISPLAY_STATS:
Huihong Luoa79ddf42022-02-17 00:01:38 -08005521 case GET_STATIC_DISPLAY_INFO:
Huihong Luo38603fd2022-02-21 14:32:54 -08005522 case GET_DYNAMIC_DISPLAY_INFO:
Huihong Luoca3d9a42022-02-22 11:07:34 -08005523 case GET_DISPLAY_NATIVE_PRIMARIES:
5524 case SET_ACTIVE_COLOR_MODE:
5525 case SET_BOOT_DISPLAY_MODE:
Huihong Luo37396db2022-02-15 10:43:00 -08005526 case CLEAR_BOOT_DISPLAY_MODE:
5527 case GET_BOOT_DISPLAY_MODE_SUPPORT:
5528 case SET_AUTO_LOW_LATENCY_MODE:
5529 case SET_GAME_CONTENT_TYPE:
Huihong Luof5029222021-12-16 14:33:46 -08005530 case CAPTURE_LAYERS:
5531 case CAPTURE_DISPLAY:
5532 case CAPTURE_DISPLAY_BY_ID:
Huihong Luo4ed1c912022-02-22 14:30:01 -08005533 case CLEAR_ANIMATION_FRAME_STATS:
5534 case GET_ANIMATION_FRAME_STATS:
Huihong Luo05539a12022-02-23 10:29:40 -08005535 case OVERRIDE_HDR_TYPES:
5536 case ON_PULL_ATOM:
5537 case ENABLE_VSYNC_INJECTIONS:
5538 case INJECT_VSYNC:
5539 case GET_LAYER_DEBUG_INFO:
5540 case GET_COLOR_MANAGEMENT:
5541 case GET_COMPOSITION_PREFERENCE:
5542 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5543 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5544 case GET_PROTECTED_CONTENT_SUPPORT:
Huihong Luo37396db2022-02-15 10:43:00 -08005545 case IS_WIDE_COLOR_DISPLAY:
Huihong Luo02186fb2022-02-23 14:21:54 -08005546 case ADD_REGION_SAMPLING_LISTENER:
5547 case REMOVE_REGION_SAMPLING_LISTENER:
5548 case ADD_FPS_LISTENER:
5549 case REMOVE_FPS_LISTENER:
5550 case ADD_TUNNEL_MODE_ENABLED_LISTENER:
5551 case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
5552 case ADD_WINDOW_INFOS_LISTENER:
5553 case REMOVE_WINDOW_INFOS_LISTENER:
5554 case SET_DESIRED_DISPLAY_MODE_SPECS:
5555 case GET_DESIRED_DISPLAY_MODE_SPECS:
Huihong Luo37396db2022-02-15 10:43:00 -08005556 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5557 case SET_DISPLAY_BRIGHTNESS:
5558 case ADD_HDR_LAYER_INFO_LISTENER:
5559 case REMOVE_HDR_LAYER_INFO_LISTENER:
5560 case NOTIFY_POWER_BOOST:
Huihong Luo02186fb2022-02-23 14:21:54 -08005561 case ADD_TRANSACTION_TRACE_LISTENER:
5562 case GET_GPU_CONTEXT_PRIORITY:
5563 case GET_MAX_ACQUIRED_BUFFER_COUNT:
Huihong Luo07e72362022-02-14 14:26:04 -08005564 LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
Huihong Luof5029222021-12-16 14:33:46 -08005565 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005566 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005567
5568 // These codes are used for the IBinder protocol to either interrogate the recipient
5569 // side of the transaction for its canonical interface descriptor or to dump its state.
5570 // We let them pass by default.
5571 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5572 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5573 code == IBinder::SYSPROPS_TRANSACTION) {
5574 return OK;
5575 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01005576 // Numbers from 1000 to 1042 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005577 // in onTransact verifies that the user is root, and has access to use SF.
Nataniel Borges533c2f82022-01-21 12:07:02 +01005578 if (code >= 1000 && code <= 1042) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005579 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5580 return OK;
5581 }
5582 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5583 return PERMISSION_DENIED;
5584#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005585}
5586
Ana Krulec13be8ad2018-08-21 02:43:56 +00005587status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5588 uint32_t flags) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005589 if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
5590 return error;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005591 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005592
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005593 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5594 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005595 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005596 IPCThreadState* ipc = IPCThreadState::self();
5597 const int uid = ipc->getCallingUid();
5598 if (CC_UNLIKELY(uid != AID_SYSTEM
5599 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005600 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005601 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005602 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005603 return PERMISSION_DENIED;
5604 }
5605 int n;
5606 switch (code) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005607 case 1000: // Unused.
5608 case 1001:
5609 return NAME_NOT_FOUND;
5610 case 1002: // Toggle flashing on surface damage.
5611 if (const int delay = data.readInt32(); delay > 0) {
5612 mDebugFlashDelay = delay;
5613 } else {
5614 mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
5615 }
5616 scheduleRepaint();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005617 return NO_ERROR;
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005618 case 1004: // Force composite ahead of next VSYNC.
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07005619 case 1006:
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07005620 scheduleComposite(FrameHint::kActive);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005621 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005622 case 1005: { // Force commit ahead of next VSYNC.
5623 Mutex::Autolock lock(mStateLock);
5624 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
5625 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005626 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005627 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005628 case 1007: // Unused.
5629 return NAME_NOT_FOUND;
5630 case 1008: // Toggle forced GPU composition.
5631 mDebugDisableHWC = data.readInt32() != 0;
5632 scheduleRepaint();
Mathias Agopian53331da2011-08-22 21:44:41 -07005633 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005634 case 1009: // Toggle use of transform hint.
5635 mDebugDisableTransformHint = data.readInt32() != 0;
5636 scheduleRepaint();
Mathias Agopiana4583642011-08-23 18:03:18 -07005637 return NO_ERROR;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005638 case 1010: // Interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005639 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005640 reply->writeInt32(0);
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005641 reply->writeInt32(mDebugFlashDelay);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005642 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005643 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005644 return NO_ERROR;
5645 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005646 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005647 if (!display) {
5648 return NAME_NOT_FOUND;
5649 }
5650
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005651 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005652 return NO_ERROR;
5653 }
5654 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005655 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005656 // daltonize
5657 n = data.readInt32();
5658 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005659 case 1:
5660 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5661 break;
5662 case 2:
5663 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5664 break;
5665 case 3:
5666 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5667 break;
5668 default:
5669 mDaltonizer.setType(ColorBlindnessType::None);
5670 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005671 }
5672 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005673 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005674 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005675 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005676 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005677
5678 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005679 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005680 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005681 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005682 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005683 // apply a color matrix
5684 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005685 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005686 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005687 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005688 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005689 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005690 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005691 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005692 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005693 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005694 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005695
5696 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5697 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005698 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005699 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5700 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5701 }
5702
Chia-I Wu28f320b2018-05-03 11:02:56 -07005703 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005704 return NO_ERROR;
5705 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005706 case 1016: { // Unused.
5707 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005708 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005709 case 1017: {
5710 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005711 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005712 return NO_ERROR;
5713 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005714 case 1018: { // Modify Choreographer's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005715 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005716 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005717 return NO_ERROR;
5718 }
Ady Abraham9c53ee72020-07-22 21:16:18 -07005719 case 1019: { // Modify SurfaceFlinger's duration
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005720 n = data.readInt32();
Ady Abraham9c53ee72020-07-22 21:16:18 -07005721 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005722 return NO_ERROR;
5723 }
Irvel468051e2016-06-13 16:44:44 -07005724 case 1020: { // Layer updates interceptor
5725 n = data.readInt32();
5726 if (n) {
5727 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005728 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005729 }
5730 else{
5731 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005732 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005733 }
5734 return NO_ERROR;
5735 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005736 case 1021: { // Disable HWC virtual displays
Dominik Laskowski3dce4f42021-03-08 20:48:28 -08005737 const bool enable = data.readInt32() != 0;
Dominik Laskowski756b7892021-08-04 12:53:59 -07005738 static_cast<void>(
5739 mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
Dan Stoza8cf150a2016-08-02 10:27:31 -07005740 return NO_ERROR;
5741 }
Romain Guy0147a172017-06-01 13:53:56 -07005742 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005743 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005744 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005745
Chia-I Wu28f320b2018-05-03 11:02:56 -07005746 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005747 return NO_ERROR;
5748 }
Romain Guy54f154a2017-10-24 21:40:32 +01005749 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005750 int32_t colorMode;
5751
Chia-I Wu0d711262018-05-21 15:19:35 -07005752 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005753 if (data.readInt32(&colorMode) == NO_ERROR) {
5754 mForceColorMode = static_cast<ColorMode>(colorMode);
5755 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07005756 scheduleRepaint();
Romain Guy54f154a2017-10-24 21:40:32 +01005757 return NO_ERROR;
5758 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005759 // Deprecate, use 1030 to check whether the device is color managed.
5760 case 1024: {
5761 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005762 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005763 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005764 n = data.readInt32();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005765 bool tracingEnabledChanged;
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005766 if (n == 1) {
5767 int64_t fixedStartingTime = data.readInt64();
Yichi Chenadc69612018-09-15 14:51:18 +08005768 ALOGD("LayerTracing enabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005769 tracingEnabledChanged = mLayerTracing.enable();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005770 if (tracingEnabledChanged) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005771 int64_t startingTime =
5772 (fixedStartingTime) ? fixedStartingTime : systemTime();
5773 mScheduler
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005774 ->schedule([&]() FTL_FAKE_GUARD(mStateLock) {
Vishnu Nairb64a3b42022-01-13 15:29:32 -08005775 mLayerTracing.notify("start", startingTime);
5776 })
Dominik Laskowski756b7892021-08-04 12:53:59 -07005777 .wait();
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005778 }
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08005779 } else if (n == 2) {
5780 std::string filename = std::string(data.readCString());
5781 ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
5782 tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
Adrian Roos1e1a1282017-11-01 19:05:31 +01005783 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005784 ALOGD("LayerTracing disabled");
Vishnu Nair00b90132021-11-05 14:03:40 -07005785 tracingEnabledChanged = mLayerTracing.disable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005786 }
Vishnu Nair31a8dbc2020-10-27 17:37:49 -07005787 mTracingEnabledChanged = tracingEnabledChanged;
5788 reply->writeInt32(NO_ERROR);
Adrian Roos1e1a1282017-11-01 19:05:31 +01005789 return NO_ERROR;
5790 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005791 case 1026: { // Get layer tracing status
Vishnu Nair00b90132021-11-05 14:03:40 -07005792 reply->writeBool(mLayerTracing.isEnabled());
Vishnu Nair87704c92018-01-08 15:32:57 -08005793 return NO_ERROR;
5794 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005795 // Is a DisplayColorSetting supported?
5796 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005797 const auto display = getDefaultDisplayDevice();
5798 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005799 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005800 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005801
5802 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5803 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005804 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005805 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005806 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005807 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005808 reply->writeBool(true);
5809 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005810 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005811 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005812 break;
5813 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005814 reply->writeBool(
5815 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005816 break;
5817 }
5818 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005819 }
Alec Mouri9c58bcd2020-09-09 18:57:07 -07005820 case 1028: { // Unused.
5821 return NAME_NOT_FOUND;
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005822 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005823 // Set buffer size for SF tracing (value in KB)
5824 case 1029: {
5825 n = data.readInt32();
5826 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5827 ALOGW("Invalid buffer size: %d KB", n);
5828 reply->writeInt32(BAD_VALUE);
5829 return BAD_VALUE;
5830 }
5831
5832 ALOGD("Updating trace buffer to %d KB", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005833 mLayerTracing.setBufferSize(n * 1024);
Nataniel Borges2b796da2019-02-15 13:32:18 -08005834 reply->writeInt32(NO_ERROR);
5835 return NO_ERROR;
5836 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005837 // Is device color managed?
5838 case 1030: {
5839 reply->writeBool(useColorManagement);
5840 return NO_ERROR;
5841 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005842 // Override default composition data space
5843 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5844 // && adb shell stop zygote && adb shell start zygote
5845 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5846 // adb shell stop zygote && adb shell start zygote
5847 case 1031: {
5848 Mutex::Autolock _l(mStateLock);
5849 n = data.readInt32();
5850 if (n) {
5851 n = data.readInt32();
5852 if (n) {
5853 Dataspace dataspace = static_cast<Dataspace>(n);
5854 if (!validateCompositionDataspace(dataspace)) {
5855 return BAD_VALUE;
5856 }
5857 mDefaultCompositionDataspace = dataspace;
5858 }
5859 n = data.readInt32();
5860 if (n) {
5861 Dataspace dataspace = static_cast<Dataspace>(n);
5862 if (!validateCompositionDataspace(dataspace)) {
5863 return BAD_VALUE;
5864 }
5865 mWideColorGamutCompositionDataspace = dataspace;
5866 }
5867 } else {
5868 // restore composition data space.
5869 mDefaultCompositionDataspace = defaultCompositionDataspace;
5870 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5871 }
5872 return NO_ERROR;
5873 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005874 // Set trace flags
5875 case 1033: {
5876 n = data.readUint32();
5877 ALOGD("Updating trace flags to 0x%x", n);
Vishnu Nair00b90132021-11-05 14:03:40 -07005878 mLayerTracing.setTraceFlags(n);
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005879 reply->writeInt32(NO_ERROR);
5880 return NO_ERROR;
5881 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005882 case 1034: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07005883 auto future = mScheduler->schedule([&] {
Ady Abraham1b11bc62021-06-03 19:51:19 -07005884 switch (n = data.readInt32()) {
5885 case 0:
5886 case 1:
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005887 FTL_FAKE_GUARD(mStateLock,
5888 enableRefreshRateOverlay(static_cast<bool>(n)));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005889 break;
5890 default: {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005891 reply->writeBool(
5892 FTL_FAKE_GUARD(mStateLock, isRefreshRateOverlayEnabled()));
Ady Abraham1b11bc62021-06-03 19:51:19 -07005893 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005894 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07005895 });
5896
5897 future.wait();
Ady Abraham03b02dd2019-03-21 15:40:11 -07005898 return NO_ERROR;
5899 }
Ady Abraham34392f72019-04-10 11:29:27 -07005900 case 1035: {
Marin Shalamanov5801c942020-12-17 17:00:13 +01005901 const int modeId = data.readInt32();
Marin Shalamanov5801c942020-12-17 17:00:13 +01005902
Dominik Laskowskif1833852021-03-23 15:06:50 -07005903 const auto display = [&]() -> sp<IBinder> {
5904 uint64_t value;
5905 if (data.readUint64(&value) != NO_ERROR) {
Ady Abrahamed3290f2021-05-17 15:12:14 -07005906 return getDefaultDisplayDevice()->getDisplayToken().promote();
Ady Abrahamfb853662021-04-09 11:46:40 -07005907 }
5908
Dominik Laskowskif1833852021-03-23 15:06:50 -07005909 if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
5910 return getPhysicalDisplayToken(*id);
5911 }
5912
5913 ALOGE("Invalid physical display ID");
5914 return nullptr;
Ady Abrahamfb853662021-04-09 11:46:40 -07005915 }();
5916
Shiyong Li2bcece92021-08-30 20:38:50 +00005917 mDebugDisplayModeSetByBackdoor = false;
Marin Shalamanov85b2bdf2021-11-03 14:31:21 +01005918 const status_t result = setActiveModeFromBackdoor(display, modeId);
Dominik Laskowskif1833852021-03-23 15:06:50 -07005919 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
5920 return result;
Ady Abraham34392f72019-04-10 11:29:27 -07005921 }
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005922 // Turn on/off frame rate flexibility mode. When turned on it overrides the display
5923 // manager frame rate policy a new policy which allows switching between all refresh
5924 // rates.
Ady Abraham07e54702020-04-16 15:05:37 -07005925 case 1036: {
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005926 if (data.readInt32() > 0) { // turn on
Dominik Laskowski756b7892021-08-04 12:53:59 -07005927 return mScheduler
5928 ->schedule([this] {
5929 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005930 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005931
Dominik Laskowski756b7892021-08-04 12:53:59 -07005932 // This is a little racy, but not in a way that hurts anything. As
5933 // we grab the defaultMode from the display manager policy, we could
5934 // be setting a new display manager policy, leaving us using a stale
5935 // defaultMode. The defaultMode doesn't matter for the override
5936 // policy though, since we set allowGroupSwitching to true, so it's
5937 // not a problem.
5938 scheduler::RefreshRateConfigs::Policy overridePolicy;
5939 overridePolicy.defaultMode = display->refreshRateConfigs()
5940 .getDisplayManagerPolicy()
5941 .defaultMode;
5942 overridePolicy.allowGroupSwitching = true;
5943 constexpr bool kOverridePolicy = true;
5944 return setDesiredDisplayModeSpecsInternal(display, overridePolicy,
5945 kOverridePolicy);
5946 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005947 .get();
5948 } else { // turn off
Dominik Laskowski756b7892021-08-04 12:53:59 -07005949 return mScheduler
5950 ->schedule([this] {
5951 const auto display =
Dominik Laskowski298b08e2022-02-15 13:45:02 -08005952 FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Dominik Laskowski756b7892021-08-04 12:53:59 -07005953 constexpr bool kOverridePolicy = true;
5954 return setDesiredDisplayModeSpecsInternal(display, {},
5955 kOverridePolicy);
5956 })
Marin Shalamanovfa39ee72021-11-01 14:04:27 +01005957 .get();
Ady Abraham07e54702020-04-16 15:05:37 -07005958 }
Ady Abraham07e54702020-04-16 15:05:37 -07005959 }
Marin Shalamanove6332b02020-09-03 11:30:37 +02005960 // Inject a hotplug connected event for the primary display. This will deallocate and
5961 // reallocate the display state including framebuffers.
5962 case 1037: {
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07005963 const hal::HWDisplayId hwcId =
5964 (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
5965
5966 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
Marin Shalamanove6332b02020-09-03 11:30:37 +02005967 return NO_ERROR;
5968 }
Adithya Srinivasan2d736322020-10-01 16:53:48 -07005969 // Modify the max number of display frames stored within FrameTimeline
5970 case 1038: {
5971 n = data.readInt32();
5972 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
5973 ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
5974 return BAD_VALUE;
5975 }
5976 if (n == 0) {
5977 // restore to default
5978 mFrameTimeline->reset();
5979 return NO_ERROR;
5980 }
5981 mFrameTimeline->setMaxDisplayFrames(n);
5982 return NO_ERROR;
5983 }
Ady Abraham0bb6a472020-10-12 10:22:13 -07005984 case 1039: {
Ady Abraham62f216c2020-10-13 19:07:23 -07005985 PhysicalDisplayId displayId = [&]() {
5986 Mutex::Autolock lock(mStateLock);
5987 return getDefaultDisplayDeviceLocked()->getPhysicalId();
5988 }();
5989
5990 auto inUid = static_cast<uid_t>(data.readInt32());
5991 const auto refreshRate = data.readFloat();
Ady Abraham62a0be22020-12-08 16:54:10 -08005992 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
5993 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
Ady Abraham0bb6a472020-10-12 10:22:13 -07005994 return NO_ERROR;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08005995 }
Alec Mouridd8bf2d2021-05-08 16:36:33 -07005996 // Toggle caching feature
5997 // First argument is an int32 - nonzero enables caching and zero disables caching
5998 // Second argument is an optional uint64 - if present, then limits enabling/disabling
5999 // caching to a particular physical display
6000 case 1040: {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006001 auto future = mScheduler->schedule([&] {
6002 n = data.readInt32();
6003 std::optional<PhysicalDisplayId> inputId = std::nullopt;
6004 if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6005 inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6006 if (!inputId || getPhysicalDisplayToken(*inputId)) {
6007 ALOGE("No display with id: %" PRIu64, inputDisplayId);
6008 return NAME_NOT_FOUND;
6009 }
6010 }
6011 {
6012 Mutex::Autolock lock(mStateLock);
6013 mLayerCachingEnabled = n != 0;
6014 for (const auto& [_, display] : mDisplays) {
6015 if (!inputId || *inputId == display->getPhysicalId()) {
6016 display->enableLayerCaching(mLayerCachingEnabled);
Alec Mouricdd722b2021-05-19 14:29:05 -07006017 }
Dominik Laskowski756b7892021-08-04 12:53:59 -07006018 }
6019 }
6020 return OK;
6021 });
Alec Mouricdd722b2021-05-19 14:29:05 -07006022
Dominik Laskowski756b7892021-08-04 12:53:59 -07006023 if (const status_t error = future.get(); error != OK) {
Alec Mouricdd722b2021-05-19 14:29:05 -07006024 return error;
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006025 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07006026 scheduleRepaint();
Alec Mouridd8bf2d2021-05-08 16:36:33 -07006027 return NO_ERROR;
6028 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006029 case 1041: { // Transaction tracing
Dominik Laskowski46471e62022-01-14 15:34:03 -08006030 if (mTransactionTracing) {
6031 if (data.readInt32()) {
6032 // Transaction tracing is always running but allow the user to temporarily
6033 // increase the buffer when actively debugging.
6034 mTransactionTracing->setBufferSize(
6035 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6036 } else {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08006037 mTransactionTracing->writeToFile();
Dominik Laskowski46471e62022-01-14 15:34:03 -08006038 mTransactionTracing->setBufferSize(
6039 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
Dominik Laskowski46471e62022-01-14 15:34:03 -08006040 }
Vishnu Nair7891e962021-11-11 12:07:21 -08006041 }
6042 reply->writeInt32(NO_ERROR);
6043 return NO_ERROR;
6044 }
Nataniel Borges533c2f82022-01-21 12:07:02 +01006045 case 1042: { // Write layers trace or transaction trace to file
6046 if (mTransactionTracing) {
6047 mTransactionTracing->writeToFile();
6048 }
6049 if (mLayerTracingEnabled) {
6050 mLayerTracing.writeToFile();
6051 }
6052 reply->writeInt32(NO_ERROR);
6053 return NO_ERROR;
6054 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08006055 }
6056 }
6057 return err;
6058}
6059
Ady Abrahama09852a2020-02-20 14:23:42 -08006060void SurfaceFlinger::kernelTimerChanged(bool expired) {
6061 static bool updateOverlay =
6062 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07006063 if (!updateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08006064
6065 // Update the overlay on the main thread to avoid race conditions with
Dominik Laskowskib0054a22022-03-03 09:03:06 -08006066 // mRefreshRateConfigs->getActiveMode()
Dominik Laskowski756b7892021-08-04 12:53:59 -07006067 static_cast<void>(mScheduler->schedule([=] {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006068 const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
Ady Abraham3efa3942021-06-24 19:01:25 -07006069 if (!display) {
6070 ALOGW("%s: default display is null", __func__);
6071 return;
6072 }
Adrian Salidoa942af82022-02-17 19:22:31 -08006073 if (!display->isRefreshRateOverlayEnabled()) return;
Ady Abraham690f4612021-07-01 23:24:03 -07006074
6075 const auto desiredActiveMode = display->getDesiredActiveMode();
6076 const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6077 ? std::make_optional(desiredActiveMode->mode->getId())
6078 : std::nullopt;
6079
6080 const bool timerExpired = mKernelIdleTimerEnabled && expired;
6081
Ady Abraham1b11bc62021-06-03 19:51:19 -07006082 if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -07006083 mScheduler->scheduleFrame();
Ady Abrahama09852a2020-02-20 14:23:42 -08006084 }
6085 }));
6086}
6087
ramindani32cf0602022-03-02 02:30:29 +00006088std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
6089SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6090 const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6091 android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6092 const auto timeout = getIdleTimerTimeout(displayId);
6093 if (isKernelIdleTimerHwcSupported) {
6094 if (const auto id = PhysicalDisplayId::tryCast(displayId);
6095 getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6096 // In order to decide if we can use the HWC api for idle timer
6097 // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6098 // without relying on hasDisplayCapability.
6099 // hasDisplayCapability relies on DisplayCapabilities
6100 // which are updated after we set the PowerMode::ON.
6101 // DISPLAY_IDLE_TIMER is a display driver property
6102 // and is available before the PowerMode::ON
6103 return {KernelIdleTimerController::HwcApi, timeout};
6104 }
6105 return {std::nullopt, timeout};
6106 }
6107 if (getKernelIdleTimerSyspropConfig(displayId)) {
6108 return {KernelIdleTimerController::Sysprop, timeout};
6109 }
6110
6111 return {std::nullopt, timeout};
6112}
6113
6114void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6115 KernelIdleTimerController controller,
6116 PhysicalDisplayId displayId) {
6117 switch (controller) {
6118 case KernelIdleTimerController::HwcApi: {
6119 getHwComposer().setIdleTimerEnabled(displayId, timeout);
6120 break;
6121 }
6122 case KernelIdleTimerController::Sysprop: {
6123 base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6124 break;
6125 }
6126 }
6127}
6128
Ana Krulecb9afd792020-06-11 13:16:15 -07006129void SurfaceFlinger::toggleKernelIdleTimer() {
6130 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
6131
Ady Abraham3efa3942021-06-24 19:01:25 -07006132 const auto display = getDefaultDisplayDeviceLocked();
6133 if (!display) {
6134 ALOGW("%s: default display is null", __func__);
6135 return;
6136 }
Ana Krulecb9afd792020-06-11 13:16:15 -07006137
Ady Abrahame9316b72021-09-24 17:04:36 -07006138 // If the support for kernel idle timer is disabled for the active display,
6139 // don't do anything.
ramindani32cf0602022-03-02 02:30:29 +00006140 const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6141 display->refreshRateConfigs().kernelIdleTimerController();
6142 if (!kernelIdleTimerController.has_value()) {
Ady Abrahame9316b72021-09-24 17:04:36 -07006143 return;
6144 }
6145
Ady Abraham3efa3942021-06-24 19:01:25 -07006146 const KernelIdleTimerAction action = display->refreshRateConfigs().getIdleTimerAction();
ramindani32cf0602022-03-02 02:30:29 +00006147
Ana Krulecb9afd792020-06-11 13:16:15 -07006148 switch (action) {
6149 case KernelIdleTimerAction::TurnOff:
6150 if (mKernelIdleTimerEnabled) {
6151 ATRACE_INT("KernelIdleTimer", 0);
ramindani32cf0602022-03-02 02:30:29 +00006152 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6153 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6154 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006155 mKernelIdleTimerEnabled = false;
6156 }
6157 break;
6158 case KernelIdleTimerAction::TurnOn:
6159 if (!mKernelIdleTimerEnabled) {
6160 ATRACE_INT("KernelIdleTimer", 1);
ramindani32cf0602022-03-02 02:30:29 +00006161 const std::chrono::milliseconds timeout =
6162 display->refreshRateConfigs().getIdleTimerTimeout();
6163 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6164 display->getPhysicalId());
Ana Krulecb9afd792020-06-11 13:16:15 -07006165 mKernelIdleTimerEnabled = true;
6166 }
6167 break;
Ana Krulecb9afd792020-06-11 13:16:15 -07006168 }
6169}
6170
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006171// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6172class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006173public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006174 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
6175 ~WindowDisconnector() {
6176 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006177 }
6178
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006179private:
6180 ANativeWindow* mWindow;
6181 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07006182};
6183
chaviw93df2ea2019-04-30 16:45:12 -07006184static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
6185 switch (colorMode) {
6186 case ColorMode::DISPLAY_P3:
6187 case ColorMode::BT2100_PQ:
6188 case ColorMode::BT2100_HLG:
6189 case ColorMode::DISPLAY_BT2020:
6190 return Dataspace::DISPLAY_P3;
6191 default:
6192 return Dataspace::V0_SRGB;
6193 }
6194}
6195
chaviwf5bb97b2021-04-28 15:35:37 -05006196static bool hasCaptureBlackoutContentPermission() {
6197 IPCThreadState* ipc = IPCThreadState::self();
6198 const int pid = ipc->getCallingPid();
6199 const int uid = ipc->getCallingUid();
6200 return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6201 PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6202}
6203
chaviw4b9d5e12020-08-04 18:30:35 -07006204static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6205 IPCThreadState* ipc = IPCThreadState::self();
6206 const int pid = ipc->getCallingPid();
6207 const int uid = ipc->getCallingUid();
6208 if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6209 return OK;
6210 }
6211
6212 // If the caller doesn't have the correct permissions but is only attempting to screenshot
6213 // itself, we allow it to continue.
6214 if (captureArgs.uid == uid) {
6215 return OK;
6216 }
6217
6218 ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6219 return PERMISSION_DENIED;
6220}
6221
Peiyong Lin05cc0112020-10-14 16:16:37 -07006222status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6223 static constexpr int kFifoPriority = 2;
6224 static constexpr int kOtherPriority = 0;
6225
6226 struct sched_param param = {0};
6227 int sched_policy;
6228 if (enabled) {
6229 sched_policy = SCHED_FIFO;
6230 param.sched_priority = kFifoPriority;
6231 } else {
6232 sched_policy = SCHED_OTHER;
6233 param.sched_priority = kOtherPriority;
6234 }
6235
6236 if (sched_setscheduler(0, sched_policy, &param) != 0) {
6237 return -errno;
6238 }
Wei Wang23aa5a62021-06-04 15:56:57 -07006239
6240 return NO_ERROR;
6241}
6242
6243status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6244 static const unsigned int kUclampMin =
6245 base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6246
6247 if (!kUclampMin) {
6248 // uclamp.min set to 0 (default), skip setting
6249 return NO_ERROR;
6250 }
6251
6252 // Currently, there is no wrapper in bionic: b/183240349.
6253 struct sched_attr {
6254 uint32_t size;
6255 uint32_t sched_policy;
6256 uint64_t sched_flags;
6257 int32_t sched_nice;
6258 uint32_t sched_priority;
6259 uint64_t sched_runtime;
6260 uint64_t sched_deadline;
6261 uint64_t sched_period;
6262 uint32_t sched_util_min;
6263 uint32_t sched_util_max;
6264 };
6265
6266 sched_attr attr = {};
6267 attr.size = sizeof(attr);
6268
6269 attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6270 attr.sched_util_min = enabled ? kUclampMin : 0;
6271 attr.sched_util_max = 1024;
6272
6273 if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6274 return -errno;
6275 }
6276
Peiyong Lin05cc0112020-10-14 16:16:37 -07006277 return NO_ERROR;
6278}
6279
chaviwd2432892020-07-24 17:42:39 -07006280status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006281 const sp<IScreenCaptureListener>& captureListener) {
chaviwd2432892020-07-24 17:42:39 -07006282 ATRACE_CALL();
6283
chaviw4b9d5e12020-08-04 18:30:35 -07006284 status_t validate = validateScreenshotPermissions(args);
6285 if (validate != OK) {
6286 return validate;
6287 }
6288
chaviwd2432892020-07-24 17:42:39 -07006289 if (!args.displayToken) return BAD_VALUE;
6290
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006291 wp<const DisplayDevice> displayWeak;
chaviwd2432892020-07-24 17:42:39 -07006292 ui::LayerStack layerStack;
6293 ui::Size reqSize(args.width, args.height);
6294 ui::Dataspace dataspace;
6295 {
6296 Mutex::Autolock lock(mStateLock);
6297 sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
6298 if (!display) return NAME_NOT_FOUND;
6299 displayWeak = display;
6300 layerStack = display->getLayerStack();
6301
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006302 // set the requested width/height to the logical display layer stack rect size by default
chaviwd2432892020-07-24 17:42:39 -07006303 if (args.width == 0 || args.height == 0) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006304 reqSize = display->getLayerStackSpaceRect().getSize();
chaviwd2432892020-07-24 17:42:39 -07006305 }
6306
arthurhung79e81aa2020-08-28 00:09:19 +08006307 // The dataspace is depended on the color mode of display, that could use non-native mode
6308 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6309 // and failed if display is not in native mode. This provide a way to force using native
6310 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006311 dataspace = args.dataspace;
6312 if (dataspace == ui::Dataspace::UNKNOWN) {
arthurhung79e81aa2020-08-28 00:09:19 +08006313 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6314 dataspace = pickDataspaceFromColorMode(colorMode);
6315 }
chaviwd2432892020-07-24 17:42:39 -07006316 }
6317
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006318 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviwd2432892020-07-24 17:42:39 -07006319 return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006320 args.useIdentityTransform, args.captureSecureLayers);
chaviwd2432892020-07-24 17:42:39 -07006321 });
6322
chaviw4b9d5e12020-08-04 18:30:35 -07006323 auto traverseLayers = [this, args, layerStack](const LayerVector::Visitor& visitor) {
6324 traverseLayersInLayerStack(layerStack, args.uid, visitor);
chaviwd2432892020-07-24 17:42:39 -07006325 };
chaviw03900772020-08-18 12:34:51 -07006326
Sally Qi59a9f502021-10-12 18:53:23 +00006327 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6328 reqSize, args.pixelFormat, args.allowProtected,
6329 args.grayscale, captureListener);
6330 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006331}
6332
Dominik Laskowskif1833852021-03-23 15:06:50 -07006333status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
chaviw8ffc7b82020-08-18 11:25:37 -07006334 const sp<IScreenCaptureListener>& captureListener) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02006335 ui::LayerStack layerStack;
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006336 wp<const DisplayDevice> displayWeak;
Marin Shalamanov1c434292020-06-12 01:47:29 +02006337 ui::Size size;
chaviw426b5c02020-07-27 11:20:15 -07006338 ui::Dataspace dataspace;
chaviw93df2ea2019-04-30 16:45:12 -07006339 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006340 Mutex::Autolock lock(mStateLock);
Dominik Laskowski7b9bf4c2021-03-18 12:21:29 -07006341
Dominik Laskowskif1833852021-03-23 15:06:50 -07006342 const auto display = getDisplayDeviceLocked(displayId);
chaviw93df2ea2019-04-30 16:45:12 -07006343 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006344 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07006345 }
6346
chaviw93df2ea2019-04-30 16:45:12 -07006347 displayWeak = display;
Dominik Laskowskif1833852021-03-23 15:06:50 -07006348 layerStack = display->getLayerStack();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006349 size = display->getLayerStackSpaceRect().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07006350
chaviw426b5c02020-07-27 11:20:15 -07006351 dataspace =
chaviw93df2ea2019-04-30 16:45:12 -07006352 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
6353 }
6354
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006355 RenderAreaFuture renderAreaFuture = ftl::defer([=] {
chaviw8ffc7b82020-08-18 11:25:37 -07006356 return DisplayRenderArea::create(displayWeak, Rect(), size, dataspace,
chaviwc6ad8af2020-08-03 11:33:30 -07006357 false /* useIdentityTransform */,
chaviwd2432892020-07-24 17:42:39 -07006358 false /* captureSecureLayers */);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006359 });
chaviw93df2ea2019-04-30 16:45:12 -07006360
Marin Shalamanov1c434292020-06-12 01:47:29 +02006361 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
chaviw4b9d5e12020-08-04 18:30:35 -07006362 traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, visitor);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006363 };
6364
Sally Qi59a9f502021-10-12 18:53:23 +00006365 if (captureListener == nullptr) {
6366 ALOGE("capture screen must provide a capture listener callback");
6367 return BAD_VALUE;
6368 }
6369 auto captureResultFuture =
6370 captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size,
6371 ui::PixelFormat::RGBA_8888, false /* allowProtected */,
6372 false /* grayscale */, captureListener);
6373 return captureResultFuture.get().status;
chaviw93df2ea2019-04-30 16:45:12 -07006374}
6375
chaviw3efadb12020-07-27 10:07:15 -07006376status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
chaviw8ffc7b82020-08-18 11:25:37 -07006377 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006378 ATRACE_CALL();
6379
chaviw4b9d5e12020-08-04 18:30:35 -07006380 status_t validate = validateScreenshotPermissions(args);
6381 if (validate != OK) {
6382 return validate;
6383 }
6384
Marin Shalamanov1c434292020-06-12 01:47:29 +02006385 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07006386 sp<Layer> parent;
chaviw3efadb12020-07-27 10:07:15 -07006387 Rect crop(args.sourceCrop);
Huihong Luoa339d0a2022-02-05 09:42:42 -08006388 std::unordered_set<sp<Layer>, SpHash<Layer>> excludeLayers;
chaviw3efadb12020-07-27 10:07:15 -07006389 ui::Dataspace dataspace;
chaviwf5bb97b2021-04-28 15:35:37 -05006390
6391 // Call this before holding mStateLock to avoid any deadlocking.
6392 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
6393
Robert Carrc0df3122019-04-11 13:18:21 -07006394 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006395 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08006396
Vishnu Nairf9096652021-07-20 18:49:42 -07006397 parent = fromHandle(args.layerHandle).promote();
chaviw79468ab2021-10-27 11:11:24 -05006398 if (parent == nullptr) {
Robert Carrc0df3122019-04-11 13:18:21 -07006399 ALOGE("captureLayers called with an invalid or removed parent");
6400 return NAME_NOT_FOUND;
6401 }
6402
chaviwf5bb97b2021-04-28 15:35:37 -05006403 if (!canCaptureBlackoutContent &&
Robert Carr6a160312021-05-17 12:08:20 -07006404 parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
Robert Carrc0df3122019-04-11 13:18:21 -07006405 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
6406 return PERMISSION_DENIED;
6407 }
6408
Robert Carr6a160312021-05-17 12:08:20 -07006409 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
chaviw3efadb12020-07-27 10:07:15 -07006410 if (args.sourceCrop.width() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006411 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006412 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07006413 }
6414
chaviw3efadb12020-07-27 10:07:15 -07006415 if (args.sourceCrop.height() <= 0) {
Robert Carrc0df3122019-04-11 13:18:21 -07006416 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08006417 crop.bottom = parentSourceBounds.getHeight();
6418 }
6419
chaviw17ac24b2021-01-28 18:50:05 -08006420 if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
Vishnu Nairefc42e22019-12-03 17:36:12 -08006421 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
6422 // crop was not specified, or an invalid frame scale was provided.
6423 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07006424 }
chaviw17ac24b2021-01-28 18:50:05 -08006425 reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
Robert Carrc0df3122019-04-11 13:18:21 -07006426
chaviw3efadb12020-07-27 10:07:15 -07006427 for (const auto& handle : args.excludeHandles) {
Vishnu Nairf9096652021-07-20 18:49:42 -07006428 sp<Layer> excludeLayer = fromHandle(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07006429 if (excludeLayer != nullptr) {
6430 excludeLayers.emplace(excludeLayer);
6431 } else {
6432 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
6433 return NAME_NOT_FOUND;
6434 }
6435 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08006436
arthurhung79e81aa2020-08-28 00:09:19 +08006437 // The dataspace is depended on the color mode of display, that could use non-native mode
6438 // (ex. displayP3) to enhance the content, but some cases are checking native RGB in bytes,
6439 // and failed if display is not in native mode. This provide a way to force using native
6440 // colors when capture.
Peiyong Lincd261472020-10-06 18:05:25 -07006441 dataspace = args.dataspace;
Robert Carrc0df3122019-04-11 13:18:21 -07006442 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08006443
Chia-I Wu20261cb2018-08-23 12:55:44 -07006444 // really small crop or frameScale
chaviw79468ab2021-10-27 11:11:24 -05006445 if (reqSize.width <= 0 || reqSize.height <= 0) {
6446 ALOGW("Failed to captureLayes: crop or scale too small");
6447 return BAD_VALUE;
Chia-I Wu20261cb2018-08-23 12:55:44 -07006448 }
6449
chaviw79468ab2021-10-27 11:11:24 -05006450 Rect layerStackSpaceRect(0, 0, reqSize.width, reqSize.height);
chaviw3efadb12020-07-27 10:07:15 -07006451 bool childrenOnly = args.childrenOnly;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08006452 RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
chaviw3efadb12020-07-27 10:07:15 -07006453 return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006454 childrenOnly, layerStackSpaceRect,
chaviw79468ab2021-10-27 11:11:24 -05006455 args.captureSecureLayers);
Marin Shalamanov1c434292020-06-12 01:47:29 +02006456 });
6457
chaviw03900772020-08-18 12:34:51 -07006458 auto traverseLayers = [parent, args, excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006459 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6460 if (!layer->isVisible()) {
6461 return;
chaviw4b9d5e12020-08-04 18:30:35 -07006462 } else if (args.childrenOnly && layer == parent.get()) {
6463 return;
6464 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
Robert Carr578038f2018-03-09 12:25:24 -08006465 return;
chaviwa76b2712017-09-20 12:02:26 -07006466 }
Robert Carr866455f2019-04-02 16:28:26 -07006467
Rob Carrc6d2d2b2021-10-25 16:51:49 +00006468 sp<Layer> p = layer;
Robert Carr866455f2019-04-02 16:28:26 -07006469 while (p != nullptr) {
6470 if (excludeLayers.count(p) != 0) {
6471 return;
6472 }
6473 p = p->getParent();
6474 }
6475
chaviwa76b2712017-09-20 12:02:26 -07006476 visitor(layer);
6477 });
6478 };
Robert Carr108b2c72019-04-02 16:32:58 -07006479
Sally Qi59a9f502021-10-12 18:53:23 +00006480 if (captureListener == nullptr) {
6481 ALOGE("capture screen must provide a capture listener callback");
6482 return BAD_VALUE;
6483 }
6484
6485 auto captureResultFuture = captureScreenCommon(std::move(renderAreaFuture), traverseLayers,
6486 reqSize, args.pixelFormat, args.allowProtected,
6487 args.grayscale, captureListener);
6488 return captureResultFuture.get().status;
chaviwa76b2712017-09-20 12:02:26 -07006489}
6490
Sally Qi59a9f502021-10-12 18:53:23 +00006491std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
6492 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6493 ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
6494 const sp<IScreenCaptureListener>& captureListener) {
chaviwa76b2712017-09-20 12:02:26 -07006495 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006496
Garfield Tan9c9c1912021-07-19 12:02:16 -07006497 if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
6498 ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
6499 ") that exceeds render target size limit.",
6500 bufferSize.getWidth(), bufferSize.getHeight());
Sally Qi59a9f502021-10-12 18:53:23 +00006501 return ftl::yield<renderengine::RenderEngineResult>({BAD_VALUE, base::unique_fd()}).share();
Garfield Tan9c9c1912021-07-19 12:02:16 -07006502 }
6503
Peiyong Lin05cc0112020-10-14 16:16:37 -07006504 // Loop over all visible layers to see whether there's any protected layer. A protected layer is
6505 // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
6506 // A protected layer has no implication on whether it's secure, which is explicitly set by
6507 // application to avoid being screenshot or drawn via unsecure display.
6508 const bool supportsProtected = getRenderEngine().supportsProtectedContent();
6509 bool hasProtectedLayer = false;
6510 if (allowProtected && supportsProtected) {
Dominik Laskowski756b7892021-08-04 12:53:59 -07006511 auto future = mScheduler->schedule([=]() {
6512 bool protectedLayerFound = false;
6513 traverseLayers([&](Layer* layer) {
6514 protectedLayerFound =
6515 protectedLayerFound || (layer->isVisible() && layer->isProtected());
6516 });
6517 return protectedLayerFound;
6518 });
6519 hasProtectedLayer = future.get();
Peiyong Lin05cc0112020-10-14 16:16:37 -07006520 }
6521
Richard Liucbcb8952020-04-08 10:51:55 +00006522 const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
6523 GRALLOC_USAGE_HW_TEXTURE |
Peiyong Lin05cc0112020-10-14 16:16:37 -07006524 (hasProtectedLayer && allowProtected && supportsProtected
6525 ? GRALLOC_USAGE_PROTECTED
6526 : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
chaviw426b5c02020-07-27 11:20:15 -07006527 sp<GraphicBuffer> buffer =
6528 getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
6529 static_cast<android_pixel_format>(reqPixelFormat),
6530 1 /* layerCount */, usage, "screenshot");
Alec Mouri7013b6f2021-02-12 11:16:54 -08006531
6532 const status_t bufferStatus = buffer->initCheck();
6533 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureScreenCommon: Buffer failed to allocate: %d",
6534 bufferStatus);
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006535 const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
6536 renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
6537 renderengine::impl::ExternalTexture::Usage::
6538 WRITEABLE);
Alec Mouria90a5702021-04-16 16:36:21 +00006539 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, texture,
Derek Sollenberger34257882021-04-06 18:32:34 +00006540 false /* regionSampling */, grayscale, captureListener);
Dan Stozaec460082018-12-17 15:35:09 -08006541}
6542
Sally Qi59a9f502021-10-12 18:53:23 +00006543std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::captureScreenCommon(
Alec Mouria90a5702021-04-16 16:36:21 +00006544 RenderAreaFuture renderAreaFuture, TraverseLayersFunction traverseLayers,
6545 const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
6546 bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
chaviw03900772020-08-18 12:34:51 -07006547 ATRACE_CALL();
6548
chaviwf5bb97b2021-04-28 15:35:37 -05006549 bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
Robert Carr03480e22018-01-04 16:02:06 -08006550
Dominik Laskowski756b7892021-08-04 12:53:59 -07006551 auto scheduleResultFuture = mScheduler->schedule([=,
6552 renderAreaFuture =
6553 std::move(renderAreaFuture)]() mutable
6554 -> std::shared_future<
6555 renderengine::RenderEngineResult> {
chaviw03900772020-08-18 12:34:51 -07006556 ScreenCaptureResults captureResults;
6557 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
6558 if (!renderArea) {
6559 ALOGW("Skipping screen capture because of invalid render area.");
6560 captureResults.result = NO_MEMORY;
Ady Abraham99599942021-01-27 20:27:23 -08006561 captureListener->onScreenCaptureCompleted(captureResults);
Sally Qi59a9f502021-10-12 18:53:23 +00006562 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()})
6563 .share();
chaviw03900772020-08-18 12:34:51 -07006564 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006565
Sally Qi59a9f502021-10-12 18:53:23 +00006566 std::shared_future<renderengine::RenderEngineResult> renderEngineResultFuture;
6567
chaviw03900772020-08-18 12:34:51 -07006568 renderArea->render([&] {
Sally Qi59a9f502021-10-12 18:53:23 +00006569 renderEngineResultFuture =
Robert Carr12a3b9b2022-03-10 09:55:29 -08006570 renderScreenImpl(*renderArea, traverseLayers, buffer,
Sally Qi59a9f502021-10-12 18:53:23 +00006571 canCaptureBlackoutContent, regionSampling, grayscale,
6572 captureResults);
chaviw03900772020-08-18 12:34:51 -07006573 });
Sally Qi59a9f502021-10-12 18:53:23 +00006574 // spring up a thread to unblock SF main thread and wait for
6575 // RenderEngineResult to be available
6576 if (captureListener != nullptr) {
6577 std::async([=]() mutable {
6578 ATRACE_NAME("captureListener is nonnull!");
6579 auto& [status, drawFence] = renderEngineResultFuture.get();
6580 captureResults.result = status;
6581 captureResults.fence = new Fence(dup(drawFence));
6582 captureListener->onScreenCaptureCompleted(captureResults);
6583 });
6584 }
6585 return renderEngineResultFuture;
6586 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006587
Sally Qi59a9f502021-10-12 18:53:23 +00006588 // flatten scheduleResultFuture object to single shared_future object
6589 if (captureListener == nullptr) {
6590 std::future<renderengine::RenderEngineResult> captureScreenResultFuture =
6591 ftl::chain(std::move(scheduleResultFuture))
6592 .then([=](std::shared_future<renderengine::RenderEngineResult> futureObject)
6593 -> renderengine::RenderEngineResult {
6594 auto& [status, drawFence] = futureObject.get();
6595 return {status, base::unique_fd(dup(drawFence))};
6596 });
6597 return captureScreenResultFuture.share();
6598 } else {
6599 return ftl::yield<renderengine::RenderEngineResult>({NO_ERROR, base::unique_fd()}).share();
6600 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006601}
6602
Robert Carr12a3b9b2022-03-10 09:55:29 -08006603std::shared_future<renderengine::RenderEngineResult> SurfaceFlinger::renderScreenImpl(
Alec Mouria90a5702021-04-16 16:36:21 +00006604 const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
chaviwf5bb97b2021-04-28 15:35:37 -05006605 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
6606 bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
6607 ScreenCaptureResults& captureResults) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006608 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006609
chaviw426b5c02020-07-27 11:20:15 -07006610 traverseLayers([&](Layer* layer) {
6611 captureResults.capturedSecureLayers =
6612 captureResults.capturedSecureLayers || (layer->isVisible() && layer->isSecure());
6613 });
6614
Vishnu Nairdbbe3852022-01-12 20:22:11 -08006615 const bool useProtected = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006616
chaviw426b5c02020-07-27 11:20:15 -07006617 // We allow the system server to take screenshots of secure layers for
6618 // use in situations like the Screen-rotation animation and place
6619 // the impetus on WindowManager to not persist them.
chaviwf5bb97b2021-04-28 15:35:37 -05006620 if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
chaviw426b5c02020-07-27 11:20:15 -07006621 ALOGW("FB is protected: PERMISSION_DENIED");
Sally Qi59a9f502021-10-12 18:53:23 +00006622 return ftl::yield<renderengine::RenderEngineResult>({PERMISSION_DENIED, base::unique_fd()})
6623 .share();
chaviw426b5c02020-07-27 11:20:15 -07006624 }
6625
Alec Mouria90a5702021-04-16 16:36:21 +00006626 captureResults.buffer = buffer->getBuffer();
Robert Carr12a3b9b2022-03-10 09:55:29 -08006627 auto dataspace = renderArea.getReqDataSpace();
6628 auto parent = renderArea.getParentLayer();
6629 if ((dataspace == ui::Dataspace::UNKNOWN) && (parent != nullptr)) {
6630 Mutex::Autolock lock(mStateLock);
6631 auto display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
6632 return display.getLayerStack() == layerStack;
6633 });
6634 if (!display) {
6635 // If the layer is not on a display, use the dataspace for the default display.
6636 display = getDefaultDisplayDeviceLocked();
6637 }
6638
6639 const ui::ColorMode colorMode = display->getCompositionDisplay()->getState().colorMode;
6640 dataspace = pickDataspaceFromColorMode(colorMode);
6641 }
6642 captureResults.capturedDataspace = dataspace;
chaviw426b5c02020-07-27 11:20:15 -07006643
chaviwa76b2712017-09-20 12:02:26 -07006644 const auto reqWidth = renderArea.getReqWidth();
6645 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07006646 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07006647 const auto transform = renderArea.getTransform();
6648 const auto rotation = renderArea.getRotationFlags();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006649 const auto& layerStackSpaceRect = renderArea.getLayerStackSpaceRect();
Dan Stozac1879002014-05-22 15:59:05 -07006650
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006651 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08006652 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006653
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006654 // assume that bounds are never offset, and that they are the same as the
6655 // buffer bounds.
6656 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006657 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07006658 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07006659
Robert Carr12a3b9b2022-03-10 09:55:29 -08006660 clientCompositionDisplay.outputDataspace = dataspace;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006661 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006662
chaviw17ac24b2021-01-28 18:50:05 -08006663 const float colorSaturation = grayscale ? 0 : 1;
6664 clientCompositionDisplay.colorTransform = calculateColorMatrix(colorSaturation);
6665
chaviw50da5042018-04-09 13:49:37 -07006666 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006667
Vishnu Nair9b079a22020-01-21 14:36:08 -08006668 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006669 fillLayer.source.buffer.buffer = nullptr;
6670 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07006671 fillLayer.geometry.boundaries =
6672 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006673 fillLayer.alpha = half(alpha);
6674 clientCompositionLayers.push_back(fillLayer);
6675
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006676 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08006677 std::vector<Layer*> renderedLayers;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006678 bool disableBlurs = false;
chaviwa76b2712017-09-20 12:02:26 -07006679 traverseLayers([&](Layer* layer) {
Robert Carr6a160312021-05-17 12:08:20 -07006680 disableBlurs |= layer->getDrawingState().sidebandStream != nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006681
Lloyd Piquef16688f2019-02-19 17:47:57 -08006682 Region clip(renderArea.getBounds());
6683 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
6684 clip,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07006685 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07006686 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08006687 renderArea.isSecure(),
Peiyong Lin05cc0112020-10-14 16:16:37 -07006688 useProtected,
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02006689 layerStackSpaceRect,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006690 clientCompositionDisplay.outputDataspace,
Alec Mourif54453c2021-05-13 16:28:28 -07006691 true, /* realContentIsVisible */
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006692 false, /* clearContent */
Alec Mourif54453c2021-05-13 16:28:28 -07006693 disableBlurs ? compositionengine::LayerFE::ClientCompositionTargetSettings::
6694 BlurSetting::Disabled
6695 : compositionengine::LayerFE::ClientCompositionTargetSettings::
6696 BlurSetting::Enabled,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07006697 DisplayDevice::sDefaultMaxLumiance,
6698
Lloyd Piquef16688f2019-02-19 17:47:57 -08006699 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08006700 std::vector<compositionengine::LayerFE::LayerSettings> results =
6701 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08006702 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07006703 for (auto& settings : results) {
6704 settings.geometry.positionTransform =
6705 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07006706 // There's no need to process blurs when we're executing region sampling,
6707 // we're just trying to understand what we're drawing, and doing so without
6708 // blurs is already a pretty good approximation.
6709 if (regionSampling) {
6710 settings.backgroundBlurRadius = 0;
6711 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07006712 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006713
Yichi Chen40773d92020-04-01 10:10:18 +08006714 clientCompositionLayers.insert(clientCompositionLayers.end(),
6715 std::make_move_iterator(results.begin()),
6716 std::make_move_iterator(results.end()));
6717 renderedLayers.push_back(layer);
6718 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01006719
chaviwa76b2712017-09-20 12:02:26 -07006720 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006721
Sally Qi59a9f502021-10-12 18:53:23 +00006722 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
6723 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08006724 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00006725 std::back_inserter(clientRenderEngineLayers),
6726 [](compositionengine::LayerFE::LayerSettings& settings)
6727 -> renderengine::LayerSettings { return settings; });
Vishnu Nair9b079a22020-01-21 14:36:08 -08006728
Alec Mouri6338c9d2019-02-07 16:57:51 -08006729 // Use an empty fence for the buffer fence, since we just created the buffer so
6730 // there is no need for synchronization with the GPU.
6731 base::unique_fd bufferFence;
Peiyong Lin05cc0112020-10-14 16:16:37 -07006732 getRenderEngine().useProtectedContext(useProtected);
Alec Mouri0d995102021-02-24 16:53:38 -08006733
Alec Mouria90a5702021-04-16 16:36:21 +00006734 const constexpr bool kUseFramebufferCache = false;
Sally Qi59a9f502021-10-12 18:53:23 +00006735 std::future<renderengine::RenderEngineResult> drawLayersResult =
6736 getRenderEngine().drawLayers(clientCompositionDisplay, clientRenderEngineLayers, buffer,
6737 kUseFramebufferCache, std::move(bufferFence));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006738
Sally Qi59a9f502021-10-12 18:53:23 +00006739 std::shared_future<renderengine::RenderEngineResult> drawLayersResultFuture =
6740 drawLayersResult.share(); // drawLayersResult will be moved to shared one
6741
6742 for (auto* layer : renderedLayers) {
6743 // make a copy of shared_future object for each layer
6744 layer->onLayerDisplayed(drawLayersResultFuture);
Yichi Chen40773d92020-04-01 10:10:18 +08006745 }
Ady Abraham99599942021-01-27 20:27:23 -08006746
Peiyong Lin05cc0112020-10-14 16:16:37 -07006747 // Always switch back to unprotected context.
6748 getRenderEngine().useProtectedContext(false);
Mathias Agopian180f10d2013-04-10 22:55:41 -07006749
Sally Qi59a9f502021-10-12 18:53:23 +00006750 return drawLayersResultFuture;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006751}
6752
chaviwbf023a62021-06-07 16:00:06 -05006753void SurfaceFlinger::windowInfosReported() {
chaviw95ef3c42019-02-14 10:55:09 -08006754 Mutex::Autolock _l(mStateLock);
Arthur Hung2274a312021-04-28 15:13:06 +00006755 signalSynchronousTransactions(CountDownLatch::eSyncInputWindows);
chaviw95ef3c42019-02-14 10:55:09 -08006756}
chaviw5f21a5e2019-02-14 10:00:34 -08006757
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006758// ---------------------------------------------------------------------------
6759
Edgar Arriaga844fa672020-01-16 14:21:42 -08006760void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
6761 layersSortedByZ.traverse(visitor);
6762}
6763
Dan Stoza412903f2017-04-27 13:42:17 -07006764void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6765 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006766}
6767
Dan Stoza412903f2017-04-27 13:42:17 -07006768void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6769 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006770}
6771
chaviw4b9d5e12020-08-04 18:30:35 -07006772void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
Marin Shalamanov1c434292020-06-12 01:47:29 +02006773 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07006774 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006775 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006776 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006777 if (layer->getLayerStack() != layerStack) {
chaviwa76b2712017-09-20 12:02:26 -07006778 continue;
6779 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006780 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006781 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07006782 if (layer->isInternalDisplayOverlay()) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006783 return;
6784 }
chaviwa76b2712017-09-20 12:02:26 -07006785 if (!layer->isVisible()) {
6786 return;
6787 }
chaviw4b9d5e12020-08-04 18:30:35 -07006788 if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
6789 return;
6790 }
chaviwa76b2712017-09-20 12:02:26 -07006791 visitor(layer);
6792 });
6793 }
6794}
6795
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006796status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
Steven Thomasd4071902020-03-24 16:02:53 -07006797 const sp<DisplayDevice>& display,
6798 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006799 Mutex::Autolock lock(mStateLock);
6800
Ady Abrahamfb853662021-04-09 11:46:40 -07006801 if (mDebugDisplayModeSetByBackdoor) {
6802 // ignore this request as mode is overridden by backdoor
6803 return NO_ERROR;
6804 }
6805
Ady Abraham3efa3942021-06-24 19:01:25 -07006806 status_t setPolicyResult = overridePolicy
6807 ? display->refreshRateConfigs().setOverridePolicy(policy)
6808 : display->refreshRateConfigs().setDisplayManagerPolicy(*policy);
6809 if (setPolicyResult < 0) {
6810 return BAD_VALUE;
6811 }
6812 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
6813 return NO_ERROR;
6814 }
6815
Ady Abraham3efa3942021-06-24 19:01:25 -07006816 scheduler::RefreshRateConfigs::Policy currentPolicy =
6817 display->refreshRateConfigs().getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006818
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006819 ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006820
Ana Krulecb9afd792020-06-11 13:16:15 -07006821 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6822 // be depending in this callback.
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006823 const auto activeMode = display->getActiveMode();
Ady Abraham690f4612021-07-01 23:24:03 -07006824 if (isDisplayActiveLocked(display)) {
6825 mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6826 toggleKernelIdleTimer();
6827 } else {
6828 mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
6829 }
Ady Abraham838de062019-02-04 10:24:03 -08006830
Ady Abraham690f4612021-07-01 23:24:03 -07006831 const DisplayModePtr preferredDisplayMode = [&] {
6832 const auto schedulerMode = mScheduler->getPreferredDisplayMode();
6833 if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
6834 return schedulerMode;
6835 }
6836
6837 return display->getMode(currentPolicy.defaultMode);
6838 }();
6839
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006840 ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
Ady Abraham690f4612021-07-01 23:24:03 -07006841 preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006842
Ady Abraham690f4612021-07-01 23:24:03 -07006843 if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006844 ALOGV("switching to Scheduler preferred display mode %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006845 preferredDisplayMode->getId().value());
Dominik Laskowski068173d2021-08-11 17:22:59 -07006846 setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006847 } else {
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006848 LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
Ady Abraham690f4612021-07-01 23:24:03 -07006849 preferredDisplayMode->getId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006850 }
6851
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006852 return NO_ERROR;
6853}
6854
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006855status_t SurfaceFlinger::setDesiredDisplayModeSpecs(
6856 const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
6857 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
6858 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006859 ATRACE_CALL();
6860
6861 if (!displayToken) {
6862 return BAD_VALUE;
6863 }
6864
Dominik Laskowski756b7892021-08-04 12:53:59 -07006865 auto future = mScheduler->schedule([=]() -> status_t {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08006866 const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006867 if (!display) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006868 ALOGE("Attempt to set desired display modes for invalid display token %p",
Ana Krulec234bb162019-11-10 22:55:55 +01006869 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006870 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006871 } else if (display->isVirtual()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006872 ALOGW("Attempt to set desired display modes for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006873 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006874 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006875 using Policy = scheduler::RefreshRateConfigs::Policy;
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006876 const Policy policy{DisplayModeId(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +02006877 allowGroupSwitching,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07006878 {Fps::fromValue(primaryRefreshRateMin),
6879 Fps::fromValue(primaryRefreshRateMax)},
6880 {Fps::fromValue(appRequestRefreshRateMin),
6881 Fps::fromValue(appRequestRefreshRateMax)}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006882 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006883
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006884 return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006885 }
6886 });
6887
6888 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006889}
6890
Marin Shalamanov228f46b2021-01-28 21:11:45 +01006891status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
6892 ui::DisplayModeId* outDefaultMode,
6893 bool* outAllowGroupSwitching,
6894 float* outPrimaryRefreshRateMin,
6895 float* outPrimaryRefreshRateMax,
6896 float* outAppRequestRefreshRateMin,
6897 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006898 ATRACE_CALL();
6899
Marin Shalamanova7fe3042021-01-29 21:02:08 +01006900 if (!displayToken || !outDefaultMode || !outPrimaryRefreshRateMin ||
Steven Thomasf734df42020-04-13 21:09:28 -07006901 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006902 return BAD_VALUE;
6903 }
6904
6905 Mutex::Autolock lock(mStateLock);
6906 const auto display = getDisplayDeviceLocked(displayToken);
6907 if (!display) {
6908 return NAME_NOT_FOUND;
6909 }
6910
Ady Abraham3efa3942021-06-24 19:01:25 -07006911 if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006912 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006913 }
Ady Abraham3efa3942021-06-24 19:01:25 -07006914
6915 scheduler::RefreshRateConfigs::Policy policy =
6916 display->refreshRateConfigs().getDisplayManagerPolicy();
6917 *outDefaultMode = policy.defaultMode.value();
6918 *outAllowGroupSwitching = policy.allowGroupSwitching;
6919 *outPrimaryRefreshRateMin = policy.primaryRange.min.getValue();
6920 *outPrimaryRefreshRateMax = policy.primaryRange.max.getValue();
6921 *outAppRequestRefreshRateMin = policy.appRequestRange.min.getValue();
6922 *outAppRequestRefreshRateMax = policy.appRequestRange.max.getValue();
6923 return NO_ERROR;
Ana Krulec0782b882019-10-15 17:34:54 -07006924}
6925
Vishnu Nairf9096652021-07-20 18:49:42 -07006926wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) const {
6927 return Layer::fromHandle(handle);
Robert Carrc0df3122019-04-11 13:18:21 -07006928}
6929
Dominik Laskowski75848362019-11-11 17:57:20 -08006930void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006931 mNumLayers++;
Ady Abrahambe09aad2021-05-03 18:59:38 -07006932 if (!layer->isRemovedFromCurrentState()) {
6933 mScheduler->registerLayer(layer);
6934 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006935}
6936
6937void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6938 mNumLayers--;
Robert Carr867be372021-06-29 17:36:02 -07006939 removeHierarchyFromOffscreenLayers(layer);
Ady Abrahambe09aad2021-05-03 18:59:38 -07006940 if (!layer->isRemovedFromCurrentState()) {
6941 mScheduler->deregisterLayer(layer);
6942 }
Dominik Laskowski46471e62022-01-14 15:34:03 -08006943 if (mTransactionTracing) {
6944 mTransactionTracing->onLayerRemoved(layer->getSequence());
Vishnu Nair84125ac2021-12-02 08:47:48 -08006945 }
Valerie Hauc5686802019-11-22 14:18:09 -08006946}
6947
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07006948void SurfaceFlinger::onLayerUpdate() {
6949 scheduleCommit(FrameHint::kActive);
6950}
6951
Valerie Hauc5686802019-11-22 14:18:09 -08006952// WARNING: ONLY CALL THIS FROM LAYER DTOR
6953// Here we add children in the current state to offscreen layers and remove the
6954// layer itself from the offscreen layer list. Since
6955// this is the dtor, it is safe to access the current state. This keeps us
6956// from dangling children layers such that they are not reachable from the
6957// Drawing state nor the offscreen layer list
6958// See b/141111965
Robert Carr867be372021-06-29 17:36:02 -07006959void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
Valerie Hauc5686802019-11-22 14:18:09 -08006960 for (auto& child : layer->getCurrentChildren()) {
6961 mOffscreenLayers.emplace(child.get());
6962 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006963 mOffscreenLayers.erase(layer);
6964}
6965
Robert Carr867be372021-06-29 17:36:02 -07006966void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6967 mOffscreenLayers.erase(layer);
6968}
6969
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006970status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6971 float lightPosY, float lightPosZ,
6972 float lightRadius) {
6973 Mutex::Autolock _l(mStateLock);
6974 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6975 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6976 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6977 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6978 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6979
6980 // these values are overridden when calculating the shadow settings for a layer.
6981 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6982 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006983 return NO_ERROR;
6984}
6985
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006986const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6987 const {
6988 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6989 // on the work to remove the table in that bug rather than adding more to
6990 // it.
6991 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006992 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6993 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6994 };
6995 return genericLayerMetadataKeyMap;
6996}
6997
Steven Thomas62a4cf82020-01-31 12:04:03 -08006998status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
Marin Shalamanovc5986772021-03-16 16:09:49 +01006999 int8_t compatibility, int8_t changeFrameRateStrategy) {
7000 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
7001 "SurfaceFlinger::setFrameRate")) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08007002 return BAD_VALUE;
7003 }
7004
Dominik Laskowski756b7892021-08-04 12:53:59 -07007005 static_cast<void>(mScheduler->schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07007006 Mutex::Autolock lock(mStateLock);
7007 if (authenticateSurfaceTextureLocked(surface)) {
7008 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
Ady Abraham162f6432020-10-08 18:40:47 +00007009 if (layer == nullptr) {
7010 ALOGE("Attempt to set frame rate on a layer that no longer exists");
7011 return BAD_VALUE;
7012 }
Marin Shalamanovc5986772021-03-16 16:09:49 +01007013 const auto strategy =
7014 Layer::FrameRate::convertChangeFrameRateStrategy(changeFrameRateStrategy);
Ady Abraham60e42ea2020-03-09 19:17:31 -07007015 if (layer->setFrameRate(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007016 Layer::FrameRate(Fps::fromValue(frameRate),
Marin Shalamanov46084422020-10-13 12:33:42 +02007017 Layer::FrameRate::convertCompatibility(compatibility),
Marin Shalamanovc5986772021-03-16 16:09:49 +01007018 strategy))) {
Ady Abraham60e42ea2020-03-09 19:17:31 -07007019 setTransactionFlags(eTraversalNeeded);
7020 }
7021 } else {
7022 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
7023 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08007024 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07007025 return NO_ERROR;
7026 }));
7027
Steven Thomas62a4cf82020-01-31 12:04:03 -08007028 return NO_ERROR;
7029}
7030
Andy Yu2ae6b6b2021-11-18 14:51:06 -08007031status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7032 PhysicalDisplayId displayId = [&]() {
7033 Mutex::Autolock lock(mStateLock);
7034 return getDefaultDisplayDeviceLocked()->getPhysicalId();
7035 }();
7036
7037 mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7038 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7039 return NO_ERROR;
7040}
7041
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10007042status_t SurfaceFlinger::setFrameTimelineInfo(const sp<IGraphicBufferProducer>& surface,
7043 const FrameTimelineInfo& frameTimelineInfo) {
Ady Abraham74e17562020-08-24 18:18:19 -07007044 Mutex::Autolock lock(mStateLock);
7045 if (!authenticateSurfaceTextureLocked(surface)) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10007046 ALOGE("Attempt to set frame timeline info on an unrecognized IGraphicBufferProducer");
Ady Abraham74e17562020-08-24 18:18:19 -07007047 return BAD_VALUE;
7048 }
7049
7050 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
Ady Abrahamfdf1bff2020-09-28 11:27:30 -07007051 if (layer == nullptr) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10007052 ALOGE("Attempt to set frame timeline info on a layer that no longer exists");
Ady Abrahamfdf1bff2020-09-28 11:27:30 -07007053 return BAD_VALUE;
7054 }
7055
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10007056 layer->setFrameTimelineInfoForBuffer(frameTimelineInfo);
Ady Abraham74e17562020-08-24 18:18:19 -07007057 return NO_ERROR;
7058}
7059
Dominik Laskowski20134642020-04-20 22:36:44 -07007060void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
Ady Abraham1b11bc62021-06-03 19:51:19 -07007061 for (const auto& [ignored, display] : mDisplays) {
7062 if (display->isInternal()) {
7063 display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
Dominik Laskowski20134642020-04-20 22:36:44 -07007064 }
Ady Abraham1b11bc62021-06-03 19:51:19 -07007065 }
Dominik Laskowski20134642020-04-20 22:36:44 -07007066}
7067
Pablo Gamito6ee484d2020-07-30 14:26:28 +00007068status_t SurfaceFlinger::addTransactionTraceListener(
7069 const sp<gui::ITransactionTraceListener>& listener) {
7070 if (!listener) {
7071 return BAD_VALUE;
7072 }
7073
7074 mInterceptor->addTransactionTraceListener(listener);
7075
7076 return NO_ERROR;
7077}
7078
Huihong Luo02186fb2022-02-23 14:21:54 -08007079int SurfaceFlinger::getGpuContextPriority() {
Alec Mourid6f09462020-12-07 11:18:17 -08007080 return getRenderEngine().getContextPriority();
Ana Krulec31f2b3c2020-12-14 14:30:09 -08007081}
7082
Ady Abraham899dcdb2021-06-15 16:56:21 -07007083int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7084 std::chrono::nanoseconds presentLatency) {
7085 auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7086 if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
Ady Abraham564f9de2021-02-03 18:34:33 -08007087 pipelineDepth++;
7088 }
Ady Abraham899dcdb2021-06-15 16:56:21 -07007089 return std::max(1ll, pipelineDepth - 1);
Ady Abraham564f9de2021-02-03 18:34:33 -08007090}
7091
Ady Abraham899dcdb2021-06-15 16:56:21 -07007092status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007093 Fps maxRefreshRate = 60_Hz;
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007094
7095 if (!getHwComposer().isHeadless()) {
7096 if (const auto display = getDefaultDisplayDevice()) {
7097 maxRefreshRate = display->refreshRateConfigs().getSupportedRefreshRateRange().max;
Ady Abraham3efa3942021-06-24 19:01:25 -07007098 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007099 }
7100
7101 *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
Ady Abraham564f9de2021-02-03 18:34:33 -08007102 return NO_ERROR;
7103}
7104
rnleeed20fa42021-08-10 18:00:03 -07007105uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07007106 Fps refreshRate = 60_Hz;
Ady Abraham3efa3942021-06-24 19:01:25 -07007107
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007108 if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7109 refreshRate = *frameRateOverride;
7110 } else if (!getHwComposer().isHeadless()) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08007111 if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08007112 refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -07007113 }
Dominik Laskowskif8db0f02021-04-19 11:05:25 -07007114 }
Ady Abraham3efa3942021-06-24 19:01:25 -07007115
Ady Abraham899dcdb2021-06-15 16:56:21 -07007116 return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7117}
7118
7119int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7120 const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7121 const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7122 return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7123}
7124
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007125void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state) {
7126 sp<Layer> layer = state.layer.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007127 if (!layer) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007128 ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7129 return;
arthurhungdba591c2021-02-08 17:28:49 +08007130 }
7131
7132 sp<Layer> parent;
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007133 bool addToRoot = state.addToRoot;
7134 if (state.initialParent != nullptr) {
7135 parent = state.initialParent.promote();
arthurhungdba591c2021-02-08 17:28:49 +08007136 if (parent == nullptr) {
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007137 ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
Garfield Tand712ad32021-10-27 13:44:22 -07007138 addToRoot = false;
arthurhungdba591c2021-02-08 17:28:49 +08007139 }
arthurhungdba591c2021-02-08 17:28:49 +08007140 }
7141
Garfield Tand712ad32021-10-27 13:44:22 -07007142 if (parent == nullptr && addToRoot) {
Vishnu Nair14d218b2021-07-13 13:57:39 -07007143 layer->setIsAtRoot(true);
arthurhungdba591c2021-02-08 17:28:49 +08007144 mCurrentState.layersSortedByZ.add(layer);
7145 } else if (parent == nullptr) {
7146 layer->onRemovedFromCurrentState();
7147 } else if (parent->isRemovedFromCurrentState()) {
7148 parent->addChild(layer);
7149 layer->onRemovedFromCurrentState();
7150 } else {
7151 parent->addChild(layer);
7152 }
7153
Ady Abraham1273ac12021-08-26 17:31:53 -07007154 layer->updateTransformHint(mActiveDisplayTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +08007155
Arthur Hung23e07502021-10-15 11:58:19 +00007156 mInterceptor->saveSurfaceCreation(layer);
arthurhungdba591c2021-02-08 17:28:49 +08007157}
Ady Abraham562c2712021-05-07 15:10:42 -07007158
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07007159void SurfaceFlinger::sample() {
Ady Abraham562c2712021-05-07 15:10:42 -07007160 if (!mLumaSampling || !mRegionSamplingThread) {
7161 return;
7162 }
7163
Dominik Laskowski756b7892021-08-04 12:53:59 -07007164 mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
Ady Abraham562c2712021-05-07 15:10:42 -07007165}
7166
Ady Abrahamed3290f2021-05-17 15:12:14 -07007167void SurfaceFlinger::onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay) {
7168 mScheduler->onActiveDisplayAreaChanged(activeDisplay->getWidth() * activeDisplay->getHeight());
7169 getRenderEngine().onActiveDisplaySizeChanged(activeDisplay->getSize());
7170}
7171
7172void SurfaceFlinger::onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) {
7173 ATRACE_CALL();
7174
Ady Abrahamdb036a82021-07-16 14:18:34 -07007175 if (const auto display = getDisplayDeviceLocked(mActiveDisplayToken)) {
7176 display->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
7177 }
7178
Ady Abrahamed3290f2021-05-17 15:12:14 -07007179 if (!activeDisplay) {
7180 ALOGE("%s: activeDisplay is null", __func__);
7181 return;
7182 }
Ady Abrahamdb036a82021-07-16 14:18:34 -07007183 mActiveDisplayToken = activeDisplay->getDisplayToken();
Ady Abrahamdb036a82021-07-16 14:18:34 -07007184 activeDisplay->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
Ady Abraham3efa3942021-06-24 19:01:25 -07007185 updateInternalDisplayVsyncLocked(activeDisplay);
Ady Abraham690f4612021-07-01 23:24:03 -07007186 mScheduler->setModeChangePending(false);
Ady Abraham3efa3942021-06-24 19:01:25 -07007187 mScheduler->setRefreshRateConfigs(activeDisplay->holdRefreshRateConfigs());
Ady Abrahamed3290f2021-05-17 15:12:14 -07007188 onActiveDisplaySizeChanged(activeDisplay);
Ady Abraham1273ac12021-08-26 17:31:53 -07007189 mActiveDisplayTransformHint = activeDisplay->getTransformHint();
Ady Abraham85d692d2021-09-28 14:08:54 -07007190
7191 // Update the kernel timer for the current active display, since the policy
7192 // for this display might have changed when it was not the active display.
7193 toggleKernelIdleTimer();
Ady Abrahamed3290f2021-05-17 15:12:14 -07007194}
7195
chaviw60c9d3e2021-06-04 12:52:17 -05007196status_t SurfaceFlinger::addWindowInfosListener(
7197 const sp<IWindowInfosListener>& windowInfosListener) const {
7198 mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener);
7199 return NO_ERROR;
7200}
7201
7202status_t SurfaceFlinger::removeWindowInfosListener(
7203 const sp<IWindowInfosListener>& windowInfosListener) const {
7204 mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
7205 return NO_ERROR;
7206}
7207
Vishnu Nairdbbe3852022-01-12 20:22:11 -08007208std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
7209 const BufferData& bufferData, const char* layerName) const {
7210 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
7211 bool bufferSizeExceedsLimit = false;
7212 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
7213 if (cacheIdChanged && bufferData.buffer != nullptr) {
7214 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7215 bufferData.buffer->getHeight());
7216 if (!bufferSizeExceedsLimit) {
7217 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
7218 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7219 }
7220 } else if (cacheIdChanged) {
7221 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
7222 } else if (bufferData.buffer != nullptr) {
7223 bufferSizeExceedsLimit = exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
7224 bufferData.buffer->getHeight());
7225 if (!bufferSizeExceedsLimit) {
7226 buffer = std::make_shared<
7227 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
7228 renderengine::impl::ExternalTexture::
7229 Usage::READABLE);
7230 }
7231 }
7232 ALOGE_IF(bufferSizeExceedsLimit,
7233 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
7234 "limit.",
7235 layerName);
7236 return buffer;
7237}
Vishnu Nair0fc7af52022-01-13 08:11:34 -08007238
7239bool SurfaceFlinger::commitCreatedLayers() {
7240 std::vector<LayerCreatedState> createdLayers;
7241 {
7242 std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
7243 createdLayers = std::move(mCreatedLayers);
7244 mCreatedLayers.clear();
7245 if (createdLayers.size() == 0) {
7246 return false;
7247 }
7248 }
7249
7250 Mutex::Autolock _l(mStateLock);
7251 for (const auto& createdLayer : createdLayers) {
7252 handleLayerCreatedLocked(createdLayer);
7253 }
7254 createdLayers.clear();
7255 mLayersAdded = true;
7256 return true;
7257}
Huihong Luof5029222021-12-16 14:33:46 -08007258
7259// gui::ISurfaceComposer
Huihong Luo07e72362022-02-14 14:26:04 -08007260
7261binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
7262 sp<IBinder>* outDisplay) {
7263 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007264 if (status != OK) {
7265 return binder::Status::fromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007266 }
Huihong Luo37396db2022-02-15 10:43:00 -08007267 String8 displayName8 = String8::format("%s", displayName.c_str());
7268 *outDisplay = mFlinger->createDisplay(displayName8, secure);
7269 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007270}
7271
7272binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
7273 status_t status = checkAccessPermission();
Huihong Luo37396db2022-02-15 10:43:00 -08007274 if (status != OK) {
7275 return binder::Status::fromStatusT(status);
Huihong Luo07e72362022-02-14 14:26:04 -08007276 }
Huihong Luo37396db2022-02-15 10:43:00 -08007277 mFlinger->destroyDisplay(display);
7278 return binder::Status::ok();
Huihong Luo07e72362022-02-14 14:26:04 -08007279}
7280
7281binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
7282 std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
7283 std::vector<int64_t> displayIds;
7284 displayIds.reserve(physicalDisplayIds.size());
7285 for (auto item : physicalDisplayIds) {
7286 displayIds.push_back(static_cast<int64_t>(item.value));
7287 }
7288 *outDisplayIds = displayIds;
7289 return binder::Status::ok();
7290}
7291
7292binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) {
7293 status_t status = checkAccessPermission();
7294 if (status != OK) {
7295 return binder::Status::fromStatusT(status);
7296 }
7297
7298 PhysicalDisplayId id;
7299 status = mFlinger->getPrimaryPhysicalDisplayId(&id);
7300 if (status == NO_ERROR) {
7301 *outDisplayId = id.value;
7302 }
7303 return binder::Status::fromStatusT(status);
7304}
7305
7306binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
7307 sp<IBinder>* outDisplay) {
7308 const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
7309 *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
7310 return binder::Status::ok();
7311}
7312
Huihong Luo37396db2022-02-15 10:43:00 -08007313binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
7314 status_t status = checkAccessPermission();
7315 if (status != OK) {
7316 return binder::Status::fromStatusT(status);
7317 }
7318 mFlinger->setPowerMode(display, mode);
7319 return binder::Status::ok();
7320}
7321
Huihong Luo0a81aa32022-02-22 16:02:36 -08007322binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
7323 std::vector<FrameEvent>* outSupported) {
7324 status_t status;
7325 if (!outSupported) {
7326 status = UNEXPECTED_NULL;
7327 } else {
7328 outSupported->clear();
7329 status = mFlinger->getSupportedFrameTimestamps(outSupported);
7330 }
7331 return binder::Status::fromStatusT(status);
7332}
7333
Huihong Luoaa7fc2e2022-02-15 10:43:00 -08007334binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
7335 gui::DisplayStatInfo* outStatInfo) {
7336 DisplayStatInfo statInfo;
7337 status_t status = mFlinger->getDisplayStats(display, &statInfo);
7338 if (status == NO_ERROR) {
7339 outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
7340 outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
7341 }
7342 return binder::Status::fromStatusT(status);
7343}
7344
7345binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
7346 gui::DisplayState* outState) {
7347 ui::DisplayState state;
7348 status_t status = mFlinger->getDisplayState(display, &state);
7349 if (status == NO_ERROR) {
7350 outState->layerStack = state.layerStack.id;
7351 outState->orientation = static_cast<gui::Rotation>(state.orientation);
7352 outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
7353 outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
7354 }
7355 return binder::Status::fromStatusT(status);
7356}
7357
Huihong Luoa79ddf42022-02-17 00:01:38 -08007358binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp<IBinder>& display,
7359 gui::StaticDisplayInfo* outInfo) {
7360 using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
7361 ui::StaticDisplayInfo info;
7362 status_t status = mFlinger->getStaticDisplayInfo(display, &info);
7363 if (status == NO_ERROR) {
7364 // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
7365 outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
7366 outInfo->density = info.density;
7367 outInfo->secure = info.secure;
7368 outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
7369
7370 gui::DeviceProductInfo dinfo;
7371 std::optional<DeviceProductInfo> dpi = info.deviceProductInfo;
7372 dinfo.name = std::move(dpi->name);
7373 dinfo.manufacturerPnpId =
7374 std::vector<uint8_t>(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end());
7375 dinfo.productId = dpi->productId;
7376 if (const auto* model =
7377 std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
7378 gui::DeviceProductInfo::ModelYear modelYear;
7379 modelYear.year = model->year;
7380 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
7381 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
7382 &dpi->manufactureOrModelDate)) {
7383 gui::DeviceProductInfo::ManufactureYear date;
7384 date.modelYear.year = manufacture->year;
7385 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
7386 } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
7387 &dpi->manufactureOrModelDate)) {
7388 gui::DeviceProductInfo::ManufactureWeekAndYear date;
7389 date.manufactureYear.modelYear.year = manufacture->year;
7390 date.week = manufacture->week;
7391 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
7392 }
7393
7394 outInfo->deviceProductInfo = dinfo;
7395 }
7396 return binder::Status::fromStatusT(status);
7397}
7398
Huihong Luo38603fd2022-02-21 14:32:54 -08007399binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp<IBinder>& display,
7400 gui::DynamicDisplayInfo* outInfo) {
7401 ui::DynamicDisplayInfo info;
7402 status_t status = mFlinger->getDynamicDisplayInfo(display, &info);
7403 if (status == NO_ERROR) {
7404 // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
7405 outInfo->supportedDisplayModes.clear();
7406 outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
7407 for (const auto& mode : info.supportedDisplayModes) {
7408 gui::DisplayMode outMode;
7409 outMode.id = mode.id;
7410 outMode.resolution.width = mode.resolution.width;
7411 outMode.resolution.height = mode.resolution.height;
7412 outMode.xDpi = mode.xDpi;
7413 outMode.yDpi = mode.yDpi;
7414 outMode.refreshRate = mode.refreshRate;
7415 outMode.appVsyncOffset = mode.appVsyncOffset;
7416 outMode.sfVsyncOffset = mode.sfVsyncOffset;
7417 outMode.presentationDeadline = mode.presentationDeadline;
7418 outMode.group = mode.group;
7419 outInfo->supportedDisplayModes.push_back(outMode);
7420 }
7421
7422 outInfo->activeDisplayModeId = info.activeDisplayModeId;
7423
7424 outInfo->supportedColorModes.clear();
7425 outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
7426 for (const auto& cmode : info.supportedColorModes) {
7427 outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
7428 }
7429
7430 outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
7431
7432 gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
7433 hdrCapabilities.supportedHdrTypes.clear();
7434 hdrCapabilities.supportedHdrTypes.reserve(
7435 info.hdrCapabilities.getSupportedHdrTypes().size());
7436 for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
7437 hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
7438 }
7439 hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
7440 hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
7441 hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
7442
7443 outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
7444 outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
7445 outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
7446 }
7447 return binder::Status::fromStatusT(status);
7448}
7449
Huihong Luoca3d9a42022-02-22 11:07:34 -08007450binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
7451 gui::DisplayPrimaries* outPrimaries) {
7452 ui::DisplayPrimaries primaries;
7453 status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
7454 if (status == NO_ERROR) {
7455 outPrimaries->red.X = primaries.red.X;
7456 outPrimaries->red.Y = primaries.red.Y;
7457 outPrimaries->red.Z = primaries.red.Z;
7458
7459 outPrimaries->green.X = primaries.green.X;
7460 outPrimaries->green.Y = primaries.green.Y;
7461 outPrimaries->green.Z = primaries.green.Z;
7462
7463 outPrimaries->blue.X = primaries.blue.X;
7464 outPrimaries->blue.Y = primaries.blue.Y;
7465 outPrimaries->blue.Z = primaries.blue.Z;
7466
7467 outPrimaries->white.X = primaries.white.X;
7468 outPrimaries->white.Y = primaries.white.Y;
7469 outPrimaries->white.Z = primaries.white.Z;
7470 }
7471 return binder::Status::fromStatusT(status);
7472}
7473
7474binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
7475 status_t status = checkAccessPermission();
7476 if (status == OK) {
7477 status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
7478 }
7479 return binder::Status::fromStatusT(status);
7480}
7481
7482binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
7483 int displayModeId) {
7484 status_t status = checkAccessPermission();
7485 if (status == OK) {
7486 status = mFlinger->setBootDisplayMode(display,
7487 static_cast<ui::DisplayModeId>(displayModeId));
7488 }
7489 return binder::Status::fromStatusT(status);
7490}
7491
Huihong Luo37396db2022-02-15 10:43:00 -08007492binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
7493 status_t status = checkAccessPermission();
7494 if (status == OK) {
7495 status = mFlinger->clearBootDisplayMode(display);
7496 }
7497 return binder::Status::fromStatusT(status);
7498}
7499
7500binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
7501 status_t status = checkAccessPermission();
7502 if (status == OK) {
7503 status = mFlinger->getBootDisplayModeSupport(outMode);
7504 }
7505 return binder::Status::fromStatusT(status);
7506}
7507
7508binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
7509 status_t status = checkAccessPermission();
7510 if (status != OK) {
7511 return binder::Status::fromStatusT(status);
7512 }
7513 mFlinger->setAutoLowLatencyMode(display, on);
7514 return binder::Status::ok();
7515}
7516
7517binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
7518 status_t status = checkAccessPermission();
7519 if (status != OK) {
7520 return binder::Status::fromStatusT(status);
7521 }
7522 mFlinger->setGameContentType(display, on);
7523 return binder::Status::ok();
7524}
7525
Huihong Luof5029222021-12-16 14:33:46 -08007526binder::Status SurfaceComposerAIDL::captureDisplay(
7527 const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7528 status_t status = mFlinger->captureDisplay(args, captureListener);
7529 return binder::Status::fromStatusT(status);
7530}
7531
7532binder::Status SurfaceComposerAIDL::captureDisplayById(
7533 int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
7534 status_t status;
7535 IPCThreadState* ipc = IPCThreadState::self();
7536 const int uid = ipc->getCallingUid();
7537 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7538 std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
7539 status = mFlinger->captureDisplay(*id, captureListener);
7540 } else {
7541 status = PERMISSION_DENIED;
7542 }
7543 return binder::Status::fromStatusT(status);
7544}
7545
7546binder::Status SurfaceComposerAIDL::captureLayers(
7547 const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
7548 status_t status = mFlinger->captureLayers(args, captureListener);
7549 return binder::Status::fromStatusT(status);
7550}
7551
Huihong Luo4ed1c912022-02-22 14:30:01 -08007552binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() {
7553 status_t status = checkAccessPermission();
7554 if (status == OK) {
7555 status = mFlinger->clearAnimationFrameStats();
7556 }
7557 return binder::Status::fromStatusT(status);
7558}
7559
7560binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) {
7561 status_t status = checkAccessPermission();
7562 if (status != OK) {
7563 return binder::Status::fromStatusT(status);
7564 }
7565
7566 FrameStats stats;
7567 status = mFlinger->getAnimationFrameStats(&stats);
7568 if (status == NO_ERROR) {
7569 outStats->refreshPeriodNano = stats.refreshPeriodNano;
7570 outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size());
7571 for (const auto& t : stats.desiredPresentTimesNano) {
7572 outStats->desiredPresentTimesNano.push_back(t);
7573 }
7574 outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size());
7575 for (const auto& t : stats.actualPresentTimesNano) {
7576 outStats->actualPresentTimesNano.push_back(t);
7577 }
7578 outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size());
7579 for (const auto& t : stats.frameReadyTimesNano) {
7580 outStats->frameReadyTimesNano.push_back(t);
7581 }
7582 }
7583 return binder::Status::fromStatusT(status);
7584}
7585
Huihong Luo05539a12022-02-23 10:29:40 -08007586binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
7587 const std::vector<int32_t>& hdrTypes) {
7588 // overrideHdrTypes is used by CTS tests, which acquire the necessary
7589 // permission dynamically. Don't use the permission cache for this check.
7590 status_t status = checkAccessPermission(false);
7591 if (status != OK) {
7592 return binder::Status::fromStatusT(status);
7593 }
7594
7595 std::vector<ui::Hdr> hdrTypesVector;
7596 for (int32_t i : hdrTypes) {
7597 hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
7598 }
7599 status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
7600 return binder::Status::fromStatusT(status);
7601}
7602
7603binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
7604 status_t status;
7605 const int uid = IPCThreadState::self()->getCallingUid();
7606 if (uid != AID_SYSTEM) {
7607 status = PERMISSION_DENIED;
7608 } else {
7609 status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
7610 }
7611 return binder::Status::fromStatusT(status);
7612}
7613
7614binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) {
7615 if (!mFlinger->hasMockHwc()) {
7616 return binder::Status::fromStatusT(PERMISSION_DENIED);
7617 }
7618
7619 status_t status = checkAccessPermission();
7620 if (status == OK) {
7621 status = mFlinger->enableVSyncInjections(enable);
7622 }
7623 return binder::Status::fromStatusT(status);
7624}
7625
7626binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) {
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->injectVSync(when);
7634 }
7635 return binder::Status::fromStatusT(status);
7636}
7637
7638binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
7639 if (!outLayers) {
7640 return binder::Status::fromStatusT(UNEXPECTED_NULL);
7641 }
7642
7643 IPCThreadState* ipc = IPCThreadState::self();
7644 const int pid = ipc->getCallingPid();
7645 const int uid = ipc->getCallingUid();
7646 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
7647 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
7648 return binder::Status::fromStatusT(PERMISSION_DENIED);
7649 }
7650 status_t status = mFlinger->getLayerDebugInfo(outLayers);
7651 return binder::Status::fromStatusT(status);
7652}
7653
7654binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
7655 status_t status = mFlinger->getColorManagement(outGetColorManagement);
7656 return binder::Status::fromStatusT(status);
7657}
7658
7659binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
7660 ui::Dataspace dataspace;
7661 ui::PixelFormat pixelFormat;
7662 ui::Dataspace wideColorGamutDataspace;
7663 ui::PixelFormat wideColorGamutPixelFormat;
7664 status_t status =
7665 mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
7666 &wideColorGamutPixelFormat);
7667 if (status == NO_ERROR) {
7668 outPref->defaultDataspace = static_cast<int32_t>(dataspace);
7669 outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
7670 outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
7671 outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
7672 }
7673 return binder::Status::fromStatusT(status);
7674}
7675
7676binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
7677 const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
7678 status_t status = checkAccessPermission();
7679 if (status != OK) {
7680 return binder::Status::fromStatusT(status);
7681 }
7682
7683 ui::PixelFormat format;
7684 ui::Dataspace dataspace;
7685 uint8_t componentMask;
7686 status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
7687 &componentMask);
7688 if (status == NO_ERROR) {
7689 outAttrs->format = static_cast<int32_t>(format);
7690 outAttrs->dataspace = static_cast<int32_t>(dataspace);
7691 outAttrs->componentMask = static_cast<int8_t>(componentMask);
7692 }
7693 return binder::Status::fromStatusT(status);
7694}
7695
7696binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
7697 bool enable,
7698 int8_t componentMask,
7699 int64_t maxFrames) {
7700 status_t status = checkAccessPermission();
7701 if (status == OK) {
7702 status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
7703 static_cast<uint8_t>(componentMask),
7704 static_cast<uint64_t>(maxFrames));
7705 }
7706 return binder::Status::fromStatusT(status);
7707}
7708
7709binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
7710 status_t status = mFlinger->getProtectedContentSupport(outSupported);
7711 return binder::Status::fromStatusT(status);
7712}
7713
Huihong Luo37396db2022-02-15 10:43:00 -08007714binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
7715 bool* outIsWideColorDisplay) {
7716 status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
7717 return binder::Status::fromStatusT(status);
7718}
7719
Huihong Luo02186fb2022-02-23 14:21:54 -08007720binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
7721 const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
7722 const sp<gui::IRegionSamplingListener>& listener) {
7723 status_t status = checkReadFrameBufferPermission();
7724 if (status != OK) {
7725 return binder::Status::fromStatusT(status);
7726 }
7727 android::Rect rect;
7728 rect.left = samplingArea.left;
7729 rect.top = samplingArea.top;
7730 rect.right = samplingArea.right;
7731 rect.bottom = samplingArea.bottom;
7732 status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
7733 return binder::Status::fromStatusT(status);
7734}
7735
7736binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
7737 const sp<gui::IRegionSamplingListener>& listener) {
7738 status_t status = checkReadFrameBufferPermission();
7739 if (status == OK) {
7740 status = mFlinger->removeRegionSamplingListener(listener);
7741 }
7742 return binder::Status::fromStatusT(status);
7743}
7744
7745binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
7746 const sp<gui::IFpsListener>& listener) {
7747 status_t status = checkReadFrameBufferPermission();
7748 if (status == OK) {
7749 status = mFlinger->addFpsListener(taskId, listener);
7750 }
7751 return binder::Status::fromStatusT(status);
7752}
7753
7754binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
7755 status_t status = checkReadFrameBufferPermission();
7756 if (status == OK) {
7757 status = mFlinger->removeFpsListener(listener);
7758 }
7759 return binder::Status::fromStatusT(status);
7760}
7761
7762binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
7763 const sp<gui::ITunnelModeEnabledListener>& listener) {
7764 status_t status = checkAccessPermission();
7765 if (status == OK) {
7766 status = mFlinger->addTunnelModeEnabledListener(listener);
7767 }
7768 return binder::Status::fromStatusT(status);
7769}
7770
7771binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
7772 const sp<gui::ITunnelModeEnabledListener>& listener) {
7773 status_t status = checkAccessPermission();
7774 if (status == OK) {
7775 status = mFlinger->removeTunnelModeEnabledListener(listener);
7776 }
7777 return binder::Status::fromStatusT(status);
7778}
7779
7780binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(
7781 const sp<IBinder>& displayToken, int32_t defaultMode, bool allowGroupSwitching,
7782 float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
7783 float appRequestRefreshRateMax) {
7784 status_t status = checkAccessPermission();
7785 if (status == OK) {
7786 status = mFlinger->setDesiredDisplayModeSpecs(displayToken,
7787 static_cast<ui::DisplayModeId>(defaultMode),
7788 allowGroupSwitching, primaryRefreshRateMin,
7789 primaryRefreshRateMax,
7790 appRequestRefreshRateMin,
7791 appRequestRefreshRateMax);
7792 }
7793 return binder::Status::fromStatusT(status);
7794}
7795
7796binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7797 gui::DisplayModeSpecs* outSpecs) {
7798 if (!outSpecs) {
7799 return binder::Status::fromStatusT(BAD_VALUE);
7800 }
7801
7802 status_t status = checkAccessPermission();
7803 if (status != OK) {
7804 return binder::Status::fromStatusT(status);
7805 }
7806
7807 ui::DisplayModeId displayModeId;
7808 bool allowGroupSwitching;
7809 float primaryRefreshRateMin;
7810 float primaryRefreshRateMax;
7811 float appRequestRefreshRateMin;
7812 float appRequestRefreshRateMax;
7813 status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId,
7814 &allowGroupSwitching, &primaryRefreshRateMin,
7815 &primaryRefreshRateMax, &appRequestRefreshRateMin,
7816 &appRequestRefreshRateMax);
7817 if (status == NO_ERROR) {
7818 outSpecs->defaultMode = displayModeId;
7819 outSpecs->allowGroupSwitching = allowGroupSwitching;
7820 outSpecs->primaryRefreshRateMin = primaryRefreshRateMin;
7821 outSpecs->primaryRefreshRateMax = primaryRefreshRateMax;
7822 outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin;
7823 outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax;
7824 }
7825
7826 return binder::Status::fromStatusT(status);
7827}
7828
Huihong Luo37396db2022-02-15 10:43:00 -08007829binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
7830 bool* outSupport) {
7831 status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
7832 return binder::Status::fromStatusT(status);
7833}
7834
7835binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
7836 const gui::DisplayBrightness& brightness) {
7837 status_t status = checkControlDisplayBrightnessPermission();
7838 if (status == OK) {
7839 status = mFlinger->setDisplayBrightness(displayToken, brightness);
7840 }
7841 return binder::Status::fromStatusT(status);
7842}
7843
7844binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
7845 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7846 status_t status = checkControlDisplayBrightnessPermission();
7847 if (status == OK) {
7848 status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
7849 }
7850 return binder::Status::fromStatusT(status);
7851}
7852
7853binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
7854 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
7855 status_t status = checkControlDisplayBrightnessPermission();
7856 if (status == OK) {
7857 status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
7858 }
7859 return binder::Status::fromStatusT(status);
7860}
7861
7862binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
7863 status_t status = checkAccessPermission();
7864 if (status == OK) {
7865 status = mFlinger->notifyPowerBoost(boostId);
7866 }
7867 return binder::Status::fromStatusT(status);
7868}
7869
Huihong Luo02186fb2022-02-23 14:21:54 -08007870binder::Status SurfaceComposerAIDL::addTransactionTraceListener(
7871 const sp<gui::ITransactionTraceListener>& listener) {
7872 status_t status;
7873 IPCThreadState* ipc = IPCThreadState::self();
7874 const int uid = ipc->getCallingUid();
7875 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
7876 status = mFlinger->addTransactionTraceListener(listener);
7877 } else {
7878 status = PERMISSION_DENIED;
7879 }
7880 return binder::Status::fromStatusT(status);
7881}
7882
7883binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
7884 *outPriority = mFlinger->getGpuContextPriority();
7885 return binder::Status::ok();
7886}
7887
7888binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
7889 status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
7890 return binder::Status::fromStatusT(status);
7891}
7892
7893binder::Status SurfaceComposerAIDL::addWindowInfosListener(
7894 const sp<gui::IWindowInfosListener>& windowInfosListener) {
7895 status_t status;
7896 const int uid = IPCThreadState::self()->getCallingUid();
7897 if (uid == AID_SYSTEM || uid == AID_GRAPHICS) {
7898 status = mFlinger->addWindowInfosListener(windowInfosListener);
7899 } else {
7900 status = PERMISSION_DENIED;
7901 }
7902 return binder::Status::fromStatusT(status);
7903}
7904
7905binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
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->removeWindowInfosListener(windowInfosListener);
7911 } else {
7912 status = PERMISSION_DENIED;
7913 }
7914 return binder::Status::fromStatusT(status);
7915}
7916
Huihong Luo07e72362022-02-14 14:26:04 -08007917status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
7918 if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
7919 IPCThreadState* ipc = IPCThreadState::self();
7920 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
7921 ipc->getCallingUid());
7922 return PERMISSION_DENIED;
7923 }
7924 return OK;
7925}
7926
Huihong Luo37396db2022-02-15 10:43:00 -08007927status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
7928 IPCThreadState* ipc = IPCThreadState::self();
7929 const int pid = ipc->getCallingPid();
7930 const int uid = ipc->getCallingUid();
7931 if ((uid != AID_GRAPHICS) &&
7932 !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
7933 ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
7934 return PERMISSION_DENIED;
7935 }
7936 return OK;
7937}
7938
Huihong Luo02186fb2022-02-23 14:21:54 -08007939status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
7940 IPCThreadState* ipc = IPCThreadState::self();
7941 const int pid = ipc->getCallingPid();
7942 const int uid = ipc->getCallingUid();
7943 if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
7944 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
7945 return PERMISSION_DENIED;
7946 }
7947 return OK;
7948}
7949
Dominik Laskowski9dab3432019-03-27 13:21:10 -07007950} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07007951
Mathias Agopian3f844832013-08-07 21:24:32 -07007952#if defined(__gl_h_)
7953#error "don't include gl/gl.h in this file"
7954#endif
7955
7956#if defined(__gl2_h_)
7957#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08007958#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08007959
7960// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01007961#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"