blob: 4a71295c34ca2385159139123fb2ffdfc95149a9 [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"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri989ddbe2020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri989ddbe2020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Peiyong Line9d809e2020-04-14 13:10:48 -0700143namespace hal = android::hardware::graphics::composer::hal;
144
Steven Thomasb02664d2017-07-26 18:48:28 -0700145namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700146
147#pragma clang diagnostic push
148#pragma clang diagnostic error "-Wswitch-enum"
149
150bool isWideColorMode(const ColorMode colorMode) {
151 switch (colorMode) {
152 case ColorMode::DISPLAY_P3:
153 case ColorMode::ADOBE_RGB:
154 case ColorMode::DCI_P3:
155 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700156 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700157 case ColorMode::BT2100_PQ:
158 case ColorMode::BT2100_HLG:
159 return true;
160 case ColorMode::NATIVE:
161 case ColorMode::STANDARD_BT601_625:
162 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
163 case ColorMode::STANDARD_BT601_525:
164 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
165 case ColorMode::STANDARD_BT709:
166 case ColorMode::SRGB:
167 return false;
168 }
169 return false;
170}
171
172#pragma clang diagnostic pop
173
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700174template <typename Mutex>
175struct ConditionalLockGuard {
176 ConditionalLockGuard(Mutex& mutex, bool lock) : mutex(mutex), lock(lock) {
177 if (lock) mutex.lock();
Steven Thomasb02664d2017-07-26 18:48:28 -0700178 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700179
180 ~ConditionalLockGuard() {
181 if (lock) mutex.unlock();
182 }
183
184 Mutex& mutex;
185 const bool lock;
Steven Thomasb02664d2017-07-26 18:48:28 -0700186};
Peiyong Linfca547f2018-07-09 13:03:33 -0700187
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700188using ConditionalLock = ConditionalLockGuard<Mutex>;
189
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800190// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
191constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
192
193float getDensityFromProperty(const char* property, bool required) {
194 char value[PROPERTY_VALUE_MAX];
195 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
196 if (!density && required) {
197 ALOGE("%s must be defined as a build property", property);
198 return FALLBACK_DENSITY;
199 }
200 return density / 160.f;
201}
202
Peiyong Lin9d846a52018-11-05 13:18:20 -0800203// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
204bool validateCompositionDataspace(Dataspace dataspace) {
205 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
206}
207
Steven Thomasd4071902020-03-24 16:02:53 -0700208class FrameRateFlexibilityToken : public BBinder {
209public:
210 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
211 virtual ~FrameRateFlexibilityToken() { mCallback(); }
212
213private:
214 std::function<void()> mCallback;
215};
216
Steven Thomasb02664d2017-07-26 18:48:28 -0700217} // namespace anonymous
218
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219// ---------------------------------------------------------------------------
220
Mathias Agopian99b49842011-06-27 16:05:52 -0700221const String16 sHardwareTest("android.permission.HARDWARE_TEST");
222const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
223const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
224const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800225const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700226
227// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700228int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700229bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800230uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800231bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800232bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800233int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100234uint32_t SurfaceFlinger::maxGraphicsWidth;
235uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600236bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800237ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700238bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700239bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700240Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
241ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
242Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
243ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800244bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700245
Kalle Raitaa099a242017-01-11 11:17:29 -0800246std::string getHwcServiceName() {
247 char value[PROPERTY_VALUE_MAX] = {};
248 property_get("debug.sf.hwc_service_name", value, "default");
249 ALOGI("Using HWComposer service: '%s'", value);
250 return std::string(value);
251}
252
253bool useTrebleTestingOverride() {
254 char value[PROPERTY_VALUE_MAX] = {};
255 property_get("debug.sf.treble_testing_override", value, "false");
256 ALOGI("Treble testing override: '%s'", value);
257 return std::string(value) == "true";
258}
259
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800260std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
261 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800262 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700263 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800264 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700265 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800266 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700267 return std::string("Enhanced");
268 default:
269 return std::string("Unknown ") +
270 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800271 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800272}
273
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700274SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800275
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700276SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
277 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700278 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700279 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700280 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700281 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700282 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800283 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
284 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800285
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700286SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800287 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800288
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800296
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800301
Brian Lindahla13f2d52020-03-05 11:54:17 +0100302 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
303 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
304
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700306
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 mDefaultCompositionDataspace =
310 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700311 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
312 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900313 defaultCompositionDataspace = mDefaultCompositionDataspace;
314 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
315 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
316 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
317 wideColorGamutCompositionPixelFormat =
318 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700319
Yichi Chenda901bf2019-06-28 14:58:27 +0800320 mColorSpaceAgnosticDataspace =
321 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800324
Dominik Laskowski718f9602019-11-09 20:01:35 -0800325 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
326 switch (primary_display_orientation(Values::ORIENTATION_0)) {
327 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800329 case Values::ORIENTATION_90:
330 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800332 case Values::ORIENTATION_180:
333 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800335 case Values::ORIENTATION_270:
336 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800339 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800340
Sundong Ahn85131bd2019-02-18 15:51:53 +0900341 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800342
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343 // debugging stuff...
344 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700345
Mathias Agopianb4b17302013-03-20 18:36:41 -0700346 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700347 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700348
Alec Mouri989ddbe2020-02-06 09:26:19 -0800349 property_get("ro.build.type", value, "user");
350 mIsUserBuild = strcmp(value, "user") == 0;
351
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352 property_get("debug.sf.showupdates", value, "0");
353 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700355 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000356
357 // DDMS debugging deprecated (b/120782499)
358 property_get("debug.sf.ddms", value, "0");
359 int debugDdms = atoi(value);
360 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700361
362 property_get("debug.sf.disable_backpressure", value, "0");
363 mPropagateBackpressure = !atoi(value);
364 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700365
Ady Abrahamadb9a992019-09-19 21:21:55 +0000366 property_get("debug.sf.enable_gl_backpressure", value, "0");
367 mPropagateBackpressureClientComposition = atoi(value);
368 ALOGI_IF(mPropagateBackpressureClientComposition,
369 "Enabling backpressure propagation for Client Composition");
370
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800371 property_get("debug.sf.enable_hwc_vds", value, "0");
372 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800373 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800374
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800375 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800376 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800377 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700378
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800379 property_get("ro.surface_flinger.supports_background_blur", value, "0");
380 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700381 mSupportsBlur = supportsBlurs;
382 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800383 property_get("ro.sf.blurs_are_expensive", value, "0");
384 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800385
Ady Abraham0a525092020-03-03 12:51:24 -0800386 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700387 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
388 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
389
Dan Stozaec460082018-12-17 15:35:09 -0800390 property_get("debug.sf.luma_sampling", value, "1");
391 mLumaSampling = atoi(value);
392
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800393 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800394 mDisableClientCompositionCache = atoi(value);
395
Romain Guy11d63f42017-07-20 12:47:14 -0700396 // We should be reading 'persist.sys.sf.color_saturation' here
397 // but since /data may be encrypted, we need to wait until after vold
398 // comes online to attempt to read the property. The property is
399 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800400
401 if (useTrebleTestingOverride()) {
402 // Without the override SurfaceFlinger cannot connect to HIDL
403 // services that are not listed in the manifests. Considered
404 // deriving the setting from the set service name, but it
405 // would be brittle if the name that's not 'default' is used
406 // for production purposes later on.
407 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
408 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800409
410 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411}
412
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413void SurfaceFlinger::onFirstRef()
414{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800415 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416}
417
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700418SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419
Dan Stozac7014012014-02-14 15:03:43 -0800420void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421{
422 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700423 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424
Andy McFadden13a082e2012-08-24 10:16:42 -0700425 // restore initial conditions (default device unblank, etc)
426 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427
428 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700429 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430}
431
Robert Carr1db73f62016-12-21 12:58:51 -0800432static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700433 status_t err = client->initCheck();
434 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800435 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800436 }
Robert Carr1db73f62016-12-21 12:58:51 -0800437 return nullptr;
438}
439
440sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
441 return initClient(new Client(this));
442}
443
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700444sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
445 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700446{
447 class DisplayToken : public BBinder {
448 sp<SurfaceFlinger> flinger;
449 virtual ~DisplayToken() {
450 // no more references, this display must be terminated
451 Mutex::Autolock _l(flinger->mStateLock);
452 flinger->mCurrentState.displays.removeItem(this);
453 flinger->setTransactionFlags(eDisplayTransactionNeeded);
454 }
455 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700456 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457 : flinger(flinger) {
458 }
459 };
460
461 sp<BBinder> token = new DisplayToken(this);
462
463 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700464 // Display ID is assigned when virtual display is allocated by HWC.
465 DisplayDeviceState state;
466 state.isSecure = secure;
467 state.displayName = displayName;
468 mCurrentState.displays.add(token, state);
469 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470 return token;
471}
472
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700473void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700474 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700475
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700476 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700478 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 return;
480 }
481
Dominik Laskowski075d3172018-05-24 15:50:06 -0700482 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700483 if (state.physical) {
484 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 return;
486 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 mInterceptor->saveDisplayDeletion(state.sequenceId);
488 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 setTransactionFlags(eDisplayTransactionNeeded);
490}
491
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800492std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
493 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800495 const auto internalDisplayId = getInternalDisplayIdLocked();
496 if (!internalDisplayId) {
497 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498 }
499
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800500 std::vector<PhysicalDisplayId> displayIds;
501 displayIds.reserve(mPhysicalDisplayTokens.size());
502 displayIds.push_back(internalDisplayId->value);
503
504 for (const auto& [id, token] : mPhysicalDisplayTokens) {
505 if (id != *internalDisplayId) {
506 displayIds.push_back(id.value);
507 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700509
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800510 return displayIds;
511}
512
513sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
514 Mutex::Autolock lock(mStateLock);
515 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516}
517
Ady Abraham37965d42018-11-01 13:43:32 -0700518status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
519 if (!outGetColorManagement) {
520 return BAD_VALUE;
521 }
522 *outGetColorManagement = useColorManagement;
523 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700524}
525
Lloyd Pique441d5042018-10-18 16:49:51 -0700526HWComposer& SurfaceFlinger::getHwComposer() const {
527 return mCompositionEngine->getHwComposer();
528}
529
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700530renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
531 return mCompositionEngine->getRenderEngine();
532}
533
Lloyd Pique70d91362018-10-18 16:02:55 -0700534compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
535 return *mCompositionEngine.get();
536}
537
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538void SurfaceFlinger::bootFinished()
539{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700540 if (mBootFinished == true) {
541 ALOGE("Extra call to bootFinished");
542 return;
543 }
544 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700545 if (mStartPropertySetThread->join() != NO_ERROR) {
546 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800547 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548 const nsecs_t now = systemTime();
549 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000550 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551
Mikael Pessa90092f42019-08-26 17:22:04 -0700552 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000553 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700554
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 // wait patiently for the window manager death
556 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700557 mWindowManager = defaultServiceManager()->getService(name);
558 if (mWindowManager != 0) {
559 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700560 }
Robert Carr720e5062018-07-30 17:45:14 -0700561 sp<IBinder> input(defaultServiceManager()->getService(
562 String16("inputflinger")));
563 if (input == nullptr) {
564 ALOGE("Failed to link to input service");
565 } else {
566 mInputFlinger = interface_cast<IInputFlinger>(input);
567 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700568
Steven Thomas050b2c82017-03-06 11:45:16 -0800569 if (mVrFlinger) {
570 mVrFlinger->OnBootFinished();
571 }
572
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700573 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700574 // formerly we would just kill the process, but we now ask it to exit so it
575 // can choose where to stop the animation.
576 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700577
578 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
579 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
580 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700581
Ana Krulecbd6654b2019-02-15 15:18:15 -0800582 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800583 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700584 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800585 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800586
Ady Abraham8a82ba62020-01-17 12:43:17 -0800587 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
588 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
589 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
590 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800591 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800592}
593
Dan Stoza436ccf32018-06-21 12:10:12 -0700594uint32_t SurfaceFlinger::getNewTexture() {
595 {
596 std::lock_guard lock(mTexturePoolMutex);
597 if (!mTexturePool.empty()) {
598 uint32_t name = mTexturePool.back();
599 mTexturePool.pop_back();
600 ATRACE_INT("TexturePoolSize", mTexturePool.size());
601 return name;
602 }
603
604 // The pool was too small, so increase it for the future
605 ++mTexturePoolSize;
606 }
607
608 // The pool was empty, so we need to get a new texture name directly using a
609 // blocking call to the main thread
610 uint32_t name = 0;
611 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
612 return name;
613}
614
Mathias Agopian3f844832013-08-07 21:24:32 -0700615void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700616 std::lock_guard lock(mTexturePoolMutex);
617 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
618 // to actually delete this or not based on mTexturePoolSize
619 mTexturePool.push_back(texture);
620 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700621}
622
Wei Wangf9b05ee2017-07-19 20:59:39 -0700623// Do not call property_set on main thread which will be blocked by init
624// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700625void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700626 ALOGI( "SurfaceFlinger's main thread ready to run. "
627 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700628 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800629
Steven Thomasb02664d2017-07-26 18:48:28 -0700630 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700631 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800632 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700633 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
634 renderengine::RenderEngineCreationArgs::Builder()
635 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
636 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
637 .setUseColorManagerment(useColorManagement)
638 .setEnableProtectedContext(enable_protected_contents(false))
639 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700640 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700641 .setContextPriority(useContextPriority
642 ? renderengine::RenderEngine::ContextPriority::HIGH
643 : renderengine::RenderEngine::ContextPriority::MEDIUM)
644 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800645 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700646
647 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
648 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700649 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800650 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800651 // Process any initial hotplug and resulting display changes.
652 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700653 const auto display = getDefaultDisplayDeviceLocked();
654 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700655 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700656 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800657
Steven Thomas050b2c82017-03-06 11:45:16 -0800658 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700659 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700660 // This callback is called from the vr flinger dispatch thread. We
661 // need to call signalTransaction(), which requires holding
662 // mStateLock when we're not on the main thread. Acquiring
663 // mStateLock from the vr flinger dispatch thread might trigger a
664 // deadlock in surface flinger (see b/66916578), so post a message
665 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700666 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700667 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
668 mVrFlingerRequestsDisplay = requestDisplay;
669 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700670 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800671 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700672 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
673 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700674 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700675 .value_or(0),
676 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800677 if (!mVrFlinger) {
678 ALOGE("Failed to start vrflinger");
679 }
680 }
681
Mathias Agopian92a979a2012-08-02 18:32:23 -0700682 // initialize our drawing state
683 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700684
Andy McFadden13a082e2012-08-24 10:16:42 -0700685 // set initial conditions (e.g. unblank default device)
686 initializeDisplays();
687
Steven Thomas137d4bc2019-07-25 16:55:14 -0700688 char primeShaderCache[PROPERTY_VALUE_MAX];
689 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
690 if (atoi(primeShaderCache)) {
691 getRenderEngine().primeCache();
692 }
Dan Stoza4e637772016-07-28 13:31:51 -0700693
Wei Wangf9b05ee2017-07-19 20:59:39 -0700694 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700695
696 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700697 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700698 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700699
700 if (mStartPropertySetThread->Start() != NO_ERROR) {
701 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800702 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703
Dan Stoza9e56aa02015-11-02 13:00:03 -0800704 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700705}
706
Romain Guy11d63f42017-07-20 12:47:14 -0700707void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700708 Mutex::Autolock _l(mStateLock);
709
Romain Guy11d63f42017-07-20 12:47:14 -0700710 char value[PROPERTY_VALUE_MAX];
711
712 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800713 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700714 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800715 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100716
717 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700718 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800719
720 property_get("persist.sys.sf.color_mode", value, "0");
721 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700722
723 property_get("persist.sys.sf.disable_blurs", value, "0");
724 bool disableBlurs = atoi(value);
725 mDisableBlurs = disableBlurs;
726 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700727}
728
Mathias Agopiana67e4182012-06-19 17:26:12 -0700729void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800730 // Start boot animation service by setting a property mailbox
731 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700732 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800733 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700734 if (mStartPropertySetThread->join() != NO_ERROR) {
735 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800736 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700737}
738
Mathias Agopian875d8e12013-06-07 15:35:48 -0700739size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700740 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700741}
742
Mathias Agopian875d8e12013-06-07 15:35:48 -0700743size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700744 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700745}
746
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800747// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800748
Jamie Gennis582270d2011-08-17 18:19:00 -0700749bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800750 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800751 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800752 return authenticateSurfaceTextureLocked(bufferProducer);
753}
754
755bool SurfaceFlinger::authenticateSurfaceTextureLocked(
756 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800757 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800758 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800759}
760
Brian Anderson6b376712017-04-04 10:51:39 -0700761status_t SurfaceFlinger::getSupportedFrameTimestamps(
762 std::vector<FrameEvent>* outSupported) const {
763 *outSupported = {
764 FrameEvent::REQUESTED_PRESENT,
765 FrameEvent::ACQUIRE,
766 FrameEvent::LATCH,
767 FrameEvent::FIRST_REFRESH_START,
768 FrameEvent::LAST_REFRESH_START,
769 FrameEvent::GPU_COMPOSITION_DONE,
770 FrameEvent::DEQUEUE_READY,
771 FrameEvent::RELEASE,
772 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700773 ConditionalLock _l(mStateLock,
774 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700775 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700776 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
777 }
778 return NO_ERROR;
779}
780
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800781status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
782 if (!displayToken || !state) {
783 return BAD_VALUE;
784 }
785
786 Mutex::Autolock lock(mStateLock);
787
788 const auto display = getDisplayDeviceLocked(displayToken);
789 if (!display) {
790 return NAME_NOT_FOUND;
791 }
792
793 state->layerStack = display->getLayerStack();
794 state->orientation = display->getOrientation();
795
796 const Rect viewport = display->getViewport();
797 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
798
799 return NO_ERROR;
800}
801
802status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
803 if (!displayToken || !info) {
804 return BAD_VALUE;
805 }
806
807 Mutex::Autolock lock(mStateLock);
808
809 const auto display = getDisplayDeviceLocked(displayToken);
810 if (!display) {
811 return NAME_NOT_FOUND;
812 }
813
Dominik Laskowski55c85402020-01-21 16:25:47 -0800814 if (const auto connectionType = display->getConnectionType())
815 info->connectionType = *connectionType;
816 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800817 return INVALID_OPERATION;
818 }
819
820 if (mEmulatedDisplayDensity) {
821 info->density = mEmulatedDisplayDensity;
822 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800823 info->density = info->connectionType == DisplayConnectionType::Internal
824 ? mInternalDisplayDensity
825 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800826 }
827
828 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200829 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800830
831 return NO_ERROR;
832}
833
Dominik Laskowski22488f62019-03-28 09:53:04 -0700834status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800835 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700836 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 return BAD_VALUE;
838 }
839
Dominik Laskowski22488f62019-03-28 09:53:04 -0700840 Mutex::Autolock lock(mStateLock);
841
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800842 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700843 if (!displayId) {
844 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700845 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800847 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700848
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700850
Dominik Laskowski075d3172018-05-24 15:50:06 -0700851 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800852 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700853
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800854 auto width = hwConfig->getWidth();
855 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700856
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800857 auto xDpi = hwConfig->getDpiX();
858 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700859
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800860 if (isInternal &&
861 (internalDisplayOrientation == ui::ROTATION_90 ||
862 internalDisplayOrientation == ui::ROTATION_270)) {
863 std::swap(width, height);
864 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 }
866
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800867 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800868
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800869 if (mEmulatedDisplayDensity) {
870 config.xDpi = mEmulatedDisplayDensity;
871 config.yDpi = mEmulatedDisplayDensity;
872 } else {
873 config.xDpi = xDpi;
874 config.yDpi = yDpi;
875 }
876
877 const nsecs_t period = hwConfig->getVsyncPeriod();
878 config.refreshRate = 1e9f / period;
879
880 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
881 config.appVsyncOffset = offsets.late.app;
882 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800883 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884
Andy McFadden91b2ca82014-06-13 14:04:23 -0700885 // This is how far in advance a buffer must be queued for
886 // presentation at a given time. If you want a buffer to appear
887 // on the screen at time N, you must submit the buffer before
888 // (N - presentationDeadline).
889 //
890 // Normally it's one full refresh period (to give SF a chance to
891 // latch the buffer), but this can be reduced by configuring a
892 // DispSync offset. Any additional delays introduced by the hardware
893 // composer or panel must be accounted for here.
894 //
895 // We add an additional 1ms to allow for processing time and
896 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800897 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700898
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800899 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700900 }
901
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 return NO_ERROR;
903}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700904
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700905status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
906 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700907 return BAD_VALUE;
908 }
909
Ana Krulecc2870422019-01-29 19:00:58 -0800910 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700911 return NO_ERROR;
912}
913
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700915 int activeConfig;
916 bool isPrimary;
917
918 {
919 Mutex::Autolock lock(mStateLock);
920
921 if (const auto display = getDisplayDeviceLocked(displayToken)) {
922 activeConfig = display->getActiveConfig().value();
923 isPrimary = display->isPrimary();
924 } else {
925 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
926 return NAME_NOT_FOUND;
927 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800928 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700929
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700930 if (isPrimary) {
Steven Thomasc9098452019-09-30 17:15:05 -0700931 std::lock_guard<std::mutex> lock(mActiveConfigLock);
932 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800933 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700934 }
Steven Thomasc9098452019-09-30 17:15:05 -0700935 }
Ady Abraham2139f732019-11-13 18:56:40 -0800936
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700937 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700938}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700939
Ady Abraham03b02dd2019-03-21 15:40:11 -0700940void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800941 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800942 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700943 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800944
Ady Abrahamb838aed2019-02-12 15:30:16 -0800945 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800946 if (mDesiredActiveConfigChanged) {
947 // If a config change is pending, just cache the latest request in
948 // mDesiredActiveConfig
949 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
950 mDesiredActiveConfig = info;
951 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
952 } else {
953 // Check is we are already at the desired config
954 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700955 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800956 return;
957 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800958
Ady Abraham59db0a32020-03-02 18:04:20 -0800959 // Initiate a config change.
960 mDesiredActiveConfigChanged = true;
961 mDesiredActiveConfig = info;
962
Ady Abrahamb838aed2019-02-12 15:30:16 -0800963 // This will trigger HWC refresh without resetting the idle timer.
964 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700965 // Start receiving vsync samples now, so that we can detect a period
966 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700967 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700968 // As we called to set period, we will call to onRefreshRateChangeCompleted once
969 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700970 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800971
Ady Abrahamabc27602020-04-08 17:20:29 -0700972 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800973 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700975
976 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800977 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700978 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979}
980
981status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
982 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800983
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100984 if (!displayToken) {
985 return BAD_VALUE;
986 }
Ady Abraham838de062019-02-04 10:24:03 -0800987
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700988 status_t result = NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100989
990 postMessageSync(new LambdaMessage([&]() {
991 const auto display = getDisplayDeviceLocked(displayToken);
992 if (!display) {
993 ALOGE("Attempt to set allowed display configs for invalid display token %p",
994 displayToken.get());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100995 } else if (display->isVirtual()) {
996 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700997 result = INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100998 } else {
999 HwcConfigIndexType config(mode);
1000 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
Steven Thomasd4071902020-03-24 16:02:53 -07001001 result = setDesiredDisplayConfigSpecsInternal(display,
1002 scheduler::RefreshRateConfigs::
Ady Abrahamabc27602020-04-08 17:20:29 -07001003 Policy{config,
1004 refreshRate.getFps(),
1005 refreshRate.getFps()},
Steven Thomasd4071902020-03-24 16:02:53 -07001006 /*overridePolicy=*/false);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001007 }
1008 }));
1009
1010 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001011}
1012
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001013void SurfaceFlinger::setActiveConfigInternal() {
1014 ATRACE_CALL();
1015
Dominik Laskowski22488f62019-03-28 09:53:04 -07001016 const auto display = getDefaultDisplayDeviceLocked();
1017 if (!display) {
1018 return;
1019 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020
Alec Mouri8de697e2020-03-19 10:52:01 -07001021 auto& oldRefreshRate =
1022 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1023
Dominik Laskowski22488f62019-03-28 09:53:04 -07001024 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001025 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001026 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001027 display->setActiveConfig(mUpcomingActiveConfig.configId);
1028
Ady Abraham2e1dd892020-03-05 13:48:36 -08001029 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001030 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001031 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001032 mTimeStats->incrementRefreshRateSwitches();
1033 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001034 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001035 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001036 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001037
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001038 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001039 const nsecs_t vsyncPeriod =
1040 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001041 .getVsyncPeriod();
Ady Abraham447052e2019-02-13 16:07:27 -08001042 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001043 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001044 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001045}
1046
Ady Abraham53852a52019-05-28 18:07:44 -07001047void SurfaceFlinger::desiredActiveConfigChangeDone() {
1048 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1049 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1050 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001051
Ady Abraham2e1dd892020-03-05 13:48:36 -08001052 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001053 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001054 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1055 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001056 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001057}
1058
Ady Abraham27cbed72020-04-10 12:56:59 -07001059void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001060 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001061 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001062 // Store the local variable to release the lock.
Ady Abraham27cbed72020-04-10 12:56:59 -07001063 const auto desiredActiveConfig = [&]() -> std::optional<ActiveConfigInfo> {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001064 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham27cbed72020-04-10 12:56:59 -07001065 if (mDesiredActiveConfigChanged) {
1066 return mDesiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001067 }
Ady Abraham27cbed72020-04-10 12:56:59 -07001068 return std::nullopt;
1069 }();
1070
1071 if (!desiredActiveConfig) {
1072 // No desired active config pending to be applied
1073 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001074 }
1075
Ady Abraham2e1dd892020-03-05 13:48:36 -08001076 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001077 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001078 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1079 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001080 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001081 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001082 // display is not valid or we are already in the requested mode
1083 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001084 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001085 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001086 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001087
Ady Abraham838de062019-02-04 10:24:03 -08001088 // Desired active config was set, it is different than the config currently in use, however
1089 // allowed configs might have change by the time we process the refresh.
1090 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001091 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001092 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001093 return;
Ady Abraham838de062019-02-04 10:24:03 -08001094 }
Alec Mouri7f015182019-07-11 13:56:22 -07001095
Ady Abraham27cbed72020-04-10 12:56:59 -07001096 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001097 const auto displayId = display->getId();
1098 LOG_ALWAYS_FATAL_IF(!displayId);
1099
Ady Abrahamabc27602020-04-08 17:20:29 -07001100 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001101
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001102 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001103 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001104 constraints.desiredTimeNanos = systemTime();
1105 constraints.seamlessRequired = false;
1106
Peiyong Line9d809e2020-04-14 13:10:48 -07001107 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001108 auto status =
1109 getHwComposer().setActiveConfigWithConstraints(*displayId,
1110 mUpcomingActiveConfig.configId.value(),
1111 constraints, &outTimeline);
1112 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001113 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1114 // to be sent. We just log the error in this case.
1115 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001116 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001117 }
1118
1119 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1120 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001121 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001122}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001123
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001124status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1125 Vector<ColorMode>* outColorModes) {
1126 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001127 return BAD_VALUE;
1128 }
1129
Peiyong Lina52f0292018-03-14 17:26:31 -07001130 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001131 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001132 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001133 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1134
1135 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1136 if (!displayId) {
1137 return NAME_NOT_FOUND;
1138 }
1139
Dominik Laskowski075d3172018-05-24 15:50:06 -07001140 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001141 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001142 }
Michael Wright28f24d02016-07-12 13:30:53 -07001143 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001144
1145 // If it's built-in display and the configuration claims it's not wide color capable,
1146 // filter out all wide color modes. The typical reason why this happens is that the
1147 // hardware is not good enough to support GPU composition of wide color, and thus the
1148 // OEMs choose to disable this capability.
1149 if (isInternalDisplay && !hasWideColorDisplay) {
1150 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1151 isWideColorMode);
1152 } else {
1153 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1154 }
Michael Wright28f24d02016-07-12 13:30:53 -07001155
1156 return NO_ERROR;
1157}
1158
Daniel Solomon42d04562019-01-20 21:03:19 -08001159status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1160 ui::DisplayPrimaries &primaries) {
1161 if (!displayToken) {
1162 return BAD_VALUE;
1163 }
1164
1165 // Currently we only support this API for a single internal display.
1166 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001167 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001168 }
1169
1170 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1171 return NO_ERROR;
1172}
1173
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001174ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001175 Mutex::Autolock lock(mStateLock);
1176
1177 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001178 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001179 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001180 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001181}
1182
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001183status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001184 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001185 Vector<ColorMode> modes;
1186 getDisplayColorModes(displayToken, &modes);
1187 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1188 if (mode < ColorMode::NATIVE || !exists) {
1189 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1190 decodeColorMode(mode).c_str(), mode, displayToken.get());
1191 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001192 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001193 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001194 if (!display) {
1195 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1196 decodeColorMode(mode).c_str(), mode, displayToken.get());
1197 } else if (display->isVirtual()) {
1198 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1199 decodeColorMode(mode).c_str(), mode);
1200 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001201 display->getCompositionDisplay()->setColorProfile(
1202 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1203 RenderIntent::COLORIMETRIC,
1204 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001205 }
1206 }));
1207
Michael Wright28f24d02016-07-12 13:30:53 -07001208 return NO_ERROR;
1209}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001210
Galia Peycheva5492cb52019-10-30 14:13:16 +01001211status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1212 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001213 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001214 return BAD_VALUE;
1215 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001216
1217 Mutex::Autolock lock(mStateLock);
1218
Galia Peycheva5492cb52019-10-30 14:13:16 +01001219 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1220 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001221 return NAME_NOT_FOUND;
1222 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001223 *outSupport =
1224 getHwComposer().hasDisplayCapability(*displayId,
1225 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001226 return NO_ERROR;
1227}
1228
1229void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001230 postMessageAsync(new LambdaMessage([=] {
1231 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1232 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1233 } else {
1234 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1235 }
1236 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001237}
1238
1239status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1240 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001241 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001242 return BAD_VALUE;
1243 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001244
1245 Mutex::Autolock lock(mStateLock);
1246
Galia Peycheva5492cb52019-10-30 14:13:16 +01001247 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1248 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001249 return NAME_NOT_FOUND;
1250 }
1251
Peiyong Line9d809e2020-04-14 13:10:48 -07001252 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001253 getHwComposer().getSupportedContentTypes(*displayId, &types);
1254
1255 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001256 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001257 return NO_ERROR;
1258}
1259
1260void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001261 postMessageAsync(new LambdaMessage([=] {
1262 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001263 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001264 getHwComposer().setContentType(*displayId, type);
1265 } else {
1266 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1267 }
1268 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001269}
1270
Svetoslavd85084b2014-03-20 10:28:31 -07001271status_t SurfaceFlinger::clearAnimationFrameStats() {
1272 Mutex::Autolock _l(mStateLock);
1273 mAnimFrameTracker.clearStats();
1274 return NO_ERROR;
1275}
1276
1277status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1278 Mutex::Autolock _l(mStateLock);
1279 mAnimFrameTracker.getStats(outStats);
1280 return NO_ERROR;
1281}
1282
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001283status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1284 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001285 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001286
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001287 const auto display = getDisplayDeviceLocked(displayToken);
1288 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001289 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1290 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001291 }
1292
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001293 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001294 // meaning the luminance information is already queried from
1295 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001296 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001297 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1298 capabilities.getDesiredMaxLuminance(),
1299 capabilities.getDesiredMaxAverageLuminance(),
1300 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001301
1302 return NO_ERROR;
1303}
1304
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001305std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1306 const DisplayDevice& display) const {
1307 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1308 // avoid repetitive HAL IPC and EDID parsing.
1309 const auto displayId = display.getId();
1310 LOG_FATAL_IF(!displayId);
1311
1312 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1313 LOG_FATAL_IF(!hwcDisplayId);
1314
1315 uint8_t port;
1316 DisplayIdentificationData data;
1317 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1318 ALOGV("%s: No identification data.", __FUNCTION__);
1319 return {};
1320 }
1321
1322 const auto info = parseDisplayIdentificationData(port, data);
1323 if (!info) {
1324 return {};
1325 }
1326 return info->deviceProductInfo;
1327}
1328
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001329status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1330 ui::PixelFormat* outFormat,
1331 ui::Dataspace* outDataspace,
1332 uint8_t* outComponentMask) const {
1333 if (!outFormat || !outDataspace || !outComponentMask) {
1334 return BAD_VALUE;
1335 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001336
1337 Mutex::Autolock lock(mStateLock);
1338
1339 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1340 if (!displayId) {
1341 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001342 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001343
1344 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001345 outDataspace, outComponentMask);
1346}
1347
Kevin DuBois74e53772018-11-19 10:52:38 -08001348status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1349 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001350 uint64_t maxFrames) {
1351 status_t result = NAME_NOT_FOUND;
Kevin DuBois74e53772018-11-19 10:52:38 -08001352
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001353 postMessageSync(new LambdaMessage([&] {
1354 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1355 result = getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1356 componentMask, maxFrames);
1357 } else {
1358 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1359 }
1360 }));
1361
1362 return result;
Kevin DuBois74e53772018-11-19 10:52:38 -08001363}
1364
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001365status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1366 uint64_t maxFrames, uint64_t timestamp,
1367 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001368 Mutex::Autolock lock(mStateLock);
1369
1370 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1371 if (!displayId) {
1372 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001373 }
1374
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001375 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001376}
1377
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001378status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1379 if (!outSupported) {
1380 return BAD_VALUE;
1381 }
1382 *outSupported = getRenderEngine().supportsProtectedContent();
1383 return NO_ERROR;
1384}
1385
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001386status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1387 bool* outIsWideColorDisplay) const {
1388 if (!displayToken || !outIsWideColorDisplay) {
1389 return BAD_VALUE;
1390 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001391
1392 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001393 const auto display = getDisplayDeviceLocked(displayToken);
1394 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001395 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001396 }
Peiyong Linff84a152019-05-17 18:36:19 -07001397
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001398 *outIsWideColorDisplay =
1399 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001400 return NO_ERROR;
1401}
1402
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001403status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001404 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001405 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001406
Dominik Laskowski6505f792019-09-18 11:10:05 -07001407 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1408 mEventQueue->setEventConnection(
1409 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001410 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001411 }));
1412
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001413 return NO_ERROR;
1414}
1415
1416status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001417 Mutex::Autolock lock(mStateLock);
1418 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001419}
1420
Lloyd Pique755e3192018-01-31 16:46:15 -08001421status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1422 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001423 // Try to acquire a lock for 1s, fail gracefully
1424 const status_t err = mStateLock.timedLock(s2ns(1));
1425 const bool locked = (err == NO_ERROR);
1426 if (!locked) {
1427 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1428 return TIMED_OUT;
1429 }
1430
1431 outLayers->clear();
1432 mCurrentState.traverseInZOrder([&](Layer* layer) {
1433 outLayers->push_back(layer->getLayerDebugInfo());
1434 });
1435
1436 mStateLock.unlock();
1437 return NO_ERROR;
1438}
1439
Peiyong Linc6780972018-10-28 15:24:08 -07001440status_t SurfaceFlinger::getCompositionPreference(
1441 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1442 Dataspace* outWideColorGamutDataspace,
1443 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001444 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001445 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001446 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001447 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001448 return NO_ERROR;
1449}
1450
Dan Stozaec460082018-12-17 15:35:09 -08001451status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1452 const sp<IBinder>& stopLayerHandle,
1453 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001454 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001455 return BAD_VALUE;
1456 }
1457 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001458 return NO_ERROR;
1459}
1460
Dan Stozaec460082018-12-17 15:35:09 -08001461status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001462 if (!listener) {
1463 return BAD_VALUE;
1464 }
Dan Stozaec460082018-12-17 15:35:09 -08001465 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001466 return NO_ERROR;
1467}
Dan Gittik57e63c52019-01-18 16:37:54 +00001468
1469status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1470 bool* outSupport) const {
1471 if (!displayToken || !outSupport) {
1472 return BAD_VALUE;
1473 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001474
1475 Mutex::Autolock lock(mStateLock);
1476
Dan Gittik57e63c52019-01-18 16:37:54 +00001477 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1478 if (!displayId) {
1479 return NAME_NOT_FOUND;
1480 }
1481 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001482 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001483 return NO_ERROR;
1484}
1485
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001486status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001487 if (!displayToken) {
1488 return BAD_VALUE;
1489 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001490
1491 status_t result = NAME_NOT_FOUND;
1492
1493 postMessageSync(new LambdaMessage([&] {
1494 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1495 result = getHwComposer().setDisplayBrightness(*displayId, brightness);
1496 } else {
1497 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1498 }
1499 }));
1500
1501 return result;
Dan Gittik57e63c52019-01-18 16:37:54 +00001502}
1503
Ady Abraham8532d012019-05-08 14:50:56 -07001504status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1505 PowerHint powerHint = static_cast<PowerHint>(hintId);
1506
1507 if (powerHint == PowerHint::INTERACTION) {
1508 mScheduler->notifyTouchEvent();
1509 }
1510
1511 return NO_ERROR;
1512}
1513
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001514// ----------------------------------------------------------------------------
1515
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001516sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001517 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001518 const auto& handle =
1519 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001520
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001521 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001522}
1523
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001524// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001525
1526void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001527 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001528}
1529
1530void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001531 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001532 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001533 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001534}
1535
1536void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001537 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001538 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001539 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001540}
1541
1542void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001543 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001544 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001545}
1546
1547status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001548 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001549 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001550}
1551
1552status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001553 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001554 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001555 if (res == NO_ERROR) {
1556 msg->wait();
1557 }
1558 return res;
1559}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001560
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001561void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001562 do {
1563 waitForEvent();
1564 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001565}
1566
Dominik Laskowski83b88212018-12-11 13:34:06 -08001567nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001568 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001569 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1570 return 0;
1571 }
1572
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001573 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001574}
1575
Peiyong Line9d809e2020-04-14 13:10:48 -07001576void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001577 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001578 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001579 ATRACE_NAME("SF onVsync");
1580
Steven Thomas3cfac282017-02-06 12:29:30 -08001581 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001582 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001583 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001584 return;
1585 }
1586
Dominik Laskowski075d3172018-05-24 15:50:06 -07001587 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001588 return;
1589 }
1590
Dominik Laskowski075d3172018-05-24 15:50:06 -07001591 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001592 // For now, we don't do anything with external display vsyncs.
1593 return;
1594 }
1595
Alec Mourif8e689c2019-05-20 18:32:22 -07001596 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001597 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001598 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001599 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001600 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001601}
1602
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001604 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1605 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606}
1607
Ady Abraham2139f732019-11-13 18:56:40 -08001608bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001609 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001610}
1611
Ady Abraham2139f732019-11-13 18:56:40 -08001612void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1613 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001614 const auto display = getDefaultDisplayDeviceLocked();
1615 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001616 return;
1617 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001618 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001619
Ana Krulec7d1d6832018-12-27 11:10:09 -08001620 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001621 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001622 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001623 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001624 return;
1625 }
1626
Ady Abrahamabc27602020-04-08 17:20:29 -07001627 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001628}
1629
Peiyong Line9d809e2020-04-14 13:10:48 -07001630void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
1631 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001632 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001633 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001634
Lloyd Piqueba04e622017-12-14 17:11:26 -08001635 // Ignore events that do not have the right sequenceId.
1636 if (sequenceId != getBE().mComposerSequenceId) {
1637 return;
1638 }
1639
Steven Thomasb02664d2017-07-26 18:48:28 -07001640 // Only lock if we're not on the main thread. This function is normally
1641 // called on a hwbinder thread, but for the primary display it's called on
1642 // the main thread with the state lock already held, so don't attempt to
1643 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001644 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001645
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001646 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001647
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001648 if (std::this_thread::get_id() == mMainThreadId) {
1649 // Process all pending hot plug events immediately if we are on the main thread.
1650 processDisplayHotplugEventsLocked();
1651 }
1652
Lloyd Piqueba04e622017-12-14 17:11:26 -08001653 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001654}
1655
Ady Abraham7159f572019-10-11 11:10:18 -07001656void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001657 int32_t sequenceId, hal::HWDisplayId /*display*/,
1658 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001659 Mutex::Autolock lock(mStateLock);
1660 if (sequenceId != getBE().mComposerSequenceId) {
1661 return;
1662 }
1663 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001664}
1665
Peiyong Line9d809e2020-04-14 13:10:48 -07001666void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001667 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1668 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1669}
1670
Peiyong Line9d809e2020-04-14 13:10:48 -07001671void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001672 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001673 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001674 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001675 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001676 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001677}
1678
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001679void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001680 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001681
1682 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1683 // display power state.
1684 postMessageAsync(new LambdaMessage(
1685 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1686}
1687
1688void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1689 ATRACE_CALL();
1690
Peiyong Line9d809e2020-04-14 13:10:48 -07001691 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001692
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001693 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001694 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1695 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001696 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001697 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001698 }
Mathias Agopian86303202012-07-24 22:46:10 -07001699}
1700
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001701// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001702void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001703 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001704 // Clear the drawing state so that the logic inside of
1705 // handleTransactionLocked will fire. It will determine the delta between
1706 // mCurrentState and mDrawingState and re-apply all changes when we make the
1707 // transition.
1708 mDrawingState.displays.clear();
1709 mDisplays.clear();
1710}
1711
Steven Thomas050b2c82017-03-06 11:45:16 -08001712void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001713 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001714 if (!mVrFlinger)
1715 return;
1716 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001717 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001718 return;
1719 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001720
Lloyd Pique441d5042018-10-18 16:49:51 -07001721 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001722 ALOGE("Vr flinger is only supported for remote hardware composer"
1723 " service connections. Ignoring request to transition to vr"
1724 " flinger.");
1725 mVrFlingerRequestsDisplay = false;
1726 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001727 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001728
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001729 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001730
Steven Thomas0123ac62018-07-12 11:32:34 -07001731 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001732 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001733
Peiyong Lin65248e02020-04-18 21:15:07 -07001734 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001735
1736 // Clear out all the output layers from the composition engine for all
1737 // displays before destroying the hardware composer interface. This ensures
1738 // any HWC layers are destroyed through that interface before it becomes
1739 // invalid.
1740 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001741 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001742 }
1743
Steven Thomas0123ac62018-07-12 11:32:34 -07001744 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1745 // called below. Clear the reference now so we don't accidentally use it
1746 // later.
1747 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001748
Steven Thomasb02664d2017-07-26 18:48:28 -07001749 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001750 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001751 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001752
Steven Thomasb02664d2017-07-26 18:48:28 -07001753 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001754 // Delete the current instance before creating the new one
1755 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1756 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1757 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001758 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001759
Lloyd Pique441d5042018-10-18 16:49:51 -07001760 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001761 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001762
1763 if (vrFlingerRequestsDisplay) {
1764 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001765 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001766
1767 mVisibleRegionsDirty = true;
1768 invalidateHwcGeometry();
1769
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001770 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001771 display = getDefaultDisplayDeviceLocked();
1772 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001773 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001774
Steven Thomasb02664d2017-07-26 18:48:28 -07001775 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001776 const nsecs_t vsyncPeriod = getVsyncPeriod();
1777 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001778
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001779 // The present fences returned from vr_hwc are not an accurate
1780 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001781 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001782
Steven Thomasb02664d2017-07-26 18:48:28 -07001783 // Use phase of 0 since phase is not known.
1784 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001785 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001786 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001787
Ana Krulecc2870422019-01-29 19:00:58 -08001788 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001789
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001790 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001791 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001792}
1793
Alec Mouri6d414b52020-03-17 11:18:05 -07001794sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001795 // We are storing the last 2 present fences. If sf's phase offset is to be
1796 // woken up before the actual vsync but targeting the next vsync, we need to check
1797 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001798 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1799 : mPreviousPresentFences[1];
1800}
1801
1802bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1803 ATRACE_CALL();
1804 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001805
Ady Abraham11579302019-09-19 12:35:58 -07001806 if (fence == Fence::NO_FENCE) {
1807 return false;
1808 }
1809
1810 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1811 fence->wait(graceTimeMs);
1812 }
1813
1814 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001815}
1816
Alec Mouri6d414b52020-03-17 11:18:05 -07001817nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1818 const sp<Fence>& fence = previousFrameFence();
1819
1820 if (fence == Fence::NO_FENCE) {
1821 return Fence::SIGNAL_TIME_INVALID;
1822 }
1823
1824 return fence->getSignalTime();
1825}
1826
Ady Abraham0ed31c92020-04-16 11:48:45 -07001827void SurfaceFlinger::populateExpectedPresentTime(nsecs_t wakeupTime) {
Alec Mouriaa614192019-06-06 13:28:34 -07001828 DisplayStatInfo stats;
1829 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham0ed31c92020-04-16 11:48:45 -07001830 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(wakeupTime);
Alec Mouriaa614192019-06-06 13:28:34 -07001831 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001832 mExpectedPresentTime.store(
1833 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001834}
1835
Ady Abraham0ed31c92020-04-16 11:48:45 -07001836void SurfaceFlinger::onMessageReceived(int32_t what, nsecs_t when) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001837 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001838 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001839 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001840 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001841 // calculate the expected present time once and use the cached
1842 // value throughout this frame to make sure all layers are
1843 // seeing this same value.
Alec Mouri6d414b52020-03-17 11:18:05 -07001844 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
Ady Abraham0ed31c92020-04-16 11:48:45 -07001845 populateExpectedPresentTime(when);
Ady Abraham7c03ce62019-07-19 10:59:45 -07001846
Ady Abraham11579302019-09-19 12:35:58 -07001847 // When Backpressure propagation is enabled we want to give a small grace period
1848 // for the present fence to fire instead of just giving up on this frame to handle cases
1849 // where present fence is just about to get signaled.
1850 const int graceTimeForPresentFenceMs =
1851 (mPropagateBackpressure &&
1852 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1853 ? 1
1854 : 0;
Alec Mouri6d414b52020-03-17 11:18:05 -07001855
1856 // Pending frames may trigger backpressure propagation.
1857 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1858 previousFramePending(
1859 graceTimeForPresentFenceMs)};
1860
1861 // Frame missed counts for metrics tracking.
1862 // A frame is missed if the prior frame is still pending. If no longer pending,
1863 // then we still count the frame as missed if the predicted present time
1864 // was further in the past than when the fence actually fired.
1865
1866 // Add some slop to correct for drift. This should generally be
1867 // smaller than a typical frame duration, but should not be so small
1868 // that it reports reasonable drift as a missed frame.
1869 DisplayStatInfo stats;
1870 mScheduler->getDisplayStatInfo(&stats);
1871 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1872 const nsecs_t previousPresentTime = previousFramePresentTime();
1873 const TracedOrdinal<bool> frameMissed =
1874 {"PrevFrameMissed",
1875 framePending ||
1876 (previousPresentTime >= 0 &&
1877 (lastExpectedPresentTime < previousPresentTime - frameMissedSlop))};
1878 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001879 mHadDeviceComposition && frameMissed};
Alec Mouri6d414b52020-03-17 11:18:05 -07001880 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001881 mHadClientComposition && frameMissed};
1882
Alec Mouricc0fc602019-02-26 21:45:19 -08001883 if (frameMissed) {
1884 mFrameMissedCount++;
1885 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001886 if (mMissedFrameJankCount == 0) {
1887 mMissedFrameJankStart = systemTime();
1888 }
1889 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001890 }
1891
Alec Mouri40189b02019-03-05 15:07:54 -08001892 if (hwcFrameMissed) {
1893 mHwcFrameMissedCount++;
1894 }
1895
1896 if (gpuFrameMissed) {
1897 mGpuFrameMissedCount++;
1898 }
1899
Ady Abraham27cbed72020-04-10 12:56:59 -07001900 // If we are in the middle of a config change and the fence hasn't
1901 // fired yet just wait for the next invalidate
1902 if (mSetActiveConfigPending) {
1903 if (framePending) {
1904 mEventQueue->invalidate();
1905 break;
1906 }
1907
1908 // We received the present fence from the HWC, so we assume it successfully updated
1909 // the config, hence we update SF.
1910 mSetActiveConfigPending = false;
1911 setActiveConfigInternal();
1912 }
1913
Alec Mouri6d414b52020-03-17 11:18:05 -07001914 if (framePending && mPropagateBackpressure) {
Ady Abrahamadb9a992019-09-19 21:21:55 +00001915 if ((hwcFrameMissed && !gpuFrameMissed) ||
1916 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001917 signalLayerUpdate();
1918 break;
1919 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001920 }
Dan Stoza50182882016-07-08 12:02:20 -07001921
Alec Mouri989ddbe2020-02-06 09:26:19 -08001922 // Our jank window is always at least 100ms since we missed a
1923 // frame...
1924 static constexpr nsecs_t kMinJankyDuration =
1925 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1926 // ...but if it's larger than 1s then we missed the trace cutoff.
1927 static constexpr nsecs_t kMaxJankyDuration =
1928 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1929 // If we're in a user build then don't push any atoms
1930 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1931 const auto displayDevice = getDefaultDisplayDeviceLocked();
1932 // Only report jank when the display is on, as displays in DOZE
1933 // power mode may operate at a different frame rate than is
1934 // reported in their config, which causes noticeable (but less
1935 // severe) jank.
Peiyong Lin65248e02020-04-18 21:15:07 -07001936 if (displayDevice && displayDevice->getPowerMode() == hal::PowerMode::ON) {
Alec Mouri989ddbe2020-02-06 09:26:19 -08001937 const nsecs_t currentTime = systemTime();
1938 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1939 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1940 ATRACE_NAME("Jank detected");
1941 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1942 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1943 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1944 jankyDurationMillis, mMissedFrameJankCount);
1945 }
1946
1947 // We either reported a jank event or we missed the trace
1948 // window, so clear counters here.
1949 if (jankDuration > kMinJankyDuration) {
1950 mMissedFrameJankCount = 0;
1951 mMissedFrameJankStart = 0;
1952 }
1953 }
1954 }
1955
Steven Thomas050b2c82017-03-06 11:45:16 -08001956 // Now that we're going to make it to the handleMessageTransaction()
1957 // call below it's safe to call updateVrFlinger(), which will
1958 // potentially trigger a display handoff.
1959 updateVrFlinger();
1960
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001961 if (mTracingEnabledChanged) {
1962 mTracingEnabled = mTracing.isEnabled();
1963 mTracingEnabledChanged = false;
1964 }
1965
Vishnu Nair60db8c02020-04-02 11:55:16 -07001966 bool refreshNeeded;
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001967 {
1968 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1969
Vishnu Nair60db8c02020-04-02 11:55:16 -07001970 refreshNeeded = handleMessageTransaction();
1971 refreshNeeded |= handleMessageInvalidate();
1972 if (mTracingEnabled) {
1973 mAddCompositionStateToTrace =
1974 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1975 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1976 mTracing.notifyLocked("visibleRegionsDirty");
1977 }
1978 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001979 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001980
Ana Krulecc84d09b2019-11-02 23:10:29 +01001981 // Layers need to get updated (in the previous line) before we can use them for
1982 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001983 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1984 // and may eventually call to ~Layer() if it holds the last reference
1985 {
1986 Mutex::Autolock _l(mStateLock);
1987 mScheduler->chooseRefreshRateForContent();
1988 }
1989
Ady Abraham27cbed72020-04-10 12:56:59 -07001990 performSetActiveConfig();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001991
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001992 updateCursorAsync();
1993 updateInputFlinger();
1994
Dan Stoza58784442014-12-02 16:58:17 -08001995 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001996 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001997 // Signal a refresh if a transaction modified the window state,
1998 // a new buffer was latched, or if HWC has requested a full
1999 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08002000 if (mFrameStartTime <= 0) {
2001 // We should only use the time of the first invalidate
2002 // message that signals a refresh as the beginning of the
2003 // frame. Otherwise the real frame time will be
2004 // underestimated.
2005 mFrameStartTime = frameStart;
2006 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08002007 signalRefresh();
2008 }
2009 break;
2010 }
2011 case MessageQueue::REFRESH: {
2012 handleMessageRefresh();
2013 break;
2014 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002015 }
2016}
2017
Dan Stoza6b9454d2014-11-07 16:00:59 -08002018bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08002019 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002020 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002021
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002022 bool flushedATransaction = flushTransactionQueues();
2023
2024 bool runHandleTransaction = transactionFlags &&
2025 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
2026
2027 if (runHandleTransaction) {
2028 handleTransaction(eTransactionMask);
2029 } else {
2030 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002031 }
2032
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002033 if (transactionFlushNeeded()) {
2034 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002035 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002036
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002037 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002038}
2039
Mathias Agopian4fec8732012-06-29 14:12:52 -07002040void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002041 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002042
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002043 mRefreshPending = false;
2044
Lloyd Piqueab039b52019-02-13 14:22:42 -08002045 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002046 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002047 for (const auto& [_, display] : mDisplays) {
2048 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2049 }
2050 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002051 if (auto layerFE = layer->getCompositionEngineLayerFE())
2052 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002053 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002054 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2055 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002056 if (auto layerFE = layer->getCompositionEngineLayerFE())
2057 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002058 }
2059
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002060 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002061 refreshArgs.outputColorSetting = useColorManagement
2062 ? mDisplayColorSetting
2063 : compositionengine::OutputColorSetting::kUnmanaged;
2064 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2065 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002066
2067 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2068 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002069 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002070
2071 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2072 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2073 mDrawingState.colorMatrixChanged = false;
2074 }
2075
2076 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2077
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002078 if (mDebugRegion != 0) {
2079 refreshArgs.devOptFlashDirtyRegionsDelay =
2080 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2081 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002082
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002083 mGeometryInvalid = false;
2084
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002085 // Store the present time just before calling to the composition engine so we could notify
2086 // the scheduler.
2087 const auto presentTime = systemTime();
2088
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002089 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002090 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2091 // Reset the frame start time now that we've recorded this frame.
2092 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002093
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002094 mScheduler->onDisplayRefreshed(presentTime);
2095
David Sodmanfa9b2af2017-12-24 13:28:59 -08002096 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002097 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002098
Alec Mouri8f7a0102020-04-15 12:11:10 -07002099 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2100
Lloyd Pique66d68602019-02-13 14:23:31 -08002101 mHadClientComposition =
2102 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2103 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002104 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2105 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002106 });
2107 mHadDeviceComposition =
2108 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2109 auto& displayDevice = tokenDisplayPair.second;
2110 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2111 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002112 mReusedClientComposition =
2113 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2114 auto& displayDevice = tokenDisplayPair.second;
2115 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2116 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002117
Alec Mouri8f7a0102020-04-15 12:11:10 -07002118 // Only report a strategy change if we move in and out of composition with hw overlays
2119 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2120 mTimeStats->incrementCompositionStrategyChanges();
2121 }
2122
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002123 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002124
David Sodman7e4ae112018-02-09 15:02:28 -08002125 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002126 if (mVisibleRegionsDirty) {
2127 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002128 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002129 mTracing.notify("visibleRegionsDirty");
2130 }
2131 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002132
2133 if (mCompositionEngine->needsAnotherUpdate()) {
2134 signalLayerUpdate();
2135 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002136}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002137
David Sodmanfa9b2af2017-12-24 13:28:59 -08002138
2139bool SurfaceFlinger::handleMessageInvalidate() {
2140 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002141 bool refreshNeeded = handlePageFlip();
2142
Vishnu Nair4351ad52019-02-11 14:13:02 -08002143 if (mVisibleRegionsDirty) {
2144 computeLayerBounds();
2145 }
2146
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002147 for (auto& layer : mLayersPendingRefresh) {
2148 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002149 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002150 invalidateLayerStack(layer, visibleReg);
2151 }
2152 mLayersPendingRefresh.clear();
2153 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002154}
2155
Ana Krulece588e312018-09-18 12:32:24 -07002156void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2157 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002158 // Update queue of past composite+present times and determine the
2159 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002160 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002161 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002162 while (!getBE().mCompositePresentTimes.empty()) {
2163 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002164 // Cached values should have been updated before calling this method,
2165 // which helps avoid duplicate syscalls.
2166 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2167 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2168 break;
2169 }
2170 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002171 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002172 }
2173
2174 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002175 while (getBE().mCompositePresentTimes.size() > 16) {
2176 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002177 }
2178
Ana Krulece588e312018-09-18 12:32:24 -07002179 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002180}
2181
Ana Krulece588e312018-09-18 12:32:24 -07002182void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2183 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002184 // Integer division and modulo round toward 0 not -inf, so we need to
2185 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002186 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2187 ? (stats.vsyncPeriod -
2188 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2189 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002190
Ady Abraham9e16a482019-12-03 17:19:41 -08002191 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002192 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002193 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002194 }
2195
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002196 // Snap the latency to a value that removes scheduling jitter from the
2197 // composition and present times, which often have >1ms of jitter.
2198 // Reducing jitter is important if an app attempts to extrapolate
2199 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002200 // Snapping also allows an app to precisely calculate
2201 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002202 nsecs_t bias = stats.vsyncPeriod / 2;
2203 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2204 nsecs_t snappedCompositeToPresentLatency =
2205 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002206
David Sodman99974d22017-11-28 12:04:33 -08002207 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002208 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2209 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002210 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002211}
2212
David Sodman2b406362017-12-15 13:33:47 -08002213void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002214{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002215 ATRACE_CALL();
2216 ALOGV("postComposition");
2217
Brian Andersonf6386862016-10-31 16:34:13 -07002218 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002219 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002220 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002221 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002222 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002223 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002224
David Sodman73beded2017-11-15 11:56:06 -08002225 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002226 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002227 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002228 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002229 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2230 ->getRenderSurface()
2231 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002232 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002233 } else {
2234 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2235 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002236
David Sodman73beded2017-11-15 11:56:06 -08002237 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002238 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2239 mPreviousPresentFences[0] = displayDevice
2240 ? getHwComposer().getPresentFence(*displayDevice->getId())
2241 : Fence::NO_FENCE;
2242 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002243 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002244
Ana Krulece588e312018-09-18 12:32:24 -07002245 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002246 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002247
Lloyd Piqueab039b52019-02-13 14:22:42 -08002248 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2249 // be sampled a little later than when we started doing work for this frame,
2250 // but that should be okay since updateCompositorTiming has snapping logic.
2251 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2252 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002253 CompositorTiming compositorTiming;
2254 {
David Sodman99974d22017-11-28 12:04:33 -08002255 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2256 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002257 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002258
Edgar Arriaga844fa672020-01-16 14:21:42 -08002259 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002260 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2261 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002262 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002263 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002264 }
Robert Carr2047fae2016-11-28 14:09:09 -08002265 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002266
Valerie Hau4b678442020-04-14 10:50:42 -07002267 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2268 mTransactionCompletedThread.sendCallbacks();
2269
Ady Abraham92fa2f42020-02-11 15:33:56 -08002270 if (displayDevice && displayDevice->isPrimary() &&
Peiyong Lin65248e02020-04-18 21:15:07 -07002271 displayDevice->getPowerMode() == hal::PowerMode::ON && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002272 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002273 }
2274
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002275 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002276 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2277 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002278 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002279 }
2280 }
2281
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002282 if (mAnimCompositionPending) {
2283 mAnimCompositionPending = false;
2284
Brian Anderson4e606e32017-03-16 15:34:57 -07002285 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002286 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002287 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002288 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002289 // The HWC doesn't support present fences, so use the refresh
2290 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002291 const nsecs_t presentTime =
2292 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002293 mAnimFrameTracker.setActualPresentTime(presentTime);
2294 }
2295 mAnimFrameTracker.advanceFrame();
2296 }
Dan Stozab90cf072015-03-05 11:05:59 -08002297
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002298 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002299 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002300 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002301 }
2302
Vishnu Nair9b079a22020-01-21 14:36:08 -08002303 if (mReusedClientComposition) {
2304 mTimeStats->incrementClientCompositionReusedFrames();
2305 }
2306
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002307 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002308
Alec Mouri717bcb62020-02-10 17:07:19 -08002309 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2310 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2311 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2312
Lloyd Pique32cbe282018-10-19 13:09:22 -07002313 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2314 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002315 return;
2316 }
2317
2318 nsecs_t currentTime = systemTime();
2319 if (mHasPoweredOff) {
2320 mHasPoweredOff = false;
2321 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002322 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002323 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002324 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2325 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002326 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002327 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002328 }
David Sodman4a36e932017-11-07 14:29:47 -08002329 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002330 }
David Sodman4a36e932017-11-07 14:29:47 -08002331 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002332
2333 {
2334 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002335 if (mTexturePool.size() < mTexturePoolSize) {
2336 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002337 const size_t offset = mTexturePool.size();
2338 mTexturePool.resize(mTexturePoolSize);
2339 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2340 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002341 } else if (mTexturePool.size() > mTexturePoolSize) {
2342 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2343 const size_t offset = mTexturePoolSize;
2344 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2345 mTexturePool.resize(mTexturePoolSize);
2346 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002347 }
2348 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002349
Kevin DuBois413287f2019-02-25 08:46:47 -08002350 if (mLumaSampling && mRegionSamplingThread) {
2351 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002352 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002353
2354 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2355 // side-effect of getTotalSize(), so we check that again here
2356 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002357 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002358 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2359 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002360}
2361
Vishnu Nair4351ad52019-02-11 14:13:02 -08002362void SurfaceFlinger::computeLayerBounds() {
2363 for (const auto& pair : mDisplays) {
2364 const auto& displayDevice = pair.second;
2365 const auto display = displayDevice->getCompositionDisplay();
2366 for (const auto& layer : mDrawingState.layersSortedByZ) {
2367 // only consider the layers on the given layer stack
2368 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002369 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002370 }
2371
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002372 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2373 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002374 }
2375 }
2376}
2377
David Sodmanfa9b2af2017-12-24 13:28:59 -08002378void SurfaceFlinger::postFrame()
2379{
2380 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002381 const auto display = getDefaultDisplayDeviceLocked();
2382 if (display && getHwComposer().isConnected(*display->getId())) {
2383 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002384 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2385 logFrameStats();
2386 }
2387 }
2388}
2389
Mathias Agopian87baae12012-07-31 12:38:26 -07002390void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002391{
Mathias Agopian841cde52012-03-01 15:44:37 -08002392 ATRACE_CALL();
2393
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002394 // here we keep a copy of the drawing state (that is the state that's
2395 // going to be overwritten by handleTransactionLocked()) outside of
2396 // mStateLock so that the side-effects of the State assignment
2397 // don't happen with mStateLock held (which can cause deadlocks).
2398 State drawingState(mDrawingState);
2399
Mathias Agopianca4d3602011-05-19 15:38:14 -07002400 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002401 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002402
Mathias Agopianca4d3602011-05-19 15:38:14 -07002403 // Here we're guaranteed that some transaction flags are set
2404 // so we can call handleTransactionLocked() unconditionally.
2405 // We call getTransactionFlags(), which will also clear the flags,
2406 // with mStateLock held to guarantee that mCurrentState won't change
2407 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002408
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002409 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002410 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002411 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002412
Mathias Agopianca4d3602011-05-19 15:38:14 -07002413 mDebugInTransaction = 0;
2414 invalidateHwcGeometry();
2415 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002416}
2417
Lloyd Piqueba04e622017-12-14 17:11:26 -08002418void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2419 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002420 const std::optional<DisplayIdentificationInfo> info =
2421 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002422
Dominik Laskowski075d3172018-05-24 15:50:06 -07002423 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002424 continue;
2425 }
2426
Dominik Laskowski55c85402020-01-21 16:25:47 -08002427 const DisplayId displayId = info->id;
2428 const auto it = mPhysicalDisplayTokens.find(displayId);
2429
Peiyong Line9d809e2020-04-14 13:10:48 -07002430 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002431 if (it == mPhysicalDisplayTokens.end()) {
2432 ALOGV("Creating display %s", to_string(displayId).c_str());
2433
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002434 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002435 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002436 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002437
Dominik Laskowski075d3172018-05-24 15:50:06 -07002438 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002439 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2440 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002441 state.isSecure = true; // All physical displays are currently considered secure.
2442 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002443
2444 sp<IBinder> token = new BBinder();
2445 mCurrentState.displays.add(token, state);
2446 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2447
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002449 } else {
2450 ALOGV("Recreating display %s", to_string(displayId).c_str());
2451
2452 const auto token = it->second;
2453 auto& state = mCurrentState.displays.editValueFor(token);
2454 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002455 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002456 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002457 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002458
Dominik Laskowski55c85402020-01-21 16:25:47 -08002459 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002460 if (index >= 0) {
2461 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2462 mInterceptor->saveDisplayDeletion(state.sequenceId);
2463 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002464 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002465 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002466 }
2467
2468 processDisplayChangesLocked();
2469 }
2470
2471 mPendingHotplugEvents.clear();
2472}
2473
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002474void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002475 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2476 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002477}
2478
Lloyd Pique99d3da52018-01-22 17:48:03 -08002479sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002480 const wp<IBinder>& displayToken,
2481 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002482 const DisplayDeviceState& state,
2483 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002484 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002485 auto displayId = compositionDisplay->getDisplayId();
2486 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002487 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002488 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002489 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002490 creationArgs.hasWideColorGamut = false;
2491 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002492
Dominik Laskowski55c85402020-01-21 16:25:47 -08002493 if (const auto& physical = state.physical) {
2494 creationArgs.connectionType = physical->type;
2495 }
2496
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002497 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002498 creationArgs.isPrimary = isInternalDisplay;
2499
2500 if (useColorManagement && displayId) {
2501 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002503 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002504 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002505 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002506
Dominik Laskowski7e045462018-05-30 13:02:02 -07002507 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002508 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002509 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002510 }
tangrobin6753a022018-08-10 10:58:54 +08002511 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002512
Dominik Laskowski075d3172018-05-24 15:50:06 -07002513 if (displayId) {
2514 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002515 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002516 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002517 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002518
Lloyd Pique90c115d2018-09-18 21:39:42 -07002519 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002520 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002521 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522
Lloyd Pique99d3da52018-01-22 17:48:03 -08002523 // Make sure that composition can never be stalled by a virtual display
2524 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002525 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002526 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002527 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2528 }
2529
Dominik Laskowski718f9602019-11-09 20:01:35 -08002530 creationArgs.physicalOrientation =
2531 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002532
Lloyd Pique99d3da52018-01-22 17:48:03 -08002533 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002534 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002535
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002536 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002537
2538 if (maxFrameBufferAcquiredBuffers >= 3) {
2539 nativeWindowSurface->preallocateBuffers();
2540 }
2541
2542 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002543 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002544 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002545 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002546 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002548 display->getCompositionDisplay()->setColorProfile(
2549 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2550 RenderIntent::COLORIMETRIC,
2551 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 if (!state.isVirtual()) {
2553 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002554 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2555 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002556 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002557
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002558 display->setLayerStack(state.layerStack);
2559 display->setProjection(state.orientation, state.viewport, state.frame);
2560 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002561
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002562 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002563}
2564
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002565void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2566 const DisplayDeviceState& state) {
2567 int width = 0;
2568 int height = 0;
2569 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2570 if (state.physical) {
2571 const auto& activeConfig =
2572 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2573 width = activeConfig->getWidth();
2574 height = activeConfig->getHeight();
2575 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2576 } else if (state.surface != nullptr) {
2577 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2578 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2579 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2580 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2581 int intPixelFormat;
2582 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2583 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2584 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2585 } else {
2586 // Virtual displays without a surface are dormant:
2587 // they have external state (layer stack, projection,
2588 // etc.) but no internal state (i.e. a DisplayDevice).
2589 return;
2590 }
2591
2592 compositionengine::DisplayCreationArgsBuilder builder;
2593 if (const auto& physical = state.physical) {
2594 builder.setPhysical({physical->id, physical->type});
2595 }
2596 builder.setPixels(ui::Size(width, height));
2597 builder.setPixelFormat(pixelFormat);
2598 builder.setIsSecure(state.isSecure);
2599 builder.setLayerStackId(state.layerStack);
2600 builder.setPowerAdvisor(&mPowerAdvisor);
2601 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2602 builder.setName(state.displayName);
2603 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2604
2605 sp<compositionengine::DisplaySurface> displaySurface;
2606 sp<IGraphicBufferProducer> producer;
2607 sp<IGraphicBufferProducer> bqProducer;
2608 sp<IGraphicBufferConsumer> bqConsumer;
2609 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2610
2611 std::optional<DisplayId> displayId = compositionDisplay->getId();
2612
2613 if (state.isVirtual()) {
2614 sp<VirtualDisplaySurface> vds =
2615 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2616 bqConsumer, state.displayName);
2617
2618 displaySurface = vds;
2619 producer = vds;
2620 } else {
2621 ALOGE_IF(state.surface != nullptr,
2622 "adding a supported display, but rendering "
2623 "surface is provided (%p), ignoring it",
2624 state.surface.get());
2625
2626 LOG_ALWAYS_FATAL_IF(!displayId);
2627 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2628 maxGraphicsWidth, maxGraphicsHeight);
2629 producer = bqProducer;
2630 }
2631
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002632 LOG_FATAL_IF(!displaySurface);
2633 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2634 displaySurface, producer);
2635 mDisplays.emplace(displayToken, display);
2636 if (!state.isVirtual()) {
2637 LOG_FATAL_IF(!displayId);
2638 dispatchDisplayHotplugEvent(displayId->value, true);
2639 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002640
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002641 if (display->isPrimary()) {
2642 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002643 }
2644}
2645
2646void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2647 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2648 // Save display ID before disconnecting.
2649 const auto displayId = display->getId();
2650 display->disconnect();
2651
2652 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002653 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002654 dispatchDisplayHotplugEvent(displayId->value, false);
2655 }
2656 }
2657
2658 mDisplays.erase(displayToken);
2659}
2660
2661void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2662 const DisplayDeviceState& currentState,
2663 const DisplayDeviceState& drawingState) {
2664 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2665 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002666 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002667 // changing the surface is like destroying and recreating the DisplayDevice
2668 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2669 display->disconnect();
2670 }
2671 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002672 if (const auto& physical = currentState.physical) {
2673 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2674 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002675 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002676 if (currentState.physical) {
2677 initializeDisplays();
2678 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002679 return;
2680 }
2681
2682 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2683 if (currentState.layerStack != drawingState.layerStack) {
2684 display->setLayerStack(currentState.layerStack);
2685 }
2686 if ((currentState.orientation != drawingState.orientation) ||
2687 (currentState.viewport != drawingState.viewport) ||
2688 (currentState.frame != drawingState.frame)) {
2689 display->setProjection(currentState.orientation, currentState.viewport,
2690 currentState.frame);
2691 }
2692 if (currentState.width != drawingState.width ||
2693 currentState.height != drawingState.height) {
2694 display->setDisplaySize(currentState.width, currentState.height);
2695 if (display->isPrimary()) {
2696 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2697 }
2698 }
2699 }
2700}
2701
Lloyd Pique347200f2017-12-14 17:00:15 -08002702void SurfaceFlinger::processDisplayChangesLocked() {
2703 // here we take advantage of Vector's copy-on-write semantics to
2704 // improve performance by skipping the transaction entirely when
2705 // know that the lists are identical
2706 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2707 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2708 if (!curr.isIdenticalTo(draw)) {
2709 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002710
2711 // find the displays that were removed
2712 // (ie: in drawing state but not in current state)
2713 // also handle displays that changed
2714 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002715 for (size_t i = 0; i < draw.size(); i++) {
2716 const wp<IBinder>& displayToken = draw.keyAt(i);
2717 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002718 if (j < 0) {
2719 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002720 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002721 } else {
2722 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002723 const DisplayDeviceState& currentState = curr[j];
2724 const DisplayDeviceState& drawingState = draw[i];
2725 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002726 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002727 }
2728
2729 // find displays that were added
2730 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002731 for (size_t i = 0; i < curr.size(); i++) {
2732 const wp<IBinder>& displayToken = curr.keyAt(i);
2733 if (draw.indexOfKey(displayToken) < 0) {
2734 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 }
2736 }
2737 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002738
2739 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002740}
2741
Mathias Agopian87baae12012-07-31 12:38:26 -07002742void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002743{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002744 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2745
Dan Stoza7dde5992015-05-22 09:51:44 -07002746 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002747 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002748 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002749 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002750
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751 /*
2752 * Traversal of the children
2753 * (perform the transaction for each of them if needed)
2754 */
2755
Marissa Wall06255332019-03-27 13:48:27 -07002756 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002757 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002759 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760
2761 const uint32_t flags = layer->doTransaction(0);
2762 if (flags & Layer::eVisibleRegion)
2763 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002764
2765 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002766 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002767 }
Robert Carr2047fae2016-11-28 14:09:09 -08002768 });
Marissa Wall06255332019-03-27 13:48:27 -07002769 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 }
2771
2772 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002773 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774 */
2775
Mathias Agopiane57f2922012-08-09 16:29:12 -07002776 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002777 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002778 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002779 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002781 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002782 // The transform hint might have changed for some layers
2783 // (either because a display has changed, or because a layer
2784 // as changed).
2785 //
2786 // Walk through all the layers in currentLayers,
2787 // and update their transform hint.
2788 //
2789 // If a layer is visible only on a single display, then that
2790 // display is used to calculate the hint, otherwise we use the
2791 // default display.
2792 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002793 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002794 // the hint is set before we acquire a buffer from the surface texture.
2795 //
2796 // NOTE: layer transactions have taken place already, so we use their
2797 // drawing state. However, SurfaceFlinger's own transaction has not
2798 // happened yet, so we must use the current state layer list
2799 // (soon to become the drawing state list).
2800 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002801 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002802 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002803 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002804 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002805 // NOTE: we rely on the fact that layers are sorted by
2806 // layerStack first (so we don't have to traverse the list
2807 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002808 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002809 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002810 currentlayerStack = layerStack;
2811 // figure out if this layerstack is mirrored
2812 // (more than one display) if so, pick the default display,
2813 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002814 hintDisplay = nullptr;
2815 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002816 if (display->getCompositionDisplay()
2817 ->belongsInOutput(layer->getLayerStack(),
2818 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002819 if (hintDisplay) {
2820 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002821 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002822 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002823 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002824 }
2825 }
2826 }
2827 }
Chet Haase91d25932013-04-11 15:24:55 -07002828
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002829 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002830 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2831 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002832
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002833 // could be null when this layer is using a layerStack
2834 // that is not visible on any display. Also can occur at
2835 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002836 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002837 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002838
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002839 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002840 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002841 if (hintDisplay) {
2842 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002843 }
Robert Carr2047fae2016-11-28 14:09:09 -08002844
2845 first = false;
2846 });
Mathias Agopian84300952012-11-21 16:02:13 -08002847 }
2848
2849
Mathias Agopian3559b072012-08-15 13:46:03 -07002850 /*
2851 * Perform our own transaction if needed
2852 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002853
2854 if (mLayersAdded) {
2855 mLayersAdded = false;
2856 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002857 mVisibleRegionsDirty = true;
2858 }
2859
2860 // some layers might have been removed, so
2861 // we need to update the regions they're exposing.
2862 if (mLayersRemoved) {
2863 mLayersRemoved = false;
2864 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002865 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002866 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002867 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002868 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002869 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002870 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002871 }
Robert Carr2047fae2016-11-28 14:09:09 -08002872 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873 }
2874
Vishnu Nairec0ab382019-02-13 15:32:56 -08002875 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002877}
2878
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002879void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002880 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002881 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002882 return;
2883 }
2884
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002885 if (mVisibleRegionsDirty || mInputInfoChanged) {
2886 mInputInfoChanged = false;
2887 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002888 } else if (mInputWindowCommands.syncInputWindows) {
2889 // If the caller requested to sync input windows, but there are no
2890 // changes to input windows, notify immediately.
2891 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002892 }
2893
Arthur Hung6cbb9752019-09-05 16:38:18 +08002894 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002895}
2896
2897void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002898 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002899
2900 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2901 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002902 // When calculating the screen bounds we ignore the transparent region since it may
2903 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002904 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002905 }
2906 });
chaviw291d88a2019-02-14 10:33:58 -08002907
2908 mInputFlinger->setInputWindows(inputHandles,
2909 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2910 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002911}
2912
Vishnu Nairec0ab382019-02-13 15:32:56 -08002913void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002914 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002915 mPendingInputWindowCommands.clear();
2916}
2917
Riley Andrews03414a12014-07-01 14:22:59 -07002918void SurfaceFlinger::updateCursorAsync()
2919{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002920 compositionengine::CompositionRefreshArgs refreshArgs;
2921 for (const auto& [_, display] : mDisplays) {
2922 if (display->getId()) {
2923 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002924 }
2925 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002926
2927 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002928}
2929
Ady Abraham2139f732019-11-13 18:56:40 -08002930void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002931 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2932 // If this is called from the main thread mStateLock must be locked before
2933 // Currently the only way to call this function from the main thread is from
2934 // Sheduler::chooseRefreshRateForContent
2935
2936 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002937 changeRefreshRateLocked(refreshRate, event);
2938}
2939
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002940void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2941 if (mScheduler) {
2942 // In practice it's not allowed to hotplug in/out the primary display once it's been
2943 // connected during startup, but some tests do it, so just warn and return.
2944 ALOGW("Can't re-init scheduler");
2945 return;
2946 }
2947
Ady Abraham2139f732019-11-13 18:56:40 -08002948 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002949 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002950 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002951 primaryDisplayId),
2952 currentConfig);
2953 mRefreshRateStats =
2954 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002955 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002956 mRefreshRateStats->setConfigMode(currentConfig);
2957
Ady Abraham9e16a482019-12-03 17:19:41 -08002958 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2959
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002960 // start the EventThread
2961 mScheduler =
2962 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002963 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002964 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002965 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002966 impl::EventThread::InterceptVSyncsCallback());
2967 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002968 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002969 [this](nsecs_t timestamp) {
2970 mInterceptor->saveVSyncEvent(timestamp);
2971 });
2972
2973 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2974 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002975 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002976
2977 mRegionSamplingThread =
2978 new RegionSamplingThread(*this, *mScheduler,
2979 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002980 // Dispatch a config change request for the primary display on scheduler
2981 // initialization, so that the EventThreads always contain a reference to a
2982 // prior configuration.
2983 //
2984 // This is a bit hacky, but this avoids a back-pointer into the main SF
2985 // classes from EventThread, and there should be no run-time binder cost
2986 // anyway since there are no connected apps at this point.
2987 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002988 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Alec Mouri60aee1c2019-10-28 16:18:59 -07002989 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2990 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002991}
2992
Mathias Agopian4fec8732012-06-29 14:12:52 -07002993void SurfaceFlinger::commitTransaction()
2994{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002995 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002996 mTransactionPending = false;
2997 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002998 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002999}
3000
Lloyd Pique58e24a32019-08-01 15:50:14 -07003001void SurfaceFlinger::commitTransactionLocked() {
3002 if (!mLayersPendingRemoval.isEmpty()) {
3003 // Notify removed layers now that they can't be drawn from
3004 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003005 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003006
3007 // Ensure any buffers set to display on any children are released.
3008 if (l->isRemovedFromCurrentState()) {
3009 l->latchAndReleaseBuffer();
3010 }
3011
3012 // If the layer has been removed and has no parent, then it will not be reachable
3013 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3014 // ensure we can copy its current to drawing state.
3015 if (!l->getParent()) {
3016 mOffscreenLayers.emplace(l.get());
3017 }
3018 }
3019 mLayersPendingRemoval.clear();
3020 }
3021
3022 // If this transaction is part of a window animation then the next frame
3023 // we composite should be considered an animation as well.
3024 mAnimCompositionPending = mAnimTransactionPending;
3025
3026 mDrawingState = mCurrentState;
3027 // clear the "changed" flags in current state
3028 mCurrentState.colorMatrixChanged = false;
3029
Edgar Arriaga844fa672020-01-16 14:21:42 -08003030 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003031 layer->commitChildList();
3032
3033 // If the layer can be reached when traversing mDrawingState, then the layer is no
3034 // longer offscreen. Remove the layer from the offscreenLayer set.
3035 if (mOffscreenLayers.count(layer)) {
3036 mOffscreenLayers.erase(layer);
3037 }
3038 });
3039
3040 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003041 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003042}
3043
chaviw74d90ad2019-04-26 14:45:26 -07003044void SurfaceFlinger::commitOffscreenLayers() {
3045 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003046 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003047 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3048 if (!trFlags) return;
3049
3050 layer->doTransaction(0);
3051 layer->commitChildList();
3052 });
3053 }
3054}
3055
Chia-I Wuab0c3192017-08-01 11:29:00 -07003056void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003057 for (const auto& [token, displayDevice] : mDisplays) {
3058 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003059 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003060 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003061 }
3062 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003063}
3064
Dan Stoza6b9454d2014-11-07 16:00:59 -08003065bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066{
Ady Abraham09bd3922019-04-08 10:44:56 -07003067 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003068 ALOGV("handlePageFlip");
3069
Brian Andersond6927fb2016-07-23 23:37:30 -07003070 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071
Mathias Agopian4fec8732012-06-29 14:12:52 -07003072 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003073 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003074 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003075
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003076 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3077
Eric Penner51c59cd2014-07-28 19:51:58 -07003078 // Store the set of layers that need updates. This set must not change as
3079 // buffers are being latched, as this could result in a deadlock.
3080 // Example: Two producers share the same command stream and:
3081 // 1.) Layer 0 is latched
3082 // 2.) Layer 0 gets a new frame
3083 // 2.) Layer 1 gets a new frame
3084 // 3.) Layer 1 is latched.
3085 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3086 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003087 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003088 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003089 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003090 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003091 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003092 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003093 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003094 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003095 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003096 } else {
3097 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003098 }
Robert Carr2047fae2016-11-28 14:09:09 -08003099 });
3100
chaviw49a108c2019-08-12 11:23:06 -07003101 // The client can continue submitting buffers for offscreen layers, but they will not
3102 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3103 // layers to ensure dequeueBuffer doesn't block indefinitely.
3104 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003105 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003106 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3107 }
3108
Lloyd Piquef2c79392018-12-20 16:23:33 -08003109 if (!mLayersWithQueuedFrames.empty()) {
3110 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3111 // writes to Layer current state. See also b/119481871
3112 Mutex::Autolock lock(mStateLock);
3113
3114 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003115 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003116 mLayersPendingRefresh.push_back(layer);
3117 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003118 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003119 if (layer->isBufferLatched()) {
3120 newDataLatched = true;
3121 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003122 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003123 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003124
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003125 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003126
3127 // If we will need to wake up at some time in the future to deal with a
3128 // queued frame that shouldn't be displayed during this vsync period, wake
3129 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003130 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003131 signalLayerUpdate();
3132 }
3133
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003134 // enter boot animation on first buffer latch
3135 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3136 ALOGI("Enter boot animation");
3137 mBootStage = BootStage::BOOTANIMATION;
3138 }
3139
Edgar Arriaga844fa672020-01-16 14:21:42 -08003140 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003141
Dan Stoza6b9454d2014-11-07 16:00:59 -08003142 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003143 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003144}
3145
Mathias Agopianad456f92011-01-13 17:53:01 -08003146void SurfaceFlinger::invalidateHwcGeometry()
3147{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003148 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003149}
3150
Robert Carrc0df3122019-04-11 13:18:21 -07003151status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3152 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3153 const sp<IBinder>& parentHandle,
3154 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003155 // add this layer to the current state list
3156 {
3157 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003158 sp<Layer> parent;
3159 if (parentHandle != nullptr) {
3160 parent = fromHandle(parentHandle);
3161 if (parent == nullptr) {
3162 return NAME_NOT_FOUND;
3163 }
3164 } else {
3165 parent = parentLayer;
3166 }
3167
Ady Abraham0a525092020-03-03 12:51:24 -08003168 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003169 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003170 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003171 return NO_MEMORY;
3172 }
Robert Carrc0df3122019-04-11 13:18:21 -07003173
3174 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3175
Robert Carrb89ea9d2018-12-10 13:01:14 -08003176 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003177 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003178 } else if (parent == nullptr) {
3179 lbc->onRemovedFromCurrentState();
3180 } else if (parent->isRemovedFromCurrentState()) {
3181 parent->addChild(lbc);
3182 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003183 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003184 parent->addChild(lbc);
3185 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003186
Yiwei Zhang243b3782018-05-15 17:40:04 -07003187 if (gbc != nullptr) {
3188 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3189 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3190 mMaxGraphicBufferProducerListSize,
3191 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3192 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003193 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003194 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003195 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003196 }
3197
Mathias Agopian96f08192010-06-02 23:28:45 -07003198 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003199 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003200
Dan Stoza7d89d062015-04-30 13:29:25 -07003201 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003202}
3203
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003204uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003205 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003206}
3207
Mathias Agopian3f844832013-08-07 21:24:32 -07003208uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003209 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210}
3211
Mathias Agopian3f844832013-08-07 21:24:32 -07003212uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003213 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003214}
3215
3216uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003217 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003218 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003219 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003221 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222 }
3223 return old;
3224}
3225
Marissa Wall713b63f2018-10-17 15:42:43 -07003226bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003227 // to prevent onHandleDestroyed from being called while the lock is held,
3228 // we must keep a copy of the transactions (specifically the composer
3229 // states) around outside the scope of the lock
3230 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003231 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003232 {
3233 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003234
Valerie Haufce31b82019-04-30 16:41:14 -07003235 auto it = mTransactionQueues.begin();
3236 while (it != mTransactionQueues.end()) {
3237 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003238
Valerie Haufce31b82019-04-30 16:41:14 -07003239 while (!transactionQueue.empty()) {
3240 const auto& transaction = transactionQueue.front();
3241 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003242 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003243 transaction.states)) {
3244 setTransactionFlags(eTransactionFlushNeeded);
3245 break;
3246 }
3247 transactions.push_back(transaction);
3248 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3249 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003250 transaction.buffer, transaction.postTime,
3251 transaction.privileged, transaction.hasListenerCallbacks,
3252 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003253 transactionQueue.pop();
3254 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003255 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003256
Valerie Haufce31b82019-04-30 16:41:14 -07003257 if (transactionQueue.empty()) {
3258 it = mTransactionQueues.erase(it);
3259 mTransactionCV.broadcast();
3260 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003261 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003262 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003263 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003264 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003265 return flushedATransaction;
3266}
3267
3268bool SurfaceFlinger::transactionFlushNeeded() {
3269 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003270}
3271
chaviwca27f252018-02-06 16:46:39 -08003272
Marissa Wall17b4e452018-12-26 16:32:34 -08003273bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003274 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003275 const Vector<ComposerState>& states) {
Ady Abraham0ed31c92020-04-16 11:48:45 -07003276 if (!useCachedExpectedPresentTime) populateExpectedPresentTime(systemTime());
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003277
3278 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003279 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3280 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3281 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3282 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3283 return false;
3284 }
3285
Marissa Wall713b63f2018-10-17 15:42:43 -07003286 for (const ComposerState& state : states) {
3287 const layer_state_t& s = state.state;
3288 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3289 continue;
3290 }
3291 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003292 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003293 }
3294 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003295 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003296}
3297
Valerie Hau9dab9732019-08-20 09:29:25 -07003298void SurfaceFlinger::setTransactionState(
3299 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3300 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3301 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3302 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003303 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003304
Valerie Haubc6ddb12019-03-08 11:10:15 -08003305 const int64_t postTime = systemTime();
3306
Robert Carr14167e02019-02-13 13:50:55 -08003307 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3308
Mathias Agopian698c0872011-06-28 19:09:31 -07003309 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003310
Marissa Wall713b63f2018-10-17 15:42:43 -07003311 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003312 auto itr = mTransactionQueues.find(applyToken);
3313 // if this is an animation frame, wait until prior animation frame has
3314 // been applied by SF
3315 if (flags & eAnimation) {
3316 while (itr != mTransactionQueues.end()) {
3317 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3318 if (CC_UNLIKELY(err != NO_ERROR)) {
3319 ALOGW_IF(err == TIMED_OUT,
3320 "setTransactionState timed out "
3321 "waiting for animation frame to apply");
3322 break;
3323 }
3324 itr = mTransactionQueues.find(applyToken);
3325 }
3326 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003327
3328 // Expected present time is computed and cached on invalidate, so it may be stale.
3329 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3330 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003331 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003332 uncacheBuffer, postTime, privileged,
3333 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003334 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003335 return;
3336 }
3337
Valerie Haubc6ddb12019-03-08 11:10:15 -08003338 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003339 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3340 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003341}
3342
Valerie Hau9dab9732019-08-20 09:29:25 -07003343void SurfaceFlinger::applyTransactionState(
3344 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3345 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3346 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3347 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3348 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003349 uint32_t transactionFlags = 0;
3350
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003351 if (flags & eAnimation) {
3352 // For window updates that are part of an animation we must wait for
3353 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003354 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003355 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003356 if (CC_UNLIKELY(err != NO_ERROR)) {
3357 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003358 // caller after a few seconds.
3359 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3360 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003361 mAnimTransactionPending = false;
3362 break;
3363 }
3364 }
3365 }
3366
chaviwca27f252018-02-06 16:46:39 -08003367 for (const DisplayState& display : displays) {
3368 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003369 }
3370
Valerie Hau9dab9732019-08-20 09:29:25 -07003371 // start and end registration for listeners w/ no surface so they can get their callback. Note
3372 // that listeners with SurfaceControls will start registration during setClientStateLocked
3373 // below.
3374 for (const auto& listener : listenerCallbacks) {
3375 mTransactionCompletedThread.startRegistration(listener);
3376 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003377 }
3378
Valerie Hau9dab9732019-08-20 09:29:25 -07003379 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003380 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003381 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003382 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3383 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003384 }
3385
Valerie Hau9dab9732019-08-20 09:29:25 -07003386 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003387 mTransactionCompletedThread.endRegistration(listenerCallback);
3388 }
3389
Marissa Walle2ffb422018-10-12 11:33:52 -07003390 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003391 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003392 mTransactionCompletedThread.sendCallbacks();
3393 }
3394 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003395
chaviw273171b2018-12-26 11:46:30 -08003396 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3397
Marissa Wall947d34e2019-03-29 14:03:53 -07003398 if (uncacheBuffer.isValid()) {
3399 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003400 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003401 }
3402
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003403 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3404 // anyway. This can be used as a flush mechanism for previous async transactions.
3405 // Empty animation transaction can be used to simulate back-pressure, so also force a
3406 // transaction for empty animation transactions.
3407 if (transactionFlags == 0 &&
3408 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003409 transactionFlags = eTransactionNeeded;
3410 }
3411
Marissa Wall06255332019-03-27 13:48:27 -07003412 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3413 // so we don't have to wake up again next frame to preform an uneeded traversal.
3414 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3415 transactionFlags = transactionFlags & (~eTraversalNeeded);
3416 mTraversalNeededMainThread = true;
3417 }
3418
Mathias Agopian386aa982011-11-07 21:58:03 -08003419 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003420 if (mInterceptor->isEnabled()) {
3421 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003422 }
Irvel468051e2016-06-13 16:44:44 -07003423
Mathias Agopian386aa982011-11-07 21:58:03 -08003424 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003425 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3426 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003427 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003428
3429 // if this is a synchronous transaction, wait for it to take effect
3430 // before returning.
3431 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003432 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003433 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003434 if (flags & eAnimation) {
3435 mAnimTransactionPending = true;
3436 }
chaviw4fe36852019-04-15 16:25:49 -07003437 if (mPendingInputWindowCommands.syncInputWindows) {
3438 mPendingSyncInputWindows = true;
3439 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003440
3441 // applyTransactionState can be called by either the main SF thread or by
3442 // another process through setTransactionState. While a given process may wish
3443 // to wait on synchronous transactions, the main SF thread should never
3444 // be blocked. Therefore, we only wait if isMainThread is false.
3445 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003446 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3447 if (CC_UNLIKELY(err != NO_ERROR)) {
3448 // just in case something goes wrong in SF, return to the
3449 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003450 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3451 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003452 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003453 break;
3454 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003455 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003456 }
3457}
3458
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003459uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3460 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3461 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003462
Mathias Agopiane57f2922012-08-09 16:29:12 -07003463 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003464 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3465
3466 const uint32_t what = s.what;
3467 if (what & DisplayState::eSurfaceChanged) {
3468 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3469 state.surface = s.surface;
3470 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003471 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003472 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003473 if (what & DisplayState::eLayerStackChanged) {
3474 if (state.layerStack != s.layerStack) {
3475 state.layerStack = s.layerStack;
3476 flags |= eDisplayTransactionNeeded;
3477 }
3478 }
3479 if (what & DisplayState::eDisplayProjectionChanged) {
3480 if (state.orientation != s.orientation) {
3481 state.orientation = s.orientation;
3482 flags |= eDisplayTransactionNeeded;
3483 }
3484 if (state.frame != s.frame) {
3485 state.frame = s.frame;
3486 flags |= eDisplayTransactionNeeded;
3487 }
3488 if (state.viewport != s.viewport) {
3489 state.viewport = s.viewport;
3490 flags |= eDisplayTransactionNeeded;
3491 }
3492 }
3493 if (what & DisplayState::eDisplaySizeChanged) {
3494 if (state.width != s.width) {
3495 state.width = s.width;
3496 flags |= eDisplayTransactionNeeded;
3497 }
3498 if (state.height != s.height) {
3499 state.height = s.height;
3500 flags |= eDisplayTransactionNeeded;
3501 }
3502 }
3503
Mathias Agopiane57f2922012-08-09 16:29:12 -07003504 return flags;
3505}
3506
Steven Thomasd4071902020-03-24 16:02:53 -07003507bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003508 IPCThreadState* ipc = IPCThreadState::self();
3509 const int pid = ipc->getCallingPid();
3510 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003511 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003512 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3513 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003514 return false;
3515 }
3516 return true;
3517}
3518
Marissa Wall3dad52d2019-03-22 14:03:19 -07003519uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003520 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3521 bool privileged,
3522 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003523 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003524
Valerie Hau9dab9732019-08-20 09:29:25 -07003525 for (auto& listener : s.listeners) {
3526 // note that startRegistration will not re-register if the listener has
3527 // already be registered for a prior surface control
3528 mTransactionCompletedThread.startRegistration(listener);
3529 listenerCallbacks.insert(listener);
3530 }
3531
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003532 sp<Layer> layer = nullptr;
3533 if (s.surface) {
3534 layer = fromHandle(s.surface);
3535 } else {
3536 // The client may provide us a null handle. Treat it as if the layer was removed.
3537 ALOGW("Attempt to set client state with a null layer handle");
3538 }
chaviw8b3871a2017-11-01 17:41:01 -07003539 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003540 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003541 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003542 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003543 }
chaviw8b3871a2017-11-01 17:41:01 -07003544 return 0;
3545 }
3546
chaviw8b3871a2017-11-01 17:41:01 -07003547 uint32_t flags = 0;
3548
Garfield Tan8a3083e2018-12-03 13:21:07 -08003549 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003550
3551 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3552 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003553 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003554 layer->pushPendingState();
3555 }
3556
Valerie Hau871d6352020-01-29 08:44:02 -08003557 // Only set by BLAST adapter layers
3558 if (what & layer_state_t::eProducerDisconnect) {
3559 layer->onDisconnect();
3560 }
3561
chaviw8b3871a2017-11-01 17:41:01 -07003562 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003563 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003564 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003565 }
chaviw8b3871a2017-11-01 17:41:01 -07003566 }
3567 if (what & layer_state_t::eLayerChanged) {
3568 // NOTE: index needs to be calculated before we update the state
3569 const auto& p = layer->getParent();
3570 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003571 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003572 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003573 mCurrentState.layersSortedByZ.removeAt(idx);
3574 mCurrentState.layersSortedByZ.add(layer);
3575 // we need traversal (state changed)
3576 // AND transaction (list changed)
3577 flags |= eTransactionNeeded|eTraversalNeeded;
3578 }
chaviw8b3871a2017-11-01 17:41:01 -07003579 } else {
3580 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003581 flags |= eTransactionNeeded|eTraversalNeeded;
3582 }
3583 }
chaviw8b3871a2017-11-01 17:41:01 -07003584 }
3585 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003586 // NOTE: index needs to be calculated before we update the state
3587 const auto& p = layer->getParent();
3588 if (p == nullptr) {
3589 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3590 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3591 mCurrentState.layersSortedByZ.removeAt(idx);
3592 mCurrentState.layersSortedByZ.add(layer);
3593 // we need traversal (state changed)
3594 // AND transaction (list changed)
3595 flags |= eTransactionNeeded|eTraversalNeeded;
3596 }
3597 } else {
3598 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3599 flags |= eTransactionNeeded|eTraversalNeeded;
3600 }
chaviw8b3871a2017-11-01 17:41:01 -07003601 }
3602 }
3603 if (what & layer_state_t::eSizeChanged) {
3604 if (layer->setSize(s.w, s.h)) {
3605 flags |= eTraversalNeeded;
3606 }
3607 }
3608 if (what & layer_state_t::eAlphaChanged) {
3609 if (layer->setAlpha(s.alpha))
3610 flags |= eTraversalNeeded;
3611 }
3612 if (what & layer_state_t::eColorChanged) {
3613 if (layer->setColor(s.color))
3614 flags |= eTraversalNeeded;
3615 }
Peiyong Lind3788632018-09-18 16:01:31 -07003616 if (what & layer_state_t::eColorTransformChanged) {
3617 if (layer->setColorTransform(s.colorTransform)) {
3618 flags |= eTraversalNeeded;
3619 }
3620 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003621 if (what & layer_state_t::eBackgroundColorChanged) {
3622 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3623 flags |= eTraversalNeeded;
3624 }
3625 }
chaviw8b3871a2017-11-01 17:41:01 -07003626 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003627 // TODO: b/109894387
3628 //
3629 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3630 // rotation. To see the problem observe that if we have a square parent, and a child
3631 // of the same size, then we rotate the child 45 degrees around it's center, the child
3632 // must now be cropped to a non rectangular 8 sided region.
3633 //
3634 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3635 // private API, and the WindowManager only uses rotation in one case, which is on a top
3636 // level layer in which cropping is not an issue.
3637 //
3638 // However given that abuse of rotation matrices could lead to surfaces extending outside
3639 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3640 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3641 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003642 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003643 flags |= eTraversalNeeded;
3644 }
3645 if (what & layer_state_t::eTransparentRegionChanged) {
3646 if (layer->setTransparentRegionHint(s.transparentRegion))
3647 flags |= eTraversalNeeded;
3648 }
3649 if (what & layer_state_t::eFlagsChanged) {
3650 if (layer->setFlags(s.flags, s.mask))
3651 flags |= eTraversalNeeded;
3652 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003653 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003654 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003655 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003656 if (what & layer_state_t::eCornerRadiusChanged) {
3657 if (layer->setCornerRadius(s.cornerRadius))
3658 flags |= eTraversalNeeded;
3659 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003660 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003661 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3662 }
chaviw8b3871a2017-11-01 17:41:01 -07003663 if (what & layer_state_t::eLayerStackChanged) {
3664 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3665 // We only allow setting layer stacks for top level layers,
3666 // everything else inherits layer stack from its parent.
3667 if (layer->hasParent()) {
3668 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003669 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003670 } else if (idx < 0) {
3671 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003672 "that also does not appear in the top level layer list. Something"
3673 " has gone wrong.",
3674 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003675 } else if (layer->setLayerStack(s.layerStack)) {
3676 mCurrentState.layersSortedByZ.removeAt(idx);
3677 mCurrentState.layersSortedByZ.add(layer);
3678 // we need traversal (state changed)
3679 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003680 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003681 }
3682 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003683 if (what & layer_state_t::eDeferTransaction_legacy) {
3684 if (s.barrierHandle_legacy != nullptr) {
3685 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3686 } else if (s.barrierGbp_legacy != nullptr) {
3687 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003688 if (authenticateSurfaceTextureLocked(gbp)) {
3689 const auto& otherLayer =
3690 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003691 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003692 } else {
3693 ALOGE("Attempt to defer transaction to to an"
3694 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003695 }
3696 }
chaviw8b3871a2017-11-01 17:41:01 -07003697 // We don't trigger a traversal here because if no other state is
3698 // changed, we don't want this to cause any more work
3699 }
chaviw8b3871a2017-11-01 17:41:01 -07003700 if (what & layer_state_t::eReparentChildren) {
3701 if (layer->reparentChildren(s.reparentHandle)) {
3702 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003703 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003704 }
chaviw8b3871a2017-11-01 17:41:01 -07003705 if (what & layer_state_t::eDetachChildren) {
3706 layer->detachChildren();
3707 }
3708 if (what & layer_state_t::eOverrideScalingModeChanged) {
3709 layer->setOverrideScalingMode(s.overrideScalingMode);
3710 // We don't trigger a traversal here because if no other state is
3711 // changed, we don't want this to cause any more work
3712 }
Marissa Wall61c58622018-07-18 10:12:20 -07003713 if (what & layer_state_t::eTransformChanged) {
3714 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3715 }
3716 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3717 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3718 flags |= eTraversalNeeded;
3719 }
3720 if (what & layer_state_t::eCropChanged) {
3721 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3722 }
Marissa Wall861616d2018-10-22 12:52:23 -07003723 if (what & layer_state_t::eFrameChanged) {
3724 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3725 }
Marissa Wall61c58622018-07-18 10:12:20 -07003726 if (what & layer_state_t::eAcquireFenceChanged) {
3727 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3728 }
3729 if (what & layer_state_t::eDataspaceChanged) {
3730 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3731 }
3732 if (what & layer_state_t::eHdrMetadataChanged) {
3733 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3734 }
3735 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3736 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3737 }
3738 if (what & layer_state_t::eApiChanged) {
3739 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3740 }
3741 if (what & layer_state_t::eSidebandStreamChanged) {
3742 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3743 }
Robert Carr720e5062018-07-30 17:45:14 -07003744 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003745 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003746 layer->setInputInfo(s.inputInfo);
3747 flags |= eTraversalNeeded;
3748 } else {
3749 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3750 }
Robert Carr720e5062018-07-30 17:45:14 -07003751 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003752 if (what & layer_state_t::eMetadataChanged) {
3753 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3754 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003755 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3756 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3757 flags |= eTraversalNeeded;
3758 }
3759 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003760 if (what & layer_state_t::eShadowRadiusChanged) {
3761 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3762 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003763 if (what & layer_state_t::eFrameRateSelectionPriority) {
3764 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3765 flags |= eTraversalNeeded;
3766 }
3767 }
Steven Thomas3172e202020-01-06 19:25:30 -08003768 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003769 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3770 "SurfaceFlinger::setClientStateLocked") &&
3771 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3772 Layer::FrameRate::convertCompatibility(
3773 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003774 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003775 }
Steven Thomas3172e202020-01-06 19:25:30 -08003776 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003777 // This has to happen after we reparent children because when we reparent to null we remove
3778 // child layers from current state and remove its relative z. If the children are reparented in
3779 // the same transaction, then we have to make sure we reparent the children first so we do not
3780 // lose its relative z order.
3781 if (what & layer_state_t::eReparent) {
3782 bool hadParent = layer->hasParent();
3783 if (layer->reparent(s.parentHandleForChild)) {
3784 if (!hadParent) {
3785 mCurrentState.layersSortedByZ.remove(layer);
3786 }
3787 flags |= eTransactionNeeded | eTraversalNeeded;
3788 }
3789 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003790 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003791 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3792 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003793 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3794 }
3795 }
Marissa Wall78b72202019-03-15 14:58:34 -07003796 bool bufferChanged = what & layer_state_t::eBufferChanged;
3797 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3798 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003799 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003800 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003801 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3802 if (success) {
3803 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3804 success = ClientCache::getInstance()
3805 .registerErasedRecipient(s.cachedBuffer,
3806 wp<ClientCache::ErasedRecipient>(this));
3807 if (!success) {
3808 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3809 }
3810 }
Marissa Wall78b72202019-03-15 14:58:34 -07003811 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003812 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003813 } else if (bufferChanged) {
3814 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003815 }
Marissa Wall78b72202019-03-15 14:58:34 -07003816 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003817 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3818 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003819 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003820 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003821 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003822 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3823 // Do not put anything that updates layer state or modifies flags after
3824 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003825 return flags;
3826}
3827
chaviw273171b2018-12-26 11:46:30 -08003828uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3829 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003830 if (inputWindowCommands.syncInputWindows) {
3831 flags |= eTraversalNeeded;
3832 }
3833
Vishnu Nairec0ab382019-02-13 15:32:56 -08003834 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003835 return flags;
3836}
3837
chaviwfe94a222019-08-21 13:52:59 -07003838status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3839 sp<IBinder>* outHandle) {
3840 if (!mirrorFromHandle) {
3841 return NAME_NOT_FOUND;
3842 }
3843
3844 sp<Layer> mirrorLayer;
3845 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003846 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003847
3848 {
3849 Mutex::Autolock _l(mStateLock);
3850 mirrorFrom = fromHandle(mirrorFromHandle);
3851 if (!mirrorFrom) {
3852 return NAME_NOT_FOUND;
3853 }
3854
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003855 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3856 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003857 if (result != NO_ERROR) {
3858 return result;
3859 }
3860
3861 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3862 }
3863
3864 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3865}
3866
Marissa Wall2d814fb2019-04-09 18:52:57 +00003867status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3868 uint32_t h, PixelFormat format, uint32_t flags,
3869 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003870 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003871 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3872 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003873 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003874 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003875 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003876 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003877 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003878
Robert Carrc0df3122019-04-11 13:18:21 -07003879 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3880 "Expected only one of parentLayer or parentHandle to be non-null. "
3881 "Programmer error?");
3882
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003883 status_t result = NO_ERROR;
3884
3885 sp<Layer> layer;
3886
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003887 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003888
Evan Roskya1f1e152019-01-24 16:17:46 -08003889 bool primaryDisplayOnly = false;
3890
3891 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3892 // TODO b/64227542
3893 if (metadata.has(METADATA_WINDOW_TYPE)) {
3894 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3895 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003896 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003897 primaryDisplayOnly = true;
3898 }
3899 }
3900
Mathias Agopian3165cc22012-08-08 19:42:09 -07003901 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003902 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003903 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3904 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003905
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003906 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003907 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003908 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003909 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003910 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003911 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003912 // check if buffer size is set for color layer.
3913 if (w > 0 || h > 0) {
3914 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3915 int(w), int(h));
3916 return BAD_VALUE;
3917 }
3918
Vishnu Nairfa247b12020-02-11 08:58:26 -08003919 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3920 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003921 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003922 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003923 // check if buffer size is set for container layer.
3924 if (w > 0 || h > 0) {
3925 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3926 int(w), int(h));
3927 return BAD_VALUE;
3928 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003929 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3930 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003931 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003932 default:
3933 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003934 break;
3935 }
3936
Dan Stoza7d89d062015-04-30 13:29:25 -07003937 if (result != NO_ERROR) {
3938 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003939 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003940
Evan Roskya1f1e152019-01-24 16:17:46 -08003941 if (primaryDisplayOnly) {
3942 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003943 }
3944
Robert Carrb89ea9d2018-12-10 13:01:14 -08003945 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003946 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3947 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003948 if (result != NO_ERROR) {
3949 return result;
3950 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003951 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003952
3953 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003954 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003955}
3956
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003957std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3958 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003959
3960 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003961 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003962
Dan Stoza436ccf32018-06-21 12:10:12 -07003963 // Grab the state lock since we're accessing mCurrentState
3964 Mutex::Autolock lock(mStateLock);
3965
Cody Northropbc755282017-03-31 12:00:08 -06003966 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003967 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003968 while (matchFound) {
3969 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003970 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003971 if (layer->getName() == uniqueName) {
3972 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003973 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003974 }
3975 });
3976 }
3977
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003978 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003979 return uniqueName;
3980}
3981
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003982status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003983 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003984 LayerMetadata metadata, PixelFormat& format,
3985 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003986 sp<IGraphicBufferProducer>* gbp,
3987 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003988 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003989 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003990 case PIXEL_FORMAT_TRANSPARENT:
3991 case PIXEL_FORMAT_TRANSLUCENT:
3992 format = PIXEL_FORMAT_RGBA_8888;
3993 break;
3994 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003995 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003996 break;
3997 }
3998
chaviwb4c6e582019-08-16 14:35:07 -07003999 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004000 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004001 args.textureName = getNewTexture();
4002 {
4003 // Grab the SF state lock during this since it's the only safe way to access
4004 // RenderEngine when creating a BufferLayerConsumer
4005 // TODO: Check if this lock is still needed here
4006 Mutex::Autolock lock(mStateLock);
4007 layer = getFactory().createBufferQueueLayer(args);
4008 }
4009
Marissa Wallfd668622018-05-10 10:21:13 -07004010 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004011 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004012 *handle = layer->getHandle();
4013 *gbp = layer->getProducer();
4014 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004015 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004016
Marissa Wallfd668622018-05-10 10:21:13 -07004017 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004018 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004019}
4020
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004021status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004022 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004023 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004024 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004025 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004026 args.displayDevice = getDefaultDisplayDevice();
4027 args.textureName = getNewTexture();
4028 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004029 if (outTransformHint) {
4030 *outTransformHint = layer->getTransformHint();
4031 }
Marissa Wall61c58622018-07-18 10:12:20 -07004032 *handle = layer->getHandle();
4033 *outLayer = layer;
4034
4035 return NO_ERROR;
4036}
4037
Vishnu Nairfa247b12020-02-11 08:58:26 -08004038status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4039 uint32_t h, uint32_t flags, LayerMetadata metadata,
4040 sp<IBinder>* handle, sp<Layer>* outLayer) {
4041 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004042 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004043 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004044 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004045}
4046
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004047status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004048 uint32_t w, uint32_t h, uint32_t flags,
4049 LayerMetadata metadata, sp<IBinder>* handle,
4050 sp<Layer>* outLayer) {
4051 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004052 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004053 *handle = (*outLayer)->getHandle();
4054 return NO_ERROR;
4055}
4056
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004057void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004058 mLayersPendingRemoval.add(layer);
4059 mLayersRemoved = true;
4060 setTransactionFlags(eTransactionNeeded);
4061}
4062
Robert Carr695d5282018-12-18 15:27:58 -08004063void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004064{
Robert Carr2e102c92018-10-23 12:11:15 -07004065 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004066 // If a layer has a parent, we allow it to out-live it's handle
4067 // with the idea that the parent holds a reference and will eventually
4068 // be cleaned up. However no one cleans up the top-level so we do so
4069 // here.
4070 if (layer->getParent() == nullptr) {
4071 mCurrentState.layersSortedByZ.remove(layer);
4072 }
4073 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004074
4075 auto it = mLayersByLocalBinderToken.begin();
4076 while (it != mLayersByLocalBinderToken.end()) {
4077 if (it->second == layer) {
4078 it = mLayersByLocalBinderToken.erase(it);
4079 } else {
4080 it++;
4081 }
4082 }
4083
Robert Carr695d5282018-12-18 15:27:58 -08004084 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004085}
4086
Mathias Agopianb60314a2012-04-10 22:09:54 -07004087// ---------------------------------------------------------------------------
4088
Andy McFadden13a082e2012-08-24 10:16:42 -07004089void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004090 const auto display = getDefaultDisplayDeviceLocked();
4091 if (!display) return;
4092
4093 const sp<IBinder> token = display->getDisplayToken().promote();
4094 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004095
Jesse Hall01e29052013-02-19 16:13:35 -08004096 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004097 Vector<ComposerState> state;
4098 Vector<DisplayState> displays;
4099 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004100 d.what = DisplayState::eDisplayProjectionChanged |
4101 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004102 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004103 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004104 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004105 d.frame.makeInvalid();
4106 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004107 d.width = 0;
4108 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004109 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004110 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4111 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004112
Peiyong Lin65248e02020-04-18 21:15:07 -07004113 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004114
Dominik Laskowski83b88212018-12-11 13:34:06 -08004115 const nsecs_t vsyncPeriod = getVsyncPeriod();
4116 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004117
Brian Andersond0010582017-03-07 13:20:31 -08004118 // Use phase of 0 since phase is not known.
4119 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004120 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004121 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004122}
4123
4124void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004125 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004126 postMessageAsync(
4127 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004128}
4129
Peiyong Line9d809e2020-04-14 13:10:48 -07004130void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, hal::Vsync enabled) {
Ady Abraham27c70212019-06-11 10:52:26 -07004131 if (mHWCVsyncState != enabled) {
4132 getHwComposer().setVsyncEnabled(displayId, enabled);
4133 mHWCVsyncState = enabled;
4134 }
4135}
4136
Peiyong Lin65248e02020-04-18 21:15:07 -07004137void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004138 if (display->isVirtual()) {
4139 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004140 return;
4141 }
4142
Dominik Laskowski075d3172018-05-24 15:50:06 -07004143 const auto displayId = display->getId();
4144 LOG_ALWAYS_FATAL_IF(!displayId);
4145
Dominik Laskowski34157762018-10-31 13:07:19 -07004146 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004147
Peiyong Lin65248e02020-04-18 21:15:07 -07004148 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004149 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004150 return;
4151 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004152
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004153 display->setPowerMode(mode);
4154
Lloyd Pique4dccc412018-01-22 17:21:36 -08004155 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004156 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004157 }
4158
Peiyong Lin65248e02020-04-18 21:15:07 -07004159 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004160 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4161 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4162 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004163 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004164 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004165 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004166 mScheduler->onScreenAcquired(mAppConnectionHandle);
4167 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004168 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004169
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004170 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004171 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004172 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004173 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004174 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004175 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4176 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004177 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004178 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004179 mScheduler->disableHardwareVsync(true);
4180 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004181 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004182
Ady Abraham27c70212019-06-11 10:52:26 -07004183 // Make sure HWVsync is disabled before turning off the display
Peiyong Line9d809e2020-04-14 13:10:48 -07004184 setVsyncEnabledInHWC(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004185
Dominik Laskowski075d3172018-05-24 15:50:06 -07004186 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004187 mVisibleRegionsDirty = true;
4188 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004189 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004190 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004191 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004192 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004193 mScheduler->onScreenAcquired(mAppConnectionHandle);
4194 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004195 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004196 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004197 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004198 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004199 mScheduler->disableHardwareVsync(true);
4200 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004201 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004202 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004203 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004204 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004205 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004206 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004207
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004208 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004209 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004210 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004211 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004212 }
4213
Dominik Laskowski34157762018-10-31 13:07:19 -07004214 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004215}
4216
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004217void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004218 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004219 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004220 if (!display) {
4221 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4222 displayToken.get());
4223 } else if (display->isVirtual()) {
4224 ALOGW("Attempt to set power mode %d for virtual display", mode);
4225 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004226 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004227 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004228 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004229}
4230
4231// ---------------------------------------------------------------------------
4232
Dominik Laskowskic2867142019-01-21 11:33:38 -08004233status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4234 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004235 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004236
Mathias Agopianbd115332013-04-18 16:41:04 -07004237 IPCThreadState* ipc = IPCThreadState::self();
4238 const int pid = ipc->getCallingPid();
4239 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004240
Mathias Agopianbd115332013-04-18 16:41:04 -07004241 if ((uid != AID_SHELL) &&
4242 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004243 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4244 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004245 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004246 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004247 // (this would indicate SF is stuck, but we want to be able to
4248 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004249 status_t err = mStateLock.timedLock(s2ns(1));
4250 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004251 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004252 StringAppendF(&result,
4253 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4254 "(no locks held)\n",
4255 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004256 }
4257
Dominik Laskowskic2867142019-01-21 11:33:38 -08004258 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004259 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004260 {"--dispsync"s,
4261 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004262 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004263 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4264 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4265 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4266 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4267 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4268 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004269 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004270 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4271 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004272
Dominik Laskowskic2867142019-01-21 11:33:38 -08004273 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004274
Dominik Laskowski46470112019-08-02 13:13:11 -07004275 const auto it = dumpers.find(flag);
4276 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004277 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004278 } else if (!asProto) {
4279 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004280 }
4281
Mathias Agopian9795c422009-08-26 16:36:26 -07004282 if (locked) {
4283 mStateLock.unlock();
4284 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004285
Dominik Laskowski46470112019-08-02 13:13:11 -07004286 if (it == dumpers.end()) {
4287 const LayersProto layersProto = dumpProtoFromMainThread();
4288 if (asProto) {
4289 result.append(layersProto.SerializeAsString());
4290 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004291 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004292 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4293 result.append(LayerProtoParser::layerTreeToString(layerTree));
4294 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004295 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004296 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004297 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004298 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004299 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004300 return NO_ERROR;
4301}
4302
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004303status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4304 if (asProto && mTracing.isEnabled()) {
4305 mTracing.writeToFileAsync();
4306 }
4307
4308 return doDump(fd, DumpArgs(), asProto);
4309}
4310
Dominik Laskowskic2867142019-01-21 11:33:38 -08004311void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004312 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004313 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004314}
4315
Dominik Laskowskic2867142019-01-21 11:33:38 -08004316void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004317 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004318
Dominik Laskowskic2867142019-01-21 11:33:38 -08004319 if (args.size() > 1) {
4320 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004321 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004322 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004323 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004324 }
Robert Carr2047fae2016-11-28 14:09:09 -08004325 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004326 } else {
4327 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328 }
4329}
4330
Dominik Laskowskic2867142019-01-21 11:33:38 -08004331void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004332 const bool clearAll = args.size() < 2;
4333 const auto name = clearAll ? String8() : String8(args[1]);
4334
Edgar Arriaga844fa672020-01-16 14:21:42 -08004335 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004336 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004337 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004338 }
Robert Carr2047fae2016-11-28 14:09:09 -08004339 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004340
Svetoslavd85084b2014-03-20 10:28:31 -07004341 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004342}
4343
Dominik Laskowskic2867142019-01-21 11:33:38 -08004344void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4345 mTimeStats->parseArgs(asProto, args, result);
4346}
4347
Jamie Gennis6547ff42013-07-16 20:12:42 -07004348// This should only be called from the main thread. Otherwise it would need
4349// the lock and should use mCurrentState rather than mDrawingState.
4350void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004351 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004352 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004353 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004354
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004355 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004356}
4357
Yiwei Zhang5434a782018-12-05 18:06:32 -08004358void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004359 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004360
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004361 if (isLayerTripleBufferingDisabled())
4362 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004363
Yiwei Zhang5434a782018-12-05 18:06:32 -08004364 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4365 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4366 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4367 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4368 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4369 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004370 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004371}
4372
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004373void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004374 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004375
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004376 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004377 result.append("\n");
4378
Ady Abraham9e16a482019-12-03 17:19:41 -08004379 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004380 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004381 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004382 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004383
Steven Thomasd4071902020-03-24 16:02:53 -07004384 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004385 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004386 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004387 ", min: %.2f Hz, max: %.2f Hz",
Steven Thomasd4071902020-03-24 16:02:53 -07004388 policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004389 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4390 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004391 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4392 if (currentPolicy != policy) {
4393 StringAppendF(&result,
4394 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
4395 ", min: %.2f Hz, max: %.2f Hz\n\n",
4396 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
4397 currentPolicy.maxRefreshRate);
4398 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004399
Ana Krulecc2870422019-01-29 19:00:58 -08004400 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004401 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004402}
4403
Yiwei Zhang5434a782018-12-05 18:06:32 -08004404void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4405 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004406 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4407 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004408 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004409 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004410 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004411 }
David Sodman4a36e932017-11-07 14:29:47 -08004412 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004413 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004414 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004415 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4416 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004417}
4418
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004419void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4420 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004421 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4422 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004423 for (const auto& segment : history) {
4424 if (!segment.usedThirdBuffer) {
4425 stats.twoBufferTime += segment.totalTime;
4426 }
4427 if (segment.occupancyAverage < 1.0f) {
4428 stats.doubleBufferedTime += segment.totalTime;
4429 } else if (segment.occupancyAverage < 2.0f) {
4430 stats.tripleBufferedTime += segment.totalTime;
4431 }
4432 ++stats.numSegments;
4433 stats.totalTime += segment.totalTime;
4434 }
4435}
4436
Yiwei Zhang5434a782018-12-05 18:06:32 -08004437void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4438 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004439
4440 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4441 const size_t count = currentLayers.size();
4442 for (size_t i=0 ; i<count ; i++) {
4443 currentLayers[i]->dumpFrameEvents(result);
4444 }
4445}
4446
Yiwei Zhang5434a782018-12-05 18:06:32 -08004447void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004448 result.append("Buffering stats:\n");
4449 result.append(" [Layer name] <Active time> <Two buffer> "
4450 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004451 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004452 typedef std::tuple<std::string, float, float, float> BufferTuple;
4453 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004454 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004455 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004456 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004457 if (stats.numSegments == 0) {
4458 continue;
4459 }
4460 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4461 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4462 stats.totalTime;
4463 float doubleBufferRatio = static_cast<float>(
4464 stats.doubleBufferedTime) / stats.totalTime;
4465 float tripleBufferRatio = static_cast<float>(
4466 stats.tripleBufferedTime) / stats.totalTime;
4467 sorted.insert({activeTime, {name, twoBufferRatio,
4468 doubleBufferRatio, tripleBufferRatio}});
4469 }
4470 for (const auto& sortedPair : sorted) {
4471 float activeTime = sortedPair.first;
4472 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004473 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4474 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004475 }
4476 result.append("\n");
4477}
4478
Yiwei Zhang5434a782018-12-05 18:06:32 -08004479void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004480 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004481 const auto displayId = display->getId();
4482 if (!displayId) {
4483 continue;
4484 }
4485 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004486 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004487 continue;
4488 }
4489
Yiwei Zhang5434a782018-12-05 18:06:32 -08004490 StringAppendF(&result,
4491 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4492 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004493 uint8_t port;
4494 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004495 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004496 result.append("no identification data\n");
4497 continue;
4498 }
4499
4500 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004501 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004502 continue;
4503 }
4504
4505 const auto edid = parseEdid(data);
4506 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004507 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004508 continue;
4509 }
4510
Yiwei Zhang5434a782018-12-05 18:06:32 -08004511 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004512 result.append(edid->displayName.data(), edid->displayName.length());
4513 result.append("\"\n");
4514 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004515}
4516
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004517void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4518 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004519 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004520 uint8_t port;
4521 DisplayIdentificationData data;
4522
4523 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4524 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4525 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4526 }
4527}
4528
Yiwei Zhang5434a782018-12-05 18:06:32 -08004529void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004530 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004531 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4532 StringAppendF(&result, "DisplayColorSetting: %s\n",
4533 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004534
4535 // TODO: print out if wide-color mode is active or not
4536
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004537 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004538 const auto displayId = display->getId();
4539 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004540 continue;
4541 }
4542
Yiwei Zhang5434a782018-12-05 18:06:32 -08004543 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004544 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004545 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004546 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004547 }
4548
Lloyd Pique32cbe282018-10-19 13:09:22 -07004549 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004550 StringAppendF(&result, " Current color mode: %s (%d)\n",
4551 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004552 }
4553 result.append("\n");
4554}
4555
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004556LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4557 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
4558 const auto display = getDefaultDisplayDeviceLocked();
4559
chaviw1d044282017-09-27 12:19:28 -07004560 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004561 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004562 layer->writeToProto(layersProto, traceFlags, display);
chaviw08f3cb22020-01-13 13:17:21 -08004563 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004564
chaviw1d044282017-09-27 12:19:28 -07004565 return layersProto;
4566}
4567
Alec Mouri6b9e9912020-01-21 10:50:24 -08004568void SurfaceFlinger::dumpHwc(std::string& result) const {
4569 getHwComposer().dump(result);
4570}
4571
Vishnu Nair0f085c62019-08-30 08:49:12 -07004572void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4573 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4574 // it.
4575 LayerProto* rootProto = layersProto.add_layers();
4576 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4577 rootProto->set_id(offscreenRootLayerId);
4578 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004579 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004580
4581 for (Layer* offscreenLayer : mOffscreenLayers) {
4582 // Add layer as child of the fake root
4583 rootProto->add_children(offscreenLayer->sequence);
4584
4585 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004586 LayerProto* layerProto =
4587 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004588 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004589 }
4590}
4591
Vishnu Nair8406fd72019-07-30 11:29:31 -07004592LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4593 LayersProto layersProto;
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004594 postMessageSync(new LambdaMessage([&] { layersProto = dumpDrawingStateProto(traceFlags); }));
Vishnu Nair8406fd72019-07-30 11:29:31 -07004595 return layersProto;
4596}
4597
Vishnu Nair0f085c62019-08-30 08:49:12 -07004598void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4599 result.append("Offscreen Layers:\n");
4600 postMessageSync(new LambdaMessage([&]() {
4601 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004602 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004603 layer->dumpCallingUidPid(result);
4604 });
4605 }
4606 }));
4607}
4608
Dominik Laskowskic2867142019-01-21 11:33:38 -08004609void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4610 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004611 Colorizer colorizer(colorize);
4612
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004613 // figure out if we're stuck somewhere
4614 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004615 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004616 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4617
4618 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004619 * Dump library configuration.
4620 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004621
4622 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004623 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004624 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004625 appendSfConfigString(result);
4626 appendUiConfigString(result);
4627 appendGuiConfigString(result);
4628 result.append("\n");
4629
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004630 result.append("\nDisplay identification data:\n");
4631 dumpDisplayIdentificationData(result);
4632
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004633 result.append("\nWide-Color information:\n");
4634 dumpWideColorInfo(result);
4635
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004636 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004637 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004638 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004639 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004640 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004641
Andy McFadden41d67d72014-04-25 16:58:34 -07004642 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004643 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004644 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004645 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004646 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004647
Dan Stozab90cf072015-03-05 11:05:59 -08004648 dumpStaticScreenStats(result);
4649 result.append("\n");
4650
Alec Mouri40189b02019-03-05 15:07:54 -08004651 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4652 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4653 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004654
Dan Stozae77c7662016-05-13 11:37:28 -07004655 dumpBufferingStats(result);
4656
Andy McFadden4803b742012-09-24 19:07:20 -07004657 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004658 * Dump the visible layer list
4659 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004660 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004661 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004662 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4663 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004664 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004665
Chia-I Wu2f884132018-09-13 15:17:58 -07004666 {
Lloyd Pique207def92019-02-28 16:09:52 -08004667 StringAppendF(&result, "Composition layers\n");
4668 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004669 auto* compositionState = layer->getCompositionState();
4670 if (!compositionState) return;
4671
4672 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4673 layer->getDebugName() ? layer->getDebugName()
4674 : "<unknown>");
4675 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004676 });
4677 }
4678
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004679 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004680 * Dump Display state
4681 */
4682
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004683 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004684 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004685 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004686 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004687 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004688 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004689 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004690
4691 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004692 * Dump CompositionEngine state
4693 */
4694
4695 mCompositionEngine->dump(result);
4696
4697 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004698 * Dump SurfaceFlinger global state
4699 */
4700
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004701 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004702 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004703 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004704
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004705 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004706
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004707 DebugEGLImageTracker::getInstance()->dump(result);
4708
Dominik Laskowski075d3172018-05-24 15:50:06 -07004709 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004710 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4711 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004712 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4713 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004714 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004715 StringAppendF(&result,
4716 " transaction-flags : %08x\n"
4717 " gpu_to_cpu_unsupported : %d\n",
4718 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004719
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004720 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004721 displayId && getHwComposer().isConnected(*displayId)) {
4722 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004723 StringAppendF(&result,
4724 " refresh-rate : %f fps\n"
4725 " x-dpi : %f\n"
4726 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004727 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4728 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004729 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004730
Yiwei Zhang5434a782018-12-05 18:06:32 -08004731 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004732
Dan Stozae22aec72016-08-01 13:20:59 -07004733 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004734 * Tracing state
4735 */
4736 mTracing.dump(result);
4737 result.append("\n");
4738
4739 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004740 * HWC layer minidump
4741 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004742 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004743 const auto displayId = display->getId();
4744 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004745 continue;
4746 }
4747
Yiwei Zhang5434a782018-12-05 18:06:32 -08004748 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004749 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004750 const sp<DisplayDevice> displayDevice = display;
4751 mCurrentState.traverseInZOrder(
4752 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004753 result.append("\n");
4754 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004755
4756 /*
4757 * Dump HWComposer state
4758 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004759 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004760 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004761 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004762 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004763 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004764 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004765
4766 /*
4767 * Dump gralloc state
4768 */
4769 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4770 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004771
4772 /*
4773 * Dump VrFlinger state if in use.
4774 */
4775 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4776 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004777 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004778 result.append("\n");
4779 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004780
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004781 result.append(mTimeStats->miniDump());
4782 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004783}
4784
Chia-I Wu28f320b2018-05-03 11:02:56 -07004785void SurfaceFlinger::updateColorMatrixLocked() {
4786 mat4 colorMatrix;
4787 if (mGlobalSaturationFactor != 1.0f) {
4788 // Rec.709 luma coefficients
4789 float3 luminance{0.213f, 0.715f, 0.072f};
4790 luminance *= 1.0f - mGlobalSaturationFactor;
4791 mat4 saturationMatrix = mat4(
4792 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4793 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4794 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4795 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4796 );
4797 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4798 } else {
4799 colorMatrix = mClientColorMatrix * mDaltonizer();
4800 }
4801
4802 if (mCurrentState.colorMatrix != colorMatrix) {
4803 mCurrentState.colorMatrix = colorMatrix;
4804 mCurrentState.colorMatrixChanged = true;
4805 setTransactionFlags(eTransactionNeeded);
4806 }
4807}
4808
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004809status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004810#pragma clang diagnostic push
4811#pragma clang diagnostic error "-Wswitch-enum"
4812 switch (static_cast<ISurfaceComposerTag>(code)) {
4813 // These methods should at minimum make sure that the client requested
4814 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004815 case BOOT_FINISHED:
4816 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004817 case CREATE_DISPLAY:
4818 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004819 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004820 case GET_ANIMATION_FRAME_STATS:
4821 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004822 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004823 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004824 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004825 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4826 case SET_AUTO_LOW_LATENCY_MODE:
4827 case GET_GAME_CONTENT_TYPE_SUPPORT:
4828 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004829 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004830 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004831 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004832 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004833 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004834 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004835 case SET_GLOBAL_SHADOW_SETTINGS:
4836 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4837 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4838 // necessary permission dynamically. Don't use the permission cache for this check.
4839 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4840 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004841 IPCThreadState* ipc = IPCThreadState::self();
4842 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4843 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004844 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004845 }
Robert Carr1db73f62016-12-21 12:58:51 -08004846 return OK;
4847 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004848 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004849 IPCThreadState* ipc = IPCThreadState::self();
4850 const int pid = ipc->getCallingPid();
4851 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004852 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4853 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004854 return PERMISSION_DENIED;
4855 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004856 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004857 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004858 // Used by apps to hook Choreographer to SurfaceFlinger.
4859 case CREATE_DISPLAY_EVENT_CONNECTION:
4860 // The following calls are currently used by clients that do not
4861 // request necessary permissions. However, they do not expose any secret
4862 // information, so it is OK to pass them.
4863 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004864 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004865 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004866 case GET_PHYSICAL_DISPLAY_IDS:
4867 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004868 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004869 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004870 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004871 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004872 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004873 case GET_DISPLAY_STATS:
4874 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4875 // Calling setTransactionState is safe, because you need to have been
4876 // granted a reference to Client* and Handle* to do anything with it.
4877 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004878 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004879 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004880 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004881 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004882 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004883 // setFrameRate() is deliberately available for apps to call without any
4884 // special permissions.
4885 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004886 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4887 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004888 return OK;
4889 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004890 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004891 case CAPTURE_SCREEN:
4892 case ADD_REGION_SAMPLING_LISTENER:
4893 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004894 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004895 IPCThreadState* ipc = IPCThreadState::self();
4896 const int pid = ipc->getCallingPid();
4897 const int uid = ipc->getCallingUid();
4898 if ((uid != AID_GRAPHICS) &&
4899 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4900 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4901 return PERMISSION_DENIED;
4902 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004903 return OK;
4904 }
chaviw93df2ea2019-04-30 16:45:12 -07004905 case CAPTURE_SCREEN_BY_ID: {
4906 IPCThreadState* ipc = IPCThreadState::self();
4907 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004908 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004909 return OK;
4910 }
4911 return PERMISSION_DENIED;
4912 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004913 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004914
4915 // These codes are used for the IBinder protocol to either interrogate the recipient
4916 // side of the transaction for its canonical interface descriptor or to dump its state.
4917 // We let them pass by default.
4918 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4919 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4920 code == IBinder::SYSPROPS_TRANSACTION) {
4921 return OK;
4922 }
Ady Abraham07e54702020-04-16 15:05:37 -07004923 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004924 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004925 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004926 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4927 return OK;
4928 }
4929 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4930 return PERMISSION_DENIED;
4931#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004932}
4933
Ana Krulec13be8ad2018-08-21 02:43:56 +00004934status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4935 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004936 status_t credentialCheck = CheckTransactCodeCredentials(code);
4937 if (credentialCheck != OK) {
4938 return credentialCheck;
4939 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004940
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004941 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4942 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004943 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004944 IPCThreadState* ipc = IPCThreadState::self();
4945 const int uid = ipc->getCallingUid();
4946 if (CC_UNLIKELY(uid != AID_SYSTEM
4947 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004948 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004949 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004950 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004951 return PERMISSION_DENIED;
4952 }
4953 int n;
4954 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004955 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004956 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004957 return NO_ERROR;
4958 case 1002: // SHOW_UPDATES
4959 n = data.readInt32();
4960 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004961 invalidateHwcGeometry();
4962 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004963 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004964 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004965 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004966 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004967 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004968 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004969 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004970 setTransactionFlags(
4971 eTransactionNeeded|
4972 eDisplayTransactionNeeded|
4973 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004974 return NO_ERROR;
4975 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004976 case 1006:{ // send empty update
4977 signalRefresh();
4978 return NO_ERROR;
4979 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004980 case 1008: // toggle use of hw composer
4981 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004982 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004983 invalidateHwcGeometry();
4984 repaintEverything();
4985 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004986 case 1009: // toggle use of transform hint
4987 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004988 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004989 invalidateHwcGeometry();
4990 repaintEverything();
4991 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004992 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004993 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004994 reply->writeInt32(0);
4995 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004996 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004997 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004998 return NO_ERROR;
4999 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005000 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005001 if (!display) {
5002 return NAME_NOT_FOUND;
5003 }
5004
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005005 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005006 return NO_ERROR;
5007 }
5008 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005009 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005010 // daltonize
5011 n = data.readInt32();
5012 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005013 case 1:
5014 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5015 break;
5016 case 2:
5017 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5018 break;
5019 case 3:
5020 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5021 break;
5022 default:
5023 mDaltonizer.setType(ColorBlindnessType::None);
5024 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005025 }
5026 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005027 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005028 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005029 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005030 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005031
5032 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005033 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005034 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005035 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005036 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005037 // apply a color matrix
5038 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005039 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005040 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005041 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005042 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005043 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005044 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005045 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005046 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005047 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005048 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005049
5050 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5051 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005052 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005053 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5054 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5055 }
5056
Chia-I Wu28f320b2018-05-03 11:02:56 -07005057 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005058 return NO_ERROR;
5059 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005060 case 1016: { // Unused.
5061 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005062 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005063 case 1017: {
5064 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005065 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005066 return NO_ERROR;
5067 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005068 case 1018: { // Modify Choreographer's phase offset
5069 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005070 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005071 return NO_ERROR;
5072 }
5073 case 1019: { // Modify SurfaceFlinger's phase offset
5074 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005075 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005076 return NO_ERROR;
5077 }
Irvel468051e2016-06-13 16:44:44 -07005078 case 1020: { // Layer updates interceptor
5079 n = data.readInt32();
5080 if (n) {
5081 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005082 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005083 }
5084 else{
5085 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005086 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005087 }
5088 return NO_ERROR;
5089 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005090 case 1021: { // Disable HWC virtual displays
5091 n = data.readInt32();
5092 mUseHwcVirtualDisplays = !n;
5093 return NO_ERROR;
5094 }
Romain Guy0147a172017-06-01 13:53:56 -07005095 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005096 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005097 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005098
Chia-I Wu28f320b2018-05-03 11:02:56 -07005099 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005100 return NO_ERROR;
5101 }
Romain Guy54f154a2017-10-24 21:40:32 +01005102 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005103 int32_t colorMode;
5104
Chia-I Wu0d711262018-05-21 15:19:35 -07005105 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005106 if (data.readInt32(&colorMode) == NO_ERROR) {
5107 mForceColorMode = static_cast<ColorMode>(colorMode);
5108 }
Romain Guy54f154a2017-10-24 21:40:32 +01005109 invalidateHwcGeometry();
5110 repaintEverything();
5111 return NO_ERROR;
5112 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005113 // Deprecate, use 1030 to check whether the device is color managed.
5114 case 1024: {
5115 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005116 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005117 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005118 n = data.readInt32();
5119 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005120 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005121 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005122 reply->writeInt32(NO_ERROR);
5123 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005124 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005125 mTracingEnabledChanged = mTracing.disable();
5126 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005127 reply->writeInt32(mTracing.writeToFile());
5128 } else {
5129 reply->writeInt32(NO_ERROR);
5130 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005131 }
5132 return NO_ERROR;
5133 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005134 case 1026: { // Get layer tracing status
5135 reply->writeBool(mTracing.isEnabled());
5136 return NO_ERROR;
5137 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005138 // Is a DisplayColorSetting supported?
5139 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005140 const auto display = getDefaultDisplayDevice();
5141 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005142 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005143 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005144
5145 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5146 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005147 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005148 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005149 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005150 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005151 reply->writeBool(true);
5152 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005153 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005154 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005155 break;
5156 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005157 reply->writeBool(
5158 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005159 break;
5160 }
5161 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005162 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005163 // Is VrFlinger active?
5164 case 1028: {
5165 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005166 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005167 return NO_ERROR;
5168 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005169 // Set buffer size for SF tracing (value in KB)
5170 case 1029: {
5171 n = data.readInt32();
5172 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5173 ALOGW("Invalid buffer size: %d KB", n);
5174 reply->writeInt32(BAD_VALUE);
5175 return BAD_VALUE;
5176 }
5177
5178 ALOGD("Updating trace buffer to %d KB", n);
5179 mTracing.setBufferSize(n * 1024);
5180 reply->writeInt32(NO_ERROR);
5181 return NO_ERROR;
5182 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005183 // Is device color managed?
5184 case 1030: {
5185 reply->writeBool(useColorManagement);
5186 return NO_ERROR;
5187 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005188 // Override default composition data space
5189 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5190 // && adb shell stop zygote && adb shell start zygote
5191 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5192 // adb shell stop zygote && adb shell start zygote
5193 case 1031: {
5194 Mutex::Autolock _l(mStateLock);
5195 n = data.readInt32();
5196 if (n) {
5197 n = data.readInt32();
5198 if (n) {
5199 Dataspace dataspace = static_cast<Dataspace>(n);
5200 if (!validateCompositionDataspace(dataspace)) {
5201 return BAD_VALUE;
5202 }
5203 mDefaultCompositionDataspace = dataspace;
5204 }
5205 n = data.readInt32();
5206 if (n) {
5207 Dataspace dataspace = static_cast<Dataspace>(n);
5208 if (!validateCompositionDataspace(dataspace)) {
5209 return BAD_VALUE;
5210 }
5211 mWideColorGamutCompositionDataspace = dataspace;
5212 }
5213 } else {
5214 // restore composition data space.
5215 mDefaultCompositionDataspace = defaultCompositionDataspace;
5216 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5217 }
5218 return NO_ERROR;
5219 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005220 // Set trace flags
5221 case 1033: {
5222 n = data.readUint32();
5223 ALOGD("Updating trace flags to 0x%x", n);
5224 mTracing.setTraceFlags(n);
5225 reply->writeInt32(NO_ERROR);
5226 return NO_ERROR;
5227 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005228 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005229 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005230 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005231 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005232 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005233 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005234 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005235 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005236 } else {
5237 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005238 }
5239 return NO_ERROR;
5240 }
Ady Abraham34392f72019-04-10 11:29:27 -07005241 case 1035: {
5242 n = data.readInt32();
5243 mDebugDisplayConfigSetByBackdoor = false;
5244 if (n >= 0) {
5245 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005246 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005247 if (result != NO_ERROR) {
5248 return result;
5249 }
5250 mDebugDisplayConfigSetByBackdoor = true;
5251 }
5252 return NO_ERROR;
5253 }
Ady Abraham07e54702020-04-16 15:05:37 -07005254 case 1036: {
5255 if (data.readInt32() > 0) {
5256 status_t result =
5257 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5258 if (result != NO_ERROR) {
5259 return result;
5260 }
5261 } else {
5262 mDebugFrameRateFlexibilityToken = nullptr;
5263 }
5264 return NO_ERROR;
5265 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005266 }
5267 }
5268 return err;
5269}
5270
Steven Thomas6d8110b2017-08-31 18:24:21 -07005271void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005272 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005273 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005274}
5275
Ana Krulec7d1d6832018-12-27 11:10:09 -08005276void SurfaceFlinger::repaintEverythingForHWC() {
5277 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005278 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005279 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005280}
5281
Ady Abrahama09852a2020-02-20 14:23:42 -08005282void SurfaceFlinger::kernelTimerChanged(bool expired) {
5283 static bool updateOverlay =
5284 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5285 if (!updateOverlay || !mRefreshRateOverlay) return;
5286
5287 // Update the overlay on the main thread to avoid race conditions with
5288 // mRefreshRateConfigs->getCurrentRefreshRate()
5289 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5290 if (mRefreshRateOverlay) {
5291 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5292 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005293 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005294 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5295 if (mDesiredActiveConfigChanged) {
5296 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5297 mDesiredActiveConfig.configId);
5298 }
5299
5300 return mRefreshRateConfigs->getCurrentRefreshRate();
5301 }();
5302 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5303
5304 if (current != min) {
5305 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5306 mEventQueue->invalidate();
5307 }
5308 }
5309 }));
5310}
5311
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005312// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5313class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005314public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005315 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5316 ~WindowDisconnector() {
5317 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005318 }
5319
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005320private:
5321 ANativeWindow* mWindow;
5322 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005323};
5324
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005325status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005326 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005327 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5328 const Rect& sourceCrop, uint32_t reqWidth,
5329 uint32_t reqHeight, bool useIdentityTransform,
5330 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005331 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005332
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005333 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005334
Dominik Laskowski718f9602019-11-09 20:01:35 -08005335 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5336 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5337 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5338 renderAreaRotation = ui::Transform::ROT_0;
5339 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005340
Chia-I Wu20261cb2018-08-23 12:55:44 -07005341 sp<DisplayDevice> display;
5342 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005343 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005344
Chia-I Wu20261cb2018-08-23 12:55:44 -07005345 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005346 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005347
Chia-I Wucb023152018-08-28 12:57:23 -07005348 // set the requested width/height to the logical display viewport size
5349 // by default
5350 if (reqWidth == 0 || reqHeight == 0) {
5351 reqWidth = uint32_t(display->getViewport().width());
5352 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005353 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005354 }
5355
Peiyong Lin0e003c92018-09-17 11:09:51 -07005356 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005357 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005358 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5359 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005360 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005361 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005362}
5363
chaviw93df2ea2019-04-30 16:45:12 -07005364static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5365 switch (colorMode) {
5366 case ColorMode::DISPLAY_P3:
5367 case ColorMode::BT2100_PQ:
5368 case ColorMode::BT2100_HLG:
5369 case ColorMode::DISPLAY_BT2020:
5370 return Dataspace::DISPLAY_P3;
5371 default:
5372 return Dataspace::V0_SRGB;
5373 }
5374}
5375
Martin Liu4a322352020-03-24 21:30:38 +08005376status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5377 static constexpr int kFifoPriority = 2;
5378 static constexpr int kOtherPriority = 0;
5379
5380 struct sched_param param = {0};
5381 int sched_policy;
5382 if (enabled) {
5383 sched_policy = SCHED_FIFO;
5384 param.sched_priority = kFifoPriority;
5385 } else {
5386 sched_policy = SCHED_OTHER;
5387 param.sched_priority = kOtherPriority;
5388 }
5389
5390 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5391 return -errno;
5392 }
5393 return NO_ERROR;
5394}
5395
chaviw93df2ea2019-04-30 16:45:12 -07005396const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5397 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5398 if (displayToken) {
5399 return getDisplayDeviceLocked(displayToken);
5400 }
5401 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5402 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005403 return getDisplayByLayerStack(displayOrLayerStack);
5404}
5405
5406const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005407 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005408 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005409 return display;
5410 }
5411 }
5412 return nullptr;
5413}
5414
5415status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5416 sp<GraphicBuffer>* outBuffer) {
5417 sp<DisplayDevice> display;
5418 uint32_t width;
5419 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005420 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005421 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005422 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005423 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5424 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005425 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005426 }
5427
5428 width = uint32_t(display->getViewport().width());
5429 height = uint32_t(display->getViewport().height());
5430
Dominik Laskowski718f9602019-11-09 20:01:35 -08005431 const auto orientation = display->getOrientation();
5432 captureOrientation = ui::Transform::toRotationFlags(orientation);
5433
5434 switch (captureOrientation) {
5435 case ui::Transform::ROT_90:
5436 captureOrientation = ui::Transform::ROT_270;
5437 break;
5438
5439 case ui::Transform::ROT_270:
5440 captureOrientation = ui::Transform::ROT_90;
5441 break;
5442
5443 case ui::Transform::ROT_INVALID:
5444 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5445 captureOrientation = ui::Transform::ROT_0;
5446 break;
5447
5448 default:
5449 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005450 }
chaviw93df2ea2019-04-30 16:45:12 -07005451 *outDataspace =
5452 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5453 }
5454
5455 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5456 false /* captureSecureLayers */);
5457
5458 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5459 std::placeholders::_1);
5460 bool ignored = false;
5461 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5462 false /* useIdentityTransform */,
5463 ignored /* outCapturedSecureLayers */);
5464}
5465
Robert Carr866455f2019-04-02 16:28:26 -07005466status_t SurfaceFlinger::captureLayers(
5467 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5468 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5469 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5470 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005471 ATRACE_CALL();
5472
5473 class LayerRenderArea : public RenderArea {
5474 public:
Robert Carr578038f2018-03-09 12:25:24 -08005475 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005476 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005477 bool childrenOnly, const Rect& displayViewport)
5478 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005479 mLayer(layer),
5480 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005481 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005482 mFlinger(flinger),
5483 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005484 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005485 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005486 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005487 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005488 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005489 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005490 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005491 }
chaviwa76b2712017-09-20 12:02:26 -07005492 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005493 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005494 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005495 Rect getSourceCrop() const override {
5496 if (mCrop.isEmpty()) {
5497 return getBounds();
5498 } else {
5499 return mCrop;
5500 }
5501 }
Robert Carr578038f2018-03-09 12:25:24 -08005502 class ReparentForDrawing {
5503 public:
5504 const sp<Layer>& oldParent;
5505 const sp<Layer>& newParent;
5506
Vishnu Nair4351ad52019-02-11 14:13:02 -08005507 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5508 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005509 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005510 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005511 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5512 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005513 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005514 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005515 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005516 };
5517
5518 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005519 const Rect sourceCrop = getSourceCrop();
5520 // no need to check rotation because there is none
5521 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5522 sourceCrop.height() != getReqHeight();
5523
Robert Carr578038f2018-03-09 12:25:24 -08005524 if (!mChildrenOnly) {
5525 mTransform = mLayer->getTransform().inverse();
5526 drawLayers();
5527 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005528 uint32_t w = static_cast<uint32_t>(getWidth());
5529 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005530 // In the "childrenOnly" case we reparent the children to a screenshot
5531 // layer which has no properties set and which does not draw.
5532 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005533 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5534 "Screenshot Parent"s, w, h, 0,
5535 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005536
Vishnu Nair4351ad52019-02-11 14:13:02 -08005537 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005538 drawLayers();
5539 }
5540 }
chaviwa76b2712017-09-20 12:02:26 -07005541
chaviwa76b2712017-09-20 12:02:26 -07005542 private:
chaviw7206d492017-11-10 16:16:12 -08005543 const sp<Layer> mLayer;
5544 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005545
Peiyong Linefefaac2018-08-17 12:27:51 -07005546 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005547 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005548
5549 SurfaceFlinger* mFlinger;
5550 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005551 };
5552
Robert Carrc0df3122019-04-11 13:18:21 -07005553 int reqWidth = 0;
5554 int reqHeight = 0;
5555 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005556 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005557 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005558 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005559 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005560 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005561
Robert Carrc0df3122019-04-11 13:18:21 -07005562 parent = fromHandle(layerHandleBinder);
5563 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5564 ALOGE("captureLayers called with an invalid or removed parent");
5565 return NAME_NOT_FOUND;
5566 }
5567
5568 const int uid = IPCThreadState::self()->getCallingUid();
5569 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5570 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5571 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5572 return PERMISSION_DENIED;
5573 }
5574
Vishnu Nairefc42e22019-12-03 17:36:12 -08005575 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005576 if (sourceCrop.width() <= 0) {
5577 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005578 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005579 }
5580
5581 if (sourceCrop.height() <= 0) {
5582 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005583 crop.bottom = parentSourceBounds.getHeight();
5584 }
5585
5586 if (crop.isEmpty() || frameScale <= 0.0f) {
5587 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5588 // crop was not specified, or an invalid frame scale was provided.
5589 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005590 }
5591 reqWidth = crop.width() * frameScale;
5592 reqHeight = crop.height() * frameScale;
5593
5594 for (const auto& handle : excludeHandles) {
5595 sp<Layer> excludeLayer = fromHandle(handle);
5596 if (excludeLayer != nullptr) {
5597 excludeLayers.emplace(excludeLayer);
5598 } else {
5599 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5600 return NAME_NOT_FOUND;
5601 }
5602 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005603
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005604 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005605 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005606 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005607 }
5608
5609 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005610 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005611
Chia-I Wu20261cb2018-08-23 12:55:44 -07005612 // really small crop or frameScale
5613 if (reqWidth <= 0) {
5614 reqWidth = 1;
5615 }
5616 if (reqHeight <= 0) {
5617 reqHeight = 1;
5618 }
5619
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005620 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5621 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005622 auto traverseLayers = [parent, childrenOnly,
5623 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005624 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5625 if (!layer->isVisible()) {
5626 return;
Robert Carr578038f2018-03-09 12:25:24 -08005627 } else if (childrenOnly && layer == parent.get()) {
5628 return;
chaviwa76b2712017-09-20 12:02:26 -07005629 }
Robert Carr866455f2019-04-02 16:28:26 -07005630
5631 sp<Layer> p = layer;
5632 while (p != nullptr) {
5633 if (excludeLayers.count(p) != 0) {
5634 return;
5635 }
5636 p = p->getParent();
5637 }
5638
chaviwa76b2712017-09-20 12:02:26 -07005639 visitor(layer);
5640 });
5641 };
Robert Carr108b2c72019-04-02 16:32:58 -07005642
5643 bool outCapturedSecureLayers = false;
5644 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5645 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005646}
5647
5648status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5649 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005650 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005651 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005652 bool useIdentityTransform,
5653 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005654 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005655
Peiyong Lin0e003c92018-09-17 11:09:51 -07005656 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005657 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5658 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005659 *outBuffer =
5660 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5661 static_cast<android_pixel_format>(reqPixelFormat), 1,
5662 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005663
Robert Carr108b2c72019-04-02 16:32:58 -07005664 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5665 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005666}
5667
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005668status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5669 TraverseLayersFunction traverseLayers,
5670 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005671 bool useIdentityTransform,
5672 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005673 // This mutex protects syncFd and captureResult for communication of the return values from the
5674 // main thread back to this Binder thread
5675 std::mutex captureMutex;
5676 std::condition_variable captureCondition;
5677 std::unique_lock<std::mutex> captureLock(captureMutex);
5678 int syncFd = -1;
5679 std::optional<status_t> captureResult;
5680
Robert Carr03480e22018-01-04 16:02:06 -08005681 const int uid = IPCThreadState::self()->getCallingUid();
5682 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5683
Dominik Laskowski8c001672018-05-30 16:52:06 -07005684 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005685 // If there is a refresh pending, bug out early and tell the binder thread to try again
5686 // after the refresh.
5687 if (mRefreshPending) {
5688 ATRACE_NAME("Skipping screenshot for now");
5689 std::unique_lock<std::mutex> captureLock(captureMutex);
5690 captureResult = std::make_optional<status_t>(EAGAIN);
5691 captureCondition.notify_one();
5692 return;
5693 }
5694
5695 status_t result = NO_ERROR;
5696 int fd = -1;
5697 {
5698 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005699 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005700 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005701 useIdentityTransform, forSystem, &fd,
5702 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005703 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005704 }
5705
5706 {
5707 std::unique_lock<std::mutex> captureLock(captureMutex);
5708 syncFd = fd;
5709 captureResult = std::make_optional<status_t>(result);
5710 captureCondition.notify_one();
5711 }
5712 });
5713
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005714 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005715 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005716 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005717 while (*captureResult == EAGAIN) {
5718 captureResult.reset();
5719 result = postMessageAsync(message);
5720 if (result != NO_ERROR) {
5721 return result;
5722 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005723 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005724 }
5725 result = *captureResult;
5726 }
5727
5728 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005729 sync_wait(syncFd, -1);
5730 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005731 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005732
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005733 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005734}
5735
chaviwa76b2712017-09-20 12:02:26 -07005736void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005737 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005738 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5739 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005740 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005741
chaviwa76b2712017-09-20 12:02:26 -07005742 const auto reqWidth = renderArea.getReqWidth();
5743 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005744 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005745 const auto transform = renderArea.getTransform();
5746 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005747 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005748
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005749 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005750 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005751
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005752 // assume that bounds are never offset, and that they are the same as the
5753 // buffer bounds.
5754 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005755 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005756 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005757
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005758 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5759 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005760
chaviw50da5042018-04-09 13:49:37 -07005761 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005762
Vishnu Nair9b079a22020-01-21 14:36:08 -08005763 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005764 fillLayer.source.buffer.buffer = nullptr;
5765 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005766 fillLayer.geometry.boundaries =
5767 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005768 fillLayer.alpha = half(alpha);
5769 clientCompositionLayers.push_back(fillLayer);
5770
Yichi Chen40773d92020-04-01 10:10:18 +08005771 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005772 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005773 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005774 const bool supportProtectedContent = false;
5775 Region clip(renderArea.getBounds());
5776 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5777 clip,
5778 useIdentityTransform,
Alec Mouri5a6d8572020-03-23 23:56:15 -07005779 layer->needsFilteringForScreenshots(renderArea.getDisplayDevice(), transform) ||
5780 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005781 renderArea.isSecure(),
5782 supportProtectedContent,
5783 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005784 displayViewport,
5785 clientCompositionDisplay.outputDataspace,
5786 true, /* realContentIsVisible */
5787 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005788 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005789 std::vector<compositionengine::LayerFE::LayerSettings> results =
5790 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005791 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005792 for (auto& settings : results) {
5793 settings.geometry.positionTransform =
5794 transform.asMatrix4() * settings.geometry.positionTransform;
5795 }
Yichi Chen40773d92020-04-01 10:10:18 +08005796 clientCompositionLayers.insert(clientCompositionLayers.end(),
5797 std::make_move_iterator(results.begin()),
5798 std::make_move_iterator(results.end()));
5799 renderedLayers.push_back(layer);
5800 }
chaviwa76b2712017-09-20 12:02:26 -07005801 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005802
Yichi Chen40773d92020-04-01 10:10:18 +08005803 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5804 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005805 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005806 clientCompositionLayerPointers.begin(),
5807 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005808
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005809 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005810 // Use an empty fence for the buffer fence, since we just created the buffer so
5811 // there is no need for synchronization with the GPU.
5812 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005813 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005814 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005815 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005816 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005817
5818 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005819
5820 if (*outSyncFd >= 0) {
5821 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5822 for (auto* layer : renderedLayers) {
5823 layer->onLayerDisplayed(releaseFence);
5824 }
5825 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005826}
5827
chaviwa76b2712017-09-20 12:02:26 -07005828status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5829 TraverseLayersFunction traverseLayers,
5830 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005831 bool useIdentityTransform, bool forSystem,
5832 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005833 ATRACE_CALL();
5834
chaviwa76b2712017-09-20 12:02:26 -07005835 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005836 outCapturedSecureLayers =
5837 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005838 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005839
Robert Carr03480e22018-01-04 16:02:06 -08005840 // We allow the system server to take screenshots of secure layers for
5841 // use in situations like the Screen-rotation animation and place
5842 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005843 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005844 ALOGW("FB is protected: PERMISSION_DENIED");
5845 return PERMISSION_DENIED;
5846 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005847 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005848 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005849}
5850
chaviw95ef3c42019-02-14 10:55:09 -08005851void SurfaceFlinger::setInputWindowsFinished() {
5852 Mutex::Autolock _l(mStateLock);
5853
5854 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005855
chaviw95ef3c42019-02-14 10:55:09 -08005856 mTransactionCV.broadcast();
5857}
chaviw5f21a5e2019-02-14 10:00:34 -08005858
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005859// ---------------------------------------------------------------------------
5860
Edgar Arriaga844fa672020-01-16 14:21:42 -08005861void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5862 layersSortedByZ.traverse(visitor);
5863}
5864
Dan Stoza412903f2017-04-27 13:42:17 -07005865void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5866 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005867}
5868
Dan Stoza412903f2017-04-27 13:42:17 -07005869void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5870 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005871}
5872
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005873void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005874 const LayerVector::Visitor& visitor) {
5875 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005876 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005877 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005878 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005879 continue;
5880 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005881 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005882 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005883 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005884 return;
5885 }
chaviwa76b2712017-09-20 12:02:26 -07005886 if (!layer->isVisible()) {
5887 return;
5888 }
5889 visitor(layer);
5890 });
5891 }
5892}
5893
Steven Thomasd4071902020-03-24 16:02:53 -07005894status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5895 const sp<DisplayDevice>& display,
5896 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005897 Mutex::Autolock lock(mStateLock);
5898
Steven Thomasd4071902020-03-24 16:02:53 -07005899 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5900 "Can only set override policy on the primary display");
5901 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5902
Dominik Laskowski22488f62019-03-28 09:53:04 -07005903 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005904 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5905 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5906 // it should go thru setDesiredActiveConfig, similar to primary display.
5907 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5908 const auto displayId = display->getId();
5909 LOG_ALWAYS_FATAL_IF(!displayId);
5910
Peiyong Line9d809e2020-04-14 13:10:48 -07005911 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005912 constraints.desiredTimeNanos = systemTime();
5913 constraints.seamlessRequired = false;
5914
Peiyong Line9d809e2020-04-14 13:10:48 -07005915 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005916 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5917 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005918 constraints, &timeline) < 0) {
5919 return BAD_VALUE;
5920 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005921 if (timeline.refreshRequired) {
5922 repaintEverythingForHWC();
5923 }
5924
Steven Thomasd4071902020-03-24 16:02:53 -07005925 display->setActiveConfig(policy->defaultConfig);
5926 const nsecs_t vsyncPeriod = getHwComposer()
5927 .getConfigs(*displayId)[policy->defaultConfig.value()]
5928 ->getVsyncPeriod();
5929 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5930 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005931 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005932 }
5933
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005934 if (mDebugDisplayConfigSetByBackdoor) {
5935 // ignore this request as config is overridden by backdoor
5936 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005937 }
5938
Steven Thomasd4071902020-03-24 16:02:53 -07005939 status_t setPolicyResult = overridePolicy
5940 ? mRefreshRateConfigs->setOverridePolicy(policy)
5941 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5942 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005943 return BAD_VALUE;
5944 }
Steven Thomasd4071902020-03-24 16:02:53 -07005945 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005946 return NO_ERROR;
5947 }
Steven Thomasd4071902020-03-24 16:02:53 -07005948 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005949
5950 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
Steven Thomasd4071902020-03-24 16:02:53 -07005951 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
5952 currentPolicy.maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005953
5954 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5955 // that listeners that care about a change in allowed configs can get the notification.
5956 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005957 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005958 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5959 .getVsyncPeriod();
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005960 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005961 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005962
Ana Krulec3f6a2062020-01-23 15:48:01 -08005963 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005964 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005965 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5966 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005967 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005968 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005969 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005970
Ady Abrahamabc27602020-04-08 17:20:29 -07005971 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5972 ALOGV("switching to Scheduler preferred config %d",
5973 preferredRefreshRate.getConfigId().value());
5974 setDesiredActiveConfig(
5975 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005976 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005977 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5978 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005979 }
5980
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005981 return NO_ERROR;
5982}
5983
Ana Krulec0782b882019-10-15 17:34:54 -07005984status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005985 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005986 float maxRefreshRate) {
5987 ATRACE_CALL();
5988
5989 if (!displayToken) {
5990 return BAD_VALUE;
5991 }
5992
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005993 status_t result = NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005994
Ana Krulec234bb162019-11-10 22:55:55 +01005995 postMessageSync(new LambdaMessage([&]() {
5996 const auto display = getDisplayDeviceLocked(displayToken);
5997 if (!display) {
5998 ALOGE("Attempt to set desired display configs for invalid display token %p",
5999 displayToken.get());
6000 } else if (display->isVirtual()) {
6001 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006002 result = INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006003 } else {
Steven Thomasd4071902020-03-24 16:02:53 -07006004 result = setDesiredDisplayConfigSpecsInternal(display,
6005 scheduler::RefreshRateConfigs::
6006 Policy{HwcConfigIndexType(
6007 defaultConfig),
6008 minRefreshRate,
6009 maxRefreshRate},
6010 /*overridePolicy=*/false);
Ana Krulec234bb162019-11-10 22:55:55 +01006011 }
6012 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006013
6014 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01006015}
6016
6017status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006018 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01006019 float* outMinRefreshRate,
6020 float* outMaxRefreshRate) {
6021 ATRACE_CALL();
6022
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006023 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01006024 return BAD_VALUE;
6025 }
6026
6027 Mutex::Autolock lock(mStateLock);
6028 const auto display = getDisplayDeviceLocked(displayToken);
6029 if (!display) {
6030 return NAME_NOT_FOUND;
6031 }
6032
6033 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006034 scheduler::RefreshRateConfigs::Policy policy =
6035 mRefreshRateConfigs->getDisplayManagerPolicy();
6036 *outDefaultConfig = policy.defaultConfig.value();
6037 *outMinRefreshRate = policy.minRefreshRate;
6038 *outMaxRefreshRate = policy.maxRefreshRate;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006039 return NO_ERROR;
6040 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006041 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006042 } else {
6043 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006044 LOG_FATAL_IF(!displayId);
6045
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006046 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6047 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6048 *outMinRefreshRate = 1e9f / vsyncPeriod;
6049 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6050 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006051 }
Ana Krulec0782b882019-10-15 17:34:54 -07006052}
6053
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006054void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006055 mFlinger->setInputWindowsFinished();
6056}
6057
Robert Carrc0df3122019-04-11 13:18:21 -07006058sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006059 BBinder* b = nullptr;
6060 if (handle) {
6061 b = handle->localBinder();
6062 }
Robert Carrc0df3122019-04-11 13:18:21 -07006063 if (b == nullptr) {
6064 return nullptr;
6065 }
6066 auto it = mLayersByLocalBinderToken.find(b);
6067 if (it != mLayersByLocalBinderToken.end()) {
6068 return it->second.promote();
6069 }
6070 return nullptr;
6071}
6072
Dominik Laskowski75848362019-11-11 17:57:20 -08006073void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006074 mNumLayers++;
6075 mScheduler->registerLayer(layer);
6076}
6077
6078void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6079 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006080 removeFromOffscreenLayers(layer);
6081}
6082
6083// WARNING: ONLY CALL THIS FROM LAYER DTOR
6084// Here we add children in the current state to offscreen layers and remove the
6085// layer itself from the offscreen layer list. Since
6086// this is the dtor, it is safe to access the current state. This keeps us
6087// from dangling children layers such that they are not reachable from the
6088// Drawing state nor the offscreen layer list
6089// See b/141111965
6090void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6091 for (auto& child : layer->getCurrentChildren()) {
6092 mOffscreenLayers.emplace(child.get());
6093 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006094 mOffscreenLayers.erase(layer);
6095}
6096
Alec Mouri4545a8a2019-08-08 20:05:32 -07006097void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6098 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6099}
6100
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006101status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6102 float lightPosY, float lightPosZ,
6103 float lightRadius) {
6104 Mutex::Autolock _l(mStateLock);
6105 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6106 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6107 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6108 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6109 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6110
6111 // these values are overridden when calculating the shadow settings for a layer.
6112 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6113 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006114 return NO_ERROR;
6115}
6116
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006117const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6118 const {
6119 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6120 // on the work to remove the table in that bug rather than adding more to
6121 // it.
6122 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6123 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6124 // supported, and exposed via the
6125 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6126 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6127 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6128 };
6129 return genericLayerMetadataKeyMap;
6130}
6131
Steven Thomas62a4cf82020-01-31 12:04:03 -08006132status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6133 int8_t compatibility) {
6134 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6135 return BAD_VALUE;
6136 }
6137
Ady Abraham60e42ea2020-03-09 19:17:31 -07006138 postMessageAsync(new LambdaMessage([=]() NO_THREAD_SAFETY_ANALYSIS {
6139 Mutex::Autolock lock(mStateLock);
6140 if (authenticateSurfaceTextureLocked(surface)) {
6141 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6142 if (layer->setFrameRate(
6143 Layer::FrameRate(frameRate,
6144 Layer::FrameRate::convertCompatibility(compatibility)))) {
6145 setTransactionFlags(eTraversalNeeded);
6146 }
6147 } else {
6148 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6149 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006150 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006151 return NO_ERROR;
6152 }));
6153
Steven Thomas62a4cf82020-01-31 12:04:03 -08006154 return NO_ERROR;
6155}
6156
Steven Thomasd4071902020-03-24 16:02:53 -07006157status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6158 if (!outToken) {
6159 return BAD_VALUE;
6160 }
6161 status_t result = NO_ERROR;
6162 postMessageSync(new LambdaMessage([&]() {
6163 if (mFrameRateFlexibilityTokenCount == 0) {
6164 // |mStateLock| not needed as we are on the main thread
6165 const auto display = getDefaultDisplayDeviceLocked();
6166
6167 // This is a little racy, but not in a way that hurts anything. As we grab the
6168 // defaultConfig from the display manager policy, we could be setting a new display
6169 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6170 // matter for the override policy though, since we set allowGroupSwitching to true, so
6171 // it's not a problem.
6172 scheduler::RefreshRateConfigs::Policy overridePolicy;
6173 overridePolicy.defaultConfig =
6174 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6175 overridePolicy.allowGroupSwitching = true;
6176 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy,
6177 /*overridePolicy=*/true);
6178 }
6179
6180 if (result == NO_ERROR) {
6181 mFrameRateFlexibilityTokenCount++;
6182 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6183 // below, is something to consider carefully. The lifetime of the
6184 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6185 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6186 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6187 // in this case, for two reasons:
6188 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6189 // the program exits is via a crash. So we won't have a situation where the
6190 // SurfaceFlinger object is dead but the process is still up.
6191 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6192 // if condition 1 were changed, the problem would only show up when running CTS tests,
6193 // not on end user devices, so we could spot it and fix it without serious impact.
6194 *outToken = new FrameRateFlexibilityToken(
6195 [this]() { onFrameRateFlexibilityTokenReleased(); });
6196 ALOGD("Frame rate flexibility token acquired. count=%d",
6197 mFrameRateFlexibilityTokenCount);
6198 }
6199 }));
6200 return result;
6201}
6202
6203void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
6204 postMessageAsync(new LambdaMessage([&]() {
6205 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6206 "Failed tracking frame rate flexibility tokens");
6207 mFrameRateFlexibilityTokenCount--;
6208 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6209 if (mFrameRateFlexibilityTokenCount == 0) {
6210 // |mStateLock| not needed as we are on the main thread
6211 const auto display = getDefaultDisplayDeviceLocked();
6212 status_t result =
6213 setDesiredDisplayConfigSpecsInternal(display, {}, /*overridePolicy=*/true);
6214 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6215 }
6216 }));
6217}
6218
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006219} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006220
Mathias Agopian3f844832013-08-07 21:24:32 -07006221#if defined(__gl_h_)
6222#error "don't include gl/gl.h in this file"
6223#endif
6224
6225#if defined(__gl2_h_)
6226#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006227#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006228
6229// TODO(b/129481165): remove the #pragma below and fix conversion issues
6230#pragma clang diagnostic pop // ignored "-Wconversion"