blob: 737f8f889ecd201da78baebde536cecf366ab2d6 [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 Mouri5f487d42020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri5f487d42020-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 Pique9370a482019-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 Mouri5f487d42020-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 Mouri5f487d42020-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 Mouri5f487d42020-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 Mouri5f487d42020-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 Mouri5f487d42020-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 Mouri5f487d42020-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 Mouri5f487d42020-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 Mouri5f487d42020-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 Mouri5f487d42020-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 Abrahamb89ca7d2020-03-04 11:19:37 -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;
Alec Mouri601393f2020-02-21 13:26:52 -0800389 mGraphicBufferProducerListSizeLogThreshold =
390 std::max(static_cast<int>(0.95 *
391 static_cast<double>(mMaxGraphicBufferProducerListSize)),
392 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700393
Dan Stozaec460082018-12-17 15:35:09 -0800394 property_get("debug.sf.luma_sampling", value, "1");
395 mLumaSampling = atoi(value);
396
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800397 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800398 mDisableClientCompositionCache = atoi(value);
399
Romain Guy11d63f42017-07-20 12:47:14 -0700400 // We should be reading 'persist.sys.sf.color_saturation' here
401 // but since /data may be encrypted, we need to wait until after vold
402 // comes online to attempt to read the property. The property is
403 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800404
405 if (useTrebleTestingOverride()) {
406 // Without the override SurfaceFlinger cannot connect to HIDL
407 // services that are not listed in the manifests. Considered
408 // deriving the setting from the set service name, but it
409 // would be brittle if the name that's not 'default' is used
410 // for production purposes later on.
411 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
412 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800413
414 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415}
416
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417void SurfaceFlinger::onFirstRef()
418{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800419 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420}
421
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700422SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423
Dan Stozac7014012014-02-14 15:03:43 -0800424void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425{
426 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700427 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428
Andy McFadden13a082e2012-08-24 10:16:42 -0700429 // restore initial conditions (default device unblank, etc)
430 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800431
432 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700433 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800434}
435
Robert Carr1db73f62016-12-21 12:58:51 -0800436static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700437 status_t err = client->initCheck();
438 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800439 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800440 }
Robert Carr1db73f62016-12-21 12:58:51 -0800441 return nullptr;
442}
443
444sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
445 return initClient(new Client(this));
446}
447
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700448sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
449 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700450{
451 class DisplayToken : public BBinder {
452 sp<SurfaceFlinger> flinger;
453 virtual ~DisplayToken() {
454 // no more references, this display must be terminated
455 Mutex::Autolock _l(flinger->mStateLock);
456 flinger->mCurrentState.displays.removeItem(this);
457 flinger->setTransactionFlags(eDisplayTransactionNeeded);
458 }
459 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700460 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461 : flinger(flinger) {
462 }
463 };
464
465 sp<BBinder> token = new DisplayToken(this);
466
467 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700468 // Display ID is assigned when virtual display is allocated by HWC.
469 DisplayDeviceState state;
470 state.isSecure = secure;
471 state.displayName = displayName;
472 mCurrentState.displays.add(token, state);
473 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700474 return token;
475}
476
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700477void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700478 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700479
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700480 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700482 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700483 return;
484 }
485
Dominik Laskowski075d3172018-05-24 15:50:06 -0700486 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700487 if (state.physical) {
488 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 return;
490 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700491 mInterceptor->saveDisplayDeletion(state.sequenceId);
492 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 setTransactionFlags(eDisplayTransactionNeeded);
494}
495
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800496std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
497 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800499 const auto internalDisplayId = getInternalDisplayIdLocked();
500 if (!internalDisplayId) {
501 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502 }
503
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800504 std::vector<PhysicalDisplayId> displayIds;
505 displayIds.reserve(mPhysicalDisplayTokens.size());
506 displayIds.push_back(internalDisplayId->value);
507
508 for (const auto& [id, token] : mPhysicalDisplayTokens) {
509 if (id != *internalDisplayId) {
510 displayIds.push_back(id.value);
511 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700512 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700513
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800514 return displayIds;
515}
516
517sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
518 Mutex::Autolock lock(mStateLock);
519 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700520}
521
Ady Abraham37965d42018-11-01 13:43:32 -0700522status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
523 if (!outGetColorManagement) {
524 return BAD_VALUE;
525 }
526 *outGetColorManagement = useColorManagement;
527 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700528}
529
Lloyd Pique441d5042018-10-18 16:49:51 -0700530HWComposer& SurfaceFlinger::getHwComposer() const {
531 return mCompositionEngine->getHwComposer();
532}
533
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700534renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
535 return mCompositionEngine->getRenderEngine();
536}
537
Lloyd Pique70d91362018-10-18 16:02:55 -0700538compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
539 return *mCompositionEngine.get();
540}
541
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800542void SurfaceFlinger::bootFinished()
543{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700544 if (mBootFinished == true) {
545 ALOGE("Extra call to bootFinished");
546 return;
547 }
548 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700549 if (mStartPropertySetThread->join() != NO_ERROR) {
550 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800551 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800552 const nsecs_t now = systemTime();
553 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000554 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555
Mikael Pessa90092f42019-08-26 17:22:04 -0700556 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000557 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700558
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 // wait patiently for the window manager death
560 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700561 mWindowManager = defaultServiceManager()->getService(name);
562 if (mWindowManager != 0) {
563 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700564 }
Robert Carr720e5062018-07-30 17:45:14 -0700565 sp<IBinder> input(defaultServiceManager()->getService(
566 String16("inputflinger")));
567 if (input == nullptr) {
568 ALOGE("Failed to link to input service");
569 } else {
570 mInputFlinger = interface_cast<IInputFlinger>(input);
571 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700572
Steven Thomas050b2c82017-03-06 11:45:16 -0800573 if (mVrFlinger) {
574 mVrFlinger->OnBootFinished();
575 }
576
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700577 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700578 // formerly we would just kill the process, but we now ask it to exit so it
579 // can choose where to stop the animation.
580 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700581
582 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
583 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
584 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700585
Ana Krulecbd6654b2019-02-15 15:18:15 -0800586 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800587 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700588 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800589 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800590
Ady Abraham8a82ba62020-01-17 12:43:17 -0800591 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
592 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
593 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
594 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800595 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800596}
597
Dan Stoza436ccf32018-06-21 12:10:12 -0700598uint32_t SurfaceFlinger::getNewTexture() {
599 {
600 std::lock_guard lock(mTexturePoolMutex);
601 if (!mTexturePool.empty()) {
602 uint32_t name = mTexturePool.back();
603 mTexturePool.pop_back();
604 ATRACE_INT("TexturePoolSize", mTexturePool.size());
605 return name;
606 }
607
608 // The pool was too small, so increase it for the future
609 ++mTexturePoolSize;
610 }
611
612 // The pool was empty, so we need to get a new texture name directly using a
613 // blocking call to the main thread
614 uint32_t name = 0;
615 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
616 return name;
617}
618
Mathias Agopian3f844832013-08-07 21:24:32 -0700619void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700620 std::lock_guard lock(mTexturePoolMutex);
621 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
622 // to actually delete this or not based on mTexturePoolSize
623 mTexturePool.push_back(texture);
624 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700625}
626
Wei Wangf9b05ee2017-07-19 20:59:39 -0700627// Do not call property_set on main thread which will be blocked by init
628// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700629void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700630 ALOGI( "SurfaceFlinger's main thread ready to run. "
631 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700632 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800633
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700635 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800636 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700637 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
638 renderengine::RenderEngineCreationArgs::Builder()
639 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
640 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
641 .setUseColorManagerment(useColorManagement)
642 .setEnableProtectedContext(enable_protected_contents(false))
643 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700644 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700645 .setContextPriority(useContextPriority
646 ? renderengine::RenderEngine::ContextPriority::HIGH
647 : renderengine::RenderEngine::ContextPriority::MEDIUM)
648 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800649 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700650
651 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
652 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700653 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800654 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800655 // Process any initial hotplug and resulting display changes.
656 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700657 const auto display = getDefaultDisplayDeviceLocked();
658 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700659 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700660 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800661
Steven Thomas050b2c82017-03-06 11:45:16 -0800662 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700663 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700664 // This callback is called from the vr flinger dispatch thread. We
665 // need to call signalTransaction(), which requires holding
666 // mStateLock when we're not on the main thread. Acquiring
667 // mStateLock from the vr flinger dispatch thread might trigger a
668 // deadlock in surface flinger (see b/66916578), so post a message
669 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700670 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700671 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
672 mVrFlingerRequestsDisplay = requestDisplay;
673 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700674 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700676 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
677 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700678 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700679 .value_or(0),
680 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800681 if (!mVrFlinger) {
682 ALOGE("Failed to start vrflinger");
683 }
684 }
685
Mathias Agopian92a979a2012-08-02 18:32:23 -0700686 // initialize our drawing state
687 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700688
Andy McFadden13a082e2012-08-24 10:16:42 -0700689 // set initial conditions (e.g. unblank default device)
690 initializeDisplays();
691
Steven Thomas137d4bc2019-07-25 16:55:14 -0700692 char primeShaderCache[PROPERTY_VALUE_MAX];
693 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
694 if (atoi(primeShaderCache)) {
695 getRenderEngine().primeCache();
696 }
Dan Stoza4e637772016-07-28 13:31:51 -0700697
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700699
700 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700701 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700702 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700703
704 if (mStartPropertySetThread->Start() != NO_ERROR) {
705 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800706 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800707
Dan Stoza9e56aa02015-11-02 13:00:03 -0800708 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700709}
710
Romain Guy11d63f42017-07-20 12:47:14 -0700711void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700712 Mutex::Autolock _l(mStateLock);
713
Romain Guy11d63f42017-07-20 12:47:14 -0700714 char value[PROPERTY_VALUE_MAX];
715
716 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800717 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700718 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800719 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100720
721 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700722 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800723
724 property_get("persist.sys.sf.color_mode", value, "0");
725 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700726
727 property_get("persist.sys.sf.disable_blurs", value, "0");
728 bool disableBlurs = atoi(value);
729 mDisableBlurs = disableBlurs;
730 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700731}
732
Mathias Agopiana67e4182012-06-19 17:26:12 -0700733void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800734 // Start boot animation service by setting a property mailbox
735 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700736 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800737 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738 if (mStartPropertySetThread->join() != NO_ERROR) {
739 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800740 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700741}
742
Mathias Agopian875d8e12013-06-07 15:35:48 -0700743size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700744 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700745}
746
Mathias Agopian875d8e12013-06-07 15:35:48 -0700747size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700748 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700749}
750
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800751// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800752
Jamie Gennis582270d2011-08-17 18:19:00 -0700753bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800754 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800755 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800756 return authenticateSurfaceTextureLocked(bufferProducer);
757}
758
759bool SurfaceFlinger::authenticateSurfaceTextureLocked(
760 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800761 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800762 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800763}
764
Brian Anderson6b376712017-04-04 10:51:39 -0700765status_t SurfaceFlinger::getSupportedFrameTimestamps(
766 std::vector<FrameEvent>* outSupported) const {
767 *outSupported = {
768 FrameEvent::REQUESTED_PRESENT,
769 FrameEvent::ACQUIRE,
770 FrameEvent::LATCH,
771 FrameEvent::FIRST_REFRESH_START,
772 FrameEvent::LAST_REFRESH_START,
773 FrameEvent::GPU_COMPOSITION_DONE,
774 FrameEvent::DEQUEUE_READY,
775 FrameEvent::RELEASE,
776 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700777 ConditionalLock _l(mStateLock,
778 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700779 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700780 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
781 }
782 return NO_ERROR;
783}
784
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800785status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
786 if (!displayToken || !state) {
787 return BAD_VALUE;
788 }
789
790 Mutex::Autolock lock(mStateLock);
791
792 const auto display = getDisplayDeviceLocked(displayToken);
793 if (!display) {
794 return NAME_NOT_FOUND;
795 }
796
797 state->layerStack = display->getLayerStack();
798 state->orientation = display->getOrientation();
799
800 const Rect viewport = display->getViewport();
801 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
802
803 return NO_ERROR;
804}
805
806status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
807 if (!displayToken || !info) {
808 return BAD_VALUE;
809 }
810
811 Mutex::Autolock lock(mStateLock);
812
813 const auto display = getDisplayDeviceLocked(displayToken);
814 if (!display) {
815 return NAME_NOT_FOUND;
816 }
817
Dominik Laskowski55c85402020-01-21 16:25:47 -0800818 if (const auto connectionType = display->getConnectionType())
819 info->connectionType = *connectionType;
820 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800821 return INVALID_OPERATION;
822 }
823
824 if (mEmulatedDisplayDensity) {
825 info->density = mEmulatedDisplayDensity;
826 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800827 info->density = info->connectionType == DisplayConnectionType::Internal
828 ? mInternalDisplayDensity
829 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800830 }
831
832 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200833 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800834
835 return NO_ERROR;
836}
837
Dominik Laskowski22488f62019-03-28 09:53:04 -0700838status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800839 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700840 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 return BAD_VALUE;
842 }
843
Dominik Laskowski22488f62019-03-28 09:53:04 -0700844 Mutex::Autolock lock(mStateLock);
845
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800846 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700847 if (!displayId) {
848 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700849 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800851 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700852
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700854
Dominik Laskowski075d3172018-05-24 15:50:06 -0700855 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800856 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700857
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800858 auto width = hwConfig->getWidth();
859 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700860
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800861 auto xDpi = hwConfig->getDpiX();
862 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700863
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800864 if (isInternal &&
865 (internalDisplayOrientation == ui::ROTATION_90 ||
866 internalDisplayOrientation == ui::ROTATION_270)) {
867 std::swap(width, height);
868 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 }
870
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800871 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800872
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800873 if (mEmulatedDisplayDensity) {
874 config.xDpi = mEmulatedDisplayDensity;
875 config.yDpi = mEmulatedDisplayDensity;
876 } else {
877 config.xDpi = xDpi;
878 config.yDpi = yDpi;
879 }
880
881 const nsecs_t period = hwConfig->getVsyncPeriod();
882 config.refreshRate = 1e9f / period;
883
884 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
885 config.appVsyncOffset = offsets.late.app;
886 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800887 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888
Andy McFadden91b2ca82014-06-13 14:04:23 -0700889 // This is how far in advance a buffer must be queued for
890 // presentation at a given time. If you want a buffer to appear
891 // on the screen at time N, you must submit the buffer before
892 // (N - presentationDeadline).
893 //
894 // Normally it's one full refresh period (to give SF a chance to
895 // latch the buffer), but this can be reduced by configuring a
896 // DispSync offset. Any additional delays introduced by the hardware
897 // composer or panel must be accounted for here.
898 //
899 // We add an additional 1ms to allow for processing time and
900 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800901 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700902
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800903 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700904 }
905
Dan Stoza7f7da322014-05-02 15:26:25 -0700906 return NO_ERROR;
907}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700908
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700909status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
910 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700911 return BAD_VALUE;
912 }
913
Ana Krulecc2870422019-01-29 19:00:58 -0800914 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700915 return NO_ERROR;
916}
917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700919 int activeConfig;
920 bool isPrimary;
921
922 {
923 Mutex::Autolock lock(mStateLock);
924
925 if (const auto display = getDisplayDeviceLocked(displayToken)) {
926 activeConfig = display->getActiveConfig().value();
927 isPrimary = display->isPrimary();
928 } else {
929 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
930 return NAME_NOT_FOUND;
931 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800932 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700933
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700934 if (isPrimary) {
Steven Thomasc9098452019-09-30 17:15:05 -0700935 std::lock_guard<std::mutex> lock(mActiveConfigLock);
936 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800937 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700938 }
Steven Thomasc9098452019-09-30 17:15:05 -0700939 }
Ady Abraham2139f732019-11-13 18:56:40 -0800940
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700941 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700942}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700943
Ady Abraham03b02dd2019-03-21 15:40:11 -0700944void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800945 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800946 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700947 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800948
Ady Abrahamb838aed2019-02-12 15:30:16 -0800949 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800950 if (mDesiredActiveConfigChanged) {
951 // If a config change is pending, just cache the latest request in
952 // mDesiredActiveConfig
953 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
954 mDesiredActiveConfig = info;
955 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
956 } else {
957 // Check is we are already at the desired config
958 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700959 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800960 return;
961 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800962
Ady Abraham59db0a32020-03-02 18:04:20 -0800963 // Initiate a config change.
964 mDesiredActiveConfigChanged = true;
965 mDesiredActiveConfig = info;
966
Ady Abrahamb838aed2019-02-12 15:30:16 -0800967 // This will trigger HWC refresh without resetting the idle timer.
968 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700969 // Start receiving vsync samples now, so that we can detect a period
970 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700971 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700972 // As we called to set period, we will call to onRefreshRateChangeCompleted once
973 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700974 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800975
Ady Abrahamabc27602020-04-08 17:20:29 -0700976 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800977 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700979
980 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800981 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700982 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983}
984
985status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
986 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800987
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100988 if (!displayToken) {
989 return BAD_VALUE;
990 }
Ady Abraham838de062019-02-04 10:24:03 -0800991
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700992 status_t result = NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100993
994 postMessageSync(new LambdaMessage([&]() {
995 const auto display = getDisplayDeviceLocked(displayToken);
996 if (!display) {
997 ALOGE("Attempt to set allowed display configs for invalid display token %p",
998 displayToken.get());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100999 } else if (display->isVirtual()) {
1000 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001001 result = INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001002 } else {
1003 HwcConfigIndexType config(mode);
1004 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
Steven Thomasd4071902020-03-24 16:02:53 -07001005 result = setDesiredDisplayConfigSpecsInternal(display,
1006 scheduler::RefreshRateConfigs::
Ady Abrahamabc27602020-04-08 17:20:29 -07001007 Policy{config,
1008 refreshRate.getFps(),
1009 refreshRate.getFps()},
Steven Thomasd4071902020-03-24 16:02:53 -07001010 /*overridePolicy=*/false);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001011 }
1012 }));
1013
1014 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001015}
1016
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001017void SurfaceFlinger::setActiveConfigInternal() {
1018 ATRACE_CALL();
1019
Dominik Laskowski22488f62019-03-28 09:53:04 -07001020 const auto display = getDefaultDisplayDeviceLocked();
1021 if (!display) {
1022 return;
1023 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001024
Alec Mouri8de697e2020-03-19 10:52:01 -07001025 auto& oldRefreshRate =
1026 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1027
Dominik Laskowski22488f62019-03-28 09:53:04 -07001028 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001029 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001030 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001031 display->setActiveConfig(mUpcomingActiveConfig.configId);
1032
Ady Abraham2e1dd892020-03-05 13:48:36 -08001033 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001034 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001035 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001036 mTimeStats->incrementRefreshRateSwitches();
1037 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001038 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001039 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001040 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001041
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001042 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001043 const nsecs_t vsyncPeriod =
1044 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001045 .getVsyncPeriod();
Ady Abraham447052e2019-02-13 16:07:27 -08001046 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001047 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001048 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001049}
1050
Ady Abraham53852a52019-05-28 18:07:44 -07001051void SurfaceFlinger::desiredActiveConfigChangeDone() {
1052 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1053 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1054 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001055
Ady Abraham2e1dd892020-03-05 13:48:36 -08001056 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001057 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001058 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1059 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001060 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001061}
1062
Ady Abraham27cbed72020-04-10 12:56:59 -07001063void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001064 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001065 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001066 // Store the local variable to release the lock.
Ady Abraham27cbed72020-04-10 12:56:59 -07001067 const auto desiredActiveConfig = [&]() -> std::optional<ActiveConfigInfo> {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001068 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham27cbed72020-04-10 12:56:59 -07001069 if (mDesiredActiveConfigChanged) {
1070 return mDesiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001071 }
Ady Abraham27cbed72020-04-10 12:56:59 -07001072 return std::nullopt;
1073 }();
1074
1075 if (!desiredActiveConfig) {
1076 // No desired active config pending to be applied
1077 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001078 }
1079
Ady Abraham2e1dd892020-03-05 13:48:36 -08001080 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001081 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001082 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1083 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001084 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001085 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001086 // display is not valid or we are already in the requested mode
1087 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001088 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001089 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001090 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001091
Ady Abraham838de062019-02-04 10:24:03 -08001092 // Desired active config was set, it is different than the config currently in use, however
1093 // allowed configs might have change by the time we process the refresh.
1094 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001095 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001096 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001097 return;
Ady Abraham838de062019-02-04 10:24:03 -08001098 }
Alec Mouri7f015182019-07-11 13:56:22 -07001099
Ady Abraham27cbed72020-04-10 12:56:59 -07001100 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001101 const auto displayId = display->getId();
1102 LOG_ALWAYS_FATAL_IF(!displayId);
1103
Ady Abrahamabc27602020-04-08 17:20:29 -07001104 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001105
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001106 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001107 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001108 constraints.desiredTimeNanos = systemTime();
1109 constraints.seamlessRequired = false;
1110
Peiyong Line9d809e2020-04-14 13:10:48 -07001111 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001112 auto status =
1113 getHwComposer().setActiveConfigWithConstraints(*displayId,
1114 mUpcomingActiveConfig.configId.value(),
1115 constraints, &outTimeline);
1116 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001117 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1118 // to be sent. We just log the error in this case.
1119 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001120 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001121 }
1122
1123 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1124 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001125 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001126}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001127
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1129 Vector<ColorMode>* outColorModes) {
1130 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001131 return BAD_VALUE;
1132 }
1133
Peiyong Lina52f0292018-03-14 17:26:31 -07001134 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001135 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001136 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001137 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1138
1139 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1140 if (!displayId) {
1141 return NAME_NOT_FOUND;
1142 }
1143
Dominik Laskowski075d3172018-05-24 15:50:06 -07001144 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001145 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001146 }
Michael Wright28f24d02016-07-12 13:30:53 -07001147 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001148
1149 // If it's built-in display and the configuration claims it's not wide color capable,
1150 // filter out all wide color modes. The typical reason why this happens is that the
1151 // hardware is not good enough to support GPU composition of wide color, and thus the
1152 // OEMs choose to disable this capability.
1153 if (isInternalDisplay && !hasWideColorDisplay) {
1154 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1155 isWideColorMode);
1156 } else {
1157 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1158 }
Michael Wright28f24d02016-07-12 13:30:53 -07001159
1160 return NO_ERROR;
1161}
1162
Daniel Solomon42d04562019-01-20 21:03:19 -08001163status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1164 ui::DisplayPrimaries &primaries) {
1165 if (!displayToken) {
1166 return BAD_VALUE;
1167 }
1168
1169 // Currently we only support this API for a single internal display.
1170 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001171 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001172 }
1173
1174 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1175 return NO_ERROR;
1176}
1177
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001178ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001179 Mutex::Autolock lock(mStateLock);
1180
1181 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001182 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001183 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001184 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001185}
1186
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001187status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001188 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001189 Vector<ColorMode> modes;
1190 getDisplayColorModes(displayToken, &modes);
1191 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1192 if (mode < ColorMode::NATIVE || !exists) {
1193 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1194 decodeColorMode(mode).c_str(), mode, displayToken.get());
1195 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001196 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001197 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001198 if (!display) {
1199 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1200 decodeColorMode(mode).c_str(), mode, displayToken.get());
1201 } else if (display->isVirtual()) {
1202 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1203 decodeColorMode(mode).c_str(), mode);
1204 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001205 display->getCompositionDisplay()->setColorProfile(
1206 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1207 RenderIntent::COLORIMETRIC,
1208 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001209 }
1210 }));
1211
Michael Wright28f24d02016-07-12 13:30:53 -07001212 return NO_ERROR;
1213}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001214
Galia Peycheva5492cb52019-10-30 14:13:16 +01001215status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1216 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001217 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001218 return BAD_VALUE;
1219 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001220
1221 Mutex::Autolock lock(mStateLock);
1222
Galia Peycheva5492cb52019-10-30 14:13:16 +01001223 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1224 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001225 return NAME_NOT_FOUND;
1226 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001227 *outSupport =
1228 getHwComposer().hasDisplayCapability(*displayId,
1229 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001230 return NO_ERROR;
1231}
1232
1233void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001234 postMessageAsync(new LambdaMessage([=] {
1235 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1236 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1237 } else {
1238 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1239 }
1240 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001241}
1242
1243status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1244 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001245 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001246 return BAD_VALUE;
1247 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001248
1249 Mutex::Autolock lock(mStateLock);
1250
Galia Peycheva5492cb52019-10-30 14:13:16 +01001251 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1252 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001253 return NAME_NOT_FOUND;
1254 }
1255
Peiyong Line9d809e2020-04-14 13:10:48 -07001256 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001257 getHwComposer().getSupportedContentTypes(*displayId, &types);
1258
1259 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001260 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001261 return NO_ERROR;
1262}
1263
1264void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001265 postMessageAsync(new LambdaMessage([=] {
1266 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001267 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001268 getHwComposer().setContentType(*displayId, type);
1269 } else {
1270 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1271 }
1272 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001273}
1274
Svetoslavd85084b2014-03-20 10:28:31 -07001275status_t SurfaceFlinger::clearAnimationFrameStats() {
1276 Mutex::Autolock _l(mStateLock);
1277 mAnimFrameTracker.clearStats();
1278 return NO_ERROR;
1279}
1280
1281status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1282 Mutex::Autolock _l(mStateLock);
1283 mAnimFrameTracker.getStats(outStats);
1284 return NO_ERROR;
1285}
1286
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001287status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1288 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001289 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001290
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001291 const auto display = getDisplayDeviceLocked(displayToken);
1292 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001293 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1294 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001295 }
1296
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001297 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001298 // meaning the luminance information is already queried from
1299 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001300 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001301 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1302 capabilities.getDesiredMaxLuminance(),
1303 capabilities.getDesiredMaxAverageLuminance(),
1304 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001305
1306 return NO_ERROR;
1307}
1308
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001309std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1310 const DisplayDevice& display) const {
1311 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1312 // avoid repetitive HAL IPC and EDID parsing.
1313 const auto displayId = display.getId();
1314 LOG_FATAL_IF(!displayId);
1315
1316 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1317 LOG_FATAL_IF(!hwcDisplayId);
1318
1319 uint8_t port;
1320 DisplayIdentificationData data;
1321 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1322 ALOGV("%s: No identification data.", __FUNCTION__);
1323 return {};
1324 }
1325
1326 const auto info = parseDisplayIdentificationData(port, data);
1327 if (!info) {
1328 return {};
1329 }
1330 return info->deviceProductInfo;
1331}
1332
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001333status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1334 ui::PixelFormat* outFormat,
1335 ui::Dataspace* outDataspace,
1336 uint8_t* outComponentMask) const {
1337 if (!outFormat || !outDataspace || !outComponentMask) {
1338 return BAD_VALUE;
1339 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001340
1341 Mutex::Autolock lock(mStateLock);
1342
1343 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1344 if (!displayId) {
1345 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001346 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001347
1348 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001349 outDataspace, outComponentMask);
1350}
1351
Kevin DuBois74e53772018-11-19 10:52:38 -08001352status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1353 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001354 uint64_t maxFrames) {
1355 status_t result = NAME_NOT_FOUND;
Kevin DuBois74e53772018-11-19 10:52:38 -08001356
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001357 postMessageSync(new LambdaMessage([&] {
1358 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1359 result = getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1360 componentMask, maxFrames);
1361 } else {
1362 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1363 }
1364 }));
1365
1366 return result;
Kevin DuBois74e53772018-11-19 10:52:38 -08001367}
1368
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001369status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1370 uint64_t maxFrames, uint64_t timestamp,
1371 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001372 Mutex::Autolock lock(mStateLock);
1373
1374 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1375 if (!displayId) {
1376 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001377 }
1378
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001379 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001380}
1381
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001382status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1383 if (!outSupported) {
1384 return BAD_VALUE;
1385 }
1386 *outSupported = getRenderEngine().supportsProtectedContent();
1387 return NO_ERROR;
1388}
1389
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001390status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1391 bool* outIsWideColorDisplay) const {
1392 if (!displayToken || !outIsWideColorDisplay) {
1393 return BAD_VALUE;
1394 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001395
1396 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001397 const auto display = getDisplayDeviceLocked(displayToken);
1398 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001399 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001400 }
Peiyong Linff84a152019-05-17 18:36:19 -07001401
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001402 *outIsWideColorDisplay =
1403 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001404 return NO_ERROR;
1405}
1406
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001407status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001408 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001409 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001410
Dominik Laskowski6505f792019-09-18 11:10:05 -07001411 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1412 mEventQueue->setEventConnection(
1413 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001414 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001415 }));
1416
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001417 return NO_ERROR;
1418}
1419
1420status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001421 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001422 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001423}
1424
Lloyd Pique755e3192018-01-31 16:46:15 -08001425status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1426 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001427 // Try to acquire a lock for 1s, fail gracefully
1428 const status_t err = mStateLock.timedLock(s2ns(1));
1429 const bool locked = (err == NO_ERROR);
1430 if (!locked) {
1431 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1432 return TIMED_OUT;
1433 }
1434
1435 outLayers->clear();
1436 mCurrentState.traverseInZOrder([&](Layer* layer) {
1437 outLayers->push_back(layer->getLayerDebugInfo());
1438 });
1439
1440 mStateLock.unlock();
1441 return NO_ERROR;
1442}
1443
Peiyong Linc6780972018-10-28 15:24:08 -07001444status_t SurfaceFlinger::getCompositionPreference(
1445 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1446 Dataspace* outWideColorGamutDataspace,
1447 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001448 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001449 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001450 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001451 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001452 return NO_ERROR;
1453}
1454
Dan Stozaec460082018-12-17 15:35:09 -08001455status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1456 const sp<IBinder>& stopLayerHandle,
1457 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001458 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001459 return BAD_VALUE;
1460 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001461
1462 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1463 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001464 return NO_ERROR;
1465}
1466
Dan Stozaec460082018-12-17 15:35:09 -08001467status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001468 if (!listener) {
1469 return BAD_VALUE;
1470 }
Dan Stozaec460082018-12-17 15:35:09 -08001471 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001472 return NO_ERROR;
1473}
Dan Gittik57e63c52019-01-18 16:37:54 +00001474
1475status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1476 bool* outSupport) const {
1477 if (!displayToken || !outSupport) {
1478 return BAD_VALUE;
1479 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001480
1481 Mutex::Autolock lock(mStateLock);
1482
Dan Gittik57e63c52019-01-18 16:37:54 +00001483 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1484 if (!displayId) {
1485 return NAME_NOT_FOUND;
1486 }
1487 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001488 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001489 return NO_ERROR;
1490}
1491
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001492status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001493 if (!displayToken) {
1494 return BAD_VALUE;
1495 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001496
1497 status_t result = NAME_NOT_FOUND;
1498
1499 postMessageSync(new LambdaMessage([&] {
1500 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1501 result = getHwComposer().setDisplayBrightness(*displayId, brightness);
1502 } else {
1503 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1504 }
1505 }));
1506
1507 return result;
Dan Gittik57e63c52019-01-18 16:37:54 +00001508}
1509
Ady Abraham8532d012019-05-08 14:50:56 -07001510status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1511 PowerHint powerHint = static_cast<PowerHint>(hintId);
1512
1513 if (powerHint == PowerHint::INTERACTION) {
1514 mScheduler->notifyTouchEvent();
1515 }
1516
1517 return NO_ERROR;
1518}
1519
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001520// ----------------------------------------------------------------------------
1521
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001522sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001523 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001524 const auto& handle =
1525 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001526
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001527 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001528}
1529
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001530// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001531
1532void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001533 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001534}
1535
1536void SurfaceFlinger::signalTransaction() {
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::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001543 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001544 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001545 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001546}
1547
1548void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001549 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001550 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001551}
1552
1553status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001554 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001555 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001556}
1557
1558status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001559 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001560 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001561 if (res == NO_ERROR) {
1562 msg->wait();
1563 }
1564 return res;
1565}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001566
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001567void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001568 do {
1569 waitForEvent();
1570 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001571}
1572
Dominik Laskowski83b88212018-12-11 13:34:06 -08001573nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001574 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001575 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1576 return 0;
1577 }
1578
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001579 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001580}
1581
Peiyong Line9d809e2020-04-14 13:10:48 -07001582void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001583 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001584 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001585 ATRACE_NAME("SF onVsync");
1586
Steven Thomas3cfac282017-02-06 12:29:30 -08001587 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001588 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001589 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001590 return;
1591 }
1592
Dominik Laskowski075d3172018-05-24 15:50:06 -07001593 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001594 return;
1595 }
1596
Dominik Laskowski075d3172018-05-24 15:50:06 -07001597 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001598 // For now, we don't do anything with external display vsyncs.
1599 return;
1600 }
1601
Alec Mourif8e689c2019-05-20 18:32:22 -07001602 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001603 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001604 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001605 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001606 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001607}
1608
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001609void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001610 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1611 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001612}
1613
Ady Abraham2139f732019-11-13 18:56:40 -08001614bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001615 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001616}
1617
Ady Abraham2139f732019-11-13 18:56:40 -08001618void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1619 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001620 const auto display = getDefaultDisplayDeviceLocked();
1621 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001622 return;
1623 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001624 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001625
Ana Krulec7d1d6832018-12-27 11:10:09 -08001626 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001627 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001628 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001629 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001630 return;
1631 }
1632
Ady Abrahamabc27602020-04-08 17:20:29 -07001633 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001634}
1635
Peiyong Line9d809e2020-04-14 13:10:48 -07001636void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
1637 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001638 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001639 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001640
Lloyd Piqueba04e622017-12-14 17:11:26 -08001641 // Ignore events that do not have the right sequenceId.
1642 if (sequenceId != getBE().mComposerSequenceId) {
1643 return;
1644 }
1645
Steven Thomasb02664d2017-07-26 18:48:28 -07001646 // Only lock if we're not on the main thread. This function is normally
1647 // called on a hwbinder thread, but for the primary display it's called on
1648 // the main thread with the state lock already held, so don't attempt to
1649 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001650 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001651
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001652 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001653
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001654 if (std::this_thread::get_id() == mMainThreadId) {
1655 // Process all pending hot plug events immediately if we are on the main thread.
1656 processDisplayHotplugEventsLocked();
1657 }
1658
Lloyd Piqueba04e622017-12-14 17:11:26 -08001659 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001660}
1661
Ady Abraham7159f572019-10-11 11:10:18 -07001662void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001663 int32_t sequenceId, hal::HWDisplayId /*display*/,
1664 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001665 Mutex::Autolock lock(mStateLock);
1666 if (sequenceId != getBE().mComposerSequenceId) {
1667 return;
1668 }
1669 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001670}
1671
Peiyong Line9d809e2020-04-14 13:10:48 -07001672void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001673 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1674 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1675}
1676
Peiyong Line9d809e2020-04-14 13:10:48 -07001677void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001678 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001679 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001680 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001681 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001682 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001683}
1684
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001685void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001686 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001687
1688 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1689 // display power state.
1690 postMessageAsync(new LambdaMessage(
1691 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1692}
1693
1694void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1695 ATRACE_CALL();
1696
Peiyong Line9d809e2020-04-14 13:10:48 -07001697 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001698
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001699 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001700 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1701 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001702 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001703 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001704 }
Mathias Agopian86303202012-07-24 22:46:10 -07001705}
1706
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001707// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001708void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001709 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001710 // Clear the drawing state so that the logic inside of
1711 // handleTransactionLocked will fire. It will determine the delta between
1712 // mCurrentState and mDrawingState and re-apply all changes when we make the
1713 // transition.
1714 mDrawingState.displays.clear();
1715 mDisplays.clear();
1716}
1717
Steven Thomas050b2c82017-03-06 11:45:16 -08001718void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001719 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001720 if (!mVrFlinger)
1721 return;
1722 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001723 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001724 return;
1725 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001726
Lloyd Pique441d5042018-10-18 16:49:51 -07001727 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001728 ALOGE("Vr flinger is only supported for remote hardware composer"
1729 " service connections. Ignoring request to transition to vr"
1730 " flinger.");
1731 mVrFlingerRequestsDisplay = false;
1732 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001733 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001734
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001735 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001736
Steven Thomas0123ac62018-07-12 11:32:34 -07001737 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001738 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001739
Peiyong Lin65248e02020-04-18 21:15:07 -07001740 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001741
1742 // Clear out all the output layers from the composition engine for all
1743 // displays before destroying the hardware composer interface. This ensures
1744 // any HWC layers are destroyed through that interface before it becomes
1745 // invalid.
1746 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001747 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001748 }
1749
Steven Thomas0123ac62018-07-12 11:32:34 -07001750 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1751 // called below. Clear the reference now so we don't accidentally use it
1752 // later.
1753 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001754
Steven Thomasb02664d2017-07-26 18:48:28 -07001755 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001756 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001757 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001758
Steven Thomasb02664d2017-07-26 18:48:28 -07001759 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001760 // Delete the current instance before creating the new one
1761 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1762 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1763 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001764 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001765
Lloyd Pique441d5042018-10-18 16:49:51 -07001766 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001767 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001768
1769 if (vrFlingerRequestsDisplay) {
1770 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001771 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001772
1773 mVisibleRegionsDirty = true;
1774 invalidateHwcGeometry();
1775
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001776 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001777 display = getDefaultDisplayDeviceLocked();
1778 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001779 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001780
Steven Thomasb02664d2017-07-26 18:48:28 -07001781 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001782 const nsecs_t vsyncPeriod = getVsyncPeriod();
1783 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001784
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001785 // The present fences returned from vr_hwc are not an accurate
1786 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001787 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001788
Steven Thomasb02664d2017-07-26 18:48:28 -07001789 // Use phase of 0 since phase is not known.
1790 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001791 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001792 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001793
Ana Krulecc2870422019-01-29 19:00:58 -08001794 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001795
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001796 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001797 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001798}
1799
Alec Mouri6d414b52020-03-17 11:18:05 -07001800sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001801 // We are storing the last 2 present fences. If sf's phase offset is to be
1802 // woken up before the actual vsync but targeting the next vsync, we need to check
1803 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001804 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1805 : mPreviousPresentFences[1];
1806}
1807
1808bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1809 ATRACE_CALL();
1810 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001811
Ady Abraham11579302019-09-19 12:35:58 -07001812 if (fence == Fence::NO_FENCE) {
1813 return false;
1814 }
1815
1816 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1817 fence->wait(graceTimeMs);
1818 }
1819
1820 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001821}
1822
Alec Mouri6d414b52020-03-17 11:18:05 -07001823nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1824 const sp<Fence>& fence = previousFrameFence();
1825
1826 if (fence == Fence::NO_FENCE) {
1827 return Fence::SIGNAL_TIME_INVALID;
1828 }
1829
1830 return fence->getSignalTime();
1831}
1832
Ady Abraham5facfb12020-04-22 15:18:31 -07001833nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001834 DisplayStatInfo stats;
1835 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001836 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001837 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001838 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001839}
1840
Ady Abraham5facfb12020-04-22 15:18:31 -07001841void SurfaceFlinger::onMessageReceived(int32_t what,
1842 nsecs_t expectedVSyncTime) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001843 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001844 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001845 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001846 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001847 // calculate the expected present time once and use the cached
1848 // value throughout this frame to make sure all layers are
1849 // seeing this same value.
Alec Mouri6d414b52020-03-17 11:18:05 -07001850 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
Ady Abraham5facfb12020-04-22 15:18:31 -07001851 mExpectedPresentTime = expectedVSyncTime;
Ady Abraham7c03ce62019-07-19 10:59:45 -07001852
Ady Abraham11579302019-09-19 12:35:58 -07001853 // When Backpressure propagation is enabled we want to give a small grace period
1854 // for the present fence to fire instead of just giving up on this frame to handle cases
1855 // where present fence is just about to get signaled.
1856 const int graceTimeForPresentFenceMs =
1857 (mPropagateBackpressure &&
1858 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1859 ? 1
1860 : 0;
Alec Mouri6d414b52020-03-17 11:18:05 -07001861
1862 // Pending frames may trigger backpressure propagation.
1863 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1864 previousFramePending(
1865 graceTimeForPresentFenceMs)};
1866
1867 // Frame missed counts for metrics tracking.
1868 // A frame is missed if the prior frame is still pending. If no longer pending,
1869 // then we still count the frame as missed if the predicted present time
1870 // was further in the past than when the fence actually fired.
1871
1872 // Add some slop to correct for drift. This should generally be
1873 // smaller than a typical frame duration, but should not be so small
1874 // that it reports reasonable drift as a missed frame.
1875 DisplayStatInfo stats;
1876 mScheduler->getDisplayStatInfo(&stats);
1877 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1878 const nsecs_t previousPresentTime = previousFramePresentTime();
1879 const TracedOrdinal<bool> frameMissed =
1880 {"PrevFrameMissed",
1881 framePending ||
1882 (previousPresentTime >= 0 &&
1883 (lastExpectedPresentTime < previousPresentTime - frameMissedSlop))};
1884 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001885 mHadDeviceComposition && frameMissed};
Alec Mouri6d414b52020-03-17 11:18:05 -07001886 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001887 mHadClientComposition && frameMissed};
1888
Alec Mouricc0fc602019-02-26 21:45:19 -08001889 if (frameMissed) {
1890 mFrameMissedCount++;
1891 mTimeStats->incrementMissedFrames();
Alec Mouri5f487d42020-02-06 09:26:19 -08001892 if (mMissedFrameJankCount == 0) {
1893 mMissedFrameJankStart = systemTime();
1894 }
1895 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001896 }
1897
Alec Mouri40189b02019-03-05 15:07:54 -08001898 if (hwcFrameMissed) {
1899 mHwcFrameMissedCount++;
1900 }
1901
1902 if (gpuFrameMissed) {
1903 mGpuFrameMissedCount++;
1904 }
1905
Ady Abraham27cbed72020-04-10 12:56:59 -07001906 // If we are in the middle of a config change and the fence hasn't
1907 // fired yet just wait for the next invalidate
1908 if (mSetActiveConfigPending) {
1909 if (framePending) {
1910 mEventQueue->invalidate();
1911 break;
1912 }
1913
1914 // We received the present fence from the HWC, so we assume it successfully updated
1915 // the config, hence we update SF.
1916 mSetActiveConfigPending = false;
1917 setActiveConfigInternal();
1918 }
1919
Alec Mouri6d414b52020-03-17 11:18:05 -07001920 if (framePending && mPropagateBackpressure) {
Ady Abrahamadb9a992019-09-19 21:21:55 +00001921 if ((hwcFrameMissed && !gpuFrameMissed) ||
1922 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001923 signalLayerUpdate();
1924 break;
1925 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001926 }
Dan Stoza50182882016-07-08 12:02:20 -07001927
Alec Mouri5f487d42020-02-06 09:26:19 -08001928 // Our jank window is always at least 100ms since we missed a
1929 // frame...
1930 static constexpr nsecs_t kMinJankyDuration =
1931 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1932 // ...but if it's larger than 1s then we missed the trace cutoff.
1933 static constexpr nsecs_t kMaxJankyDuration =
1934 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1935 // If we're in a user build then don't push any atoms
1936 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1937 const auto displayDevice = getDefaultDisplayDeviceLocked();
1938 // Only report jank when the display is on, as displays in DOZE
1939 // power mode may operate at a different frame rate than is
1940 // reported in their config, which causes noticeable (but less
1941 // severe) jank.
Peiyong Lin65248e02020-04-18 21:15:07 -07001942 if (displayDevice && displayDevice->getPowerMode() == hal::PowerMode::ON) {
Alec Mouri5f487d42020-02-06 09:26:19 -08001943 const nsecs_t currentTime = systemTime();
1944 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1945 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1946 ATRACE_NAME("Jank detected");
1947 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1948 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1949 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1950 jankyDurationMillis, mMissedFrameJankCount);
1951 }
1952
1953 // We either reported a jank event or we missed the trace
1954 // window, so clear counters here.
1955 if (jankDuration > kMinJankyDuration) {
1956 mMissedFrameJankCount = 0;
1957 mMissedFrameJankStart = 0;
1958 }
1959 }
1960 }
1961
Steven Thomas050b2c82017-03-06 11:45:16 -08001962 // Now that we're going to make it to the handleMessageTransaction()
1963 // call below it's safe to call updateVrFlinger(), which will
1964 // potentially trigger a display handoff.
1965 updateVrFlinger();
1966
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001967 if (mTracingEnabledChanged) {
1968 mTracingEnabled = mTracing.isEnabled();
1969 mTracingEnabledChanged = false;
1970 }
1971
Vishnu Nair60db8c02020-04-02 11:55:16 -07001972 bool refreshNeeded;
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001973 {
1974 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1975
Vishnu Nair60db8c02020-04-02 11:55:16 -07001976 refreshNeeded = handleMessageTransaction();
1977 refreshNeeded |= handleMessageInvalidate();
1978 if (mTracingEnabled) {
1979 mAddCompositionStateToTrace =
1980 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1981 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1982 mTracing.notifyLocked("visibleRegionsDirty");
1983 }
1984 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001985 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001986
Ana Krulecc84d09b2019-11-02 23:10:29 +01001987 // Layers need to get updated (in the previous line) before we can use them for
1988 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001989 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1990 // and may eventually call to ~Layer() if it holds the last reference
1991 {
1992 Mutex::Autolock _l(mStateLock);
1993 mScheduler->chooseRefreshRateForContent();
1994 }
1995
Ady Abraham27cbed72020-04-10 12:56:59 -07001996 performSetActiveConfig();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001997
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001998 updateCursorAsync();
1999 updateInputFlinger();
2000
Dan Stoza58784442014-12-02 16:58:17 -08002001 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002002 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08002003 // Signal a refresh if a transaction modified the window state,
2004 // a new buffer was latched, or if HWC has requested a full
2005 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08002006 if (mFrameStartTime <= 0) {
2007 // We should only use the time of the first invalidate
2008 // message that signals a refresh as the beginning of the
2009 // frame. Otherwise the real frame time will be
2010 // underestimated.
2011 mFrameStartTime = frameStart;
2012 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08002013 signalRefresh();
2014 }
2015 break;
2016 }
2017 case MessageQueue::REFRESH: {
2018 handleMessageRefresh();
2019 break;
2020 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002021 }
2022}
2023
Dan Stoza6b9454d2014-11-07 16:00:59 -08002024bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08002025 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002026 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002027
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002028 bool flushedATransaction = flushTransactionQueues();
2029
2030 bool runHandleTransaction = transactionFlags &&
2031 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
2032
2033 if (runHandleTransaction) {
2034 handleTransaction(eTransactionMask);
2035 } else {
2036 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002037 }
2038
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002039 if (transactionFlushNeeded()) {
2040 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002041 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002042
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002043 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002044}
2045
Mathias Agopian4fec8732012-06-29 14:12:52 -07002046void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002047 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002048
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002049 mRefreshPending = false;
2050
Lloyd Piqueab039b52019-02-13 14:22:42 -08002051 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002052 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002053 for (const auto& [_, display] : mDisplays) {
2054 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2055 }
2056 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002057 if (auto layerFE = layer->getCompositionEngineLayerFE())
2058 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002059 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002060 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2061 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002062 if (auto layerFE = layer->getCompositionEngineLayerFE())
2063 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002064 }
2065
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002066 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002067 refreshArgs.outputColorSetting = useColorManagement
2068 ? mDisplayColorSetting
2069 : compositionengine::OutputColorSetting::kUnmanaged;
2070 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2071 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002072
2073 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2074 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002075 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002076
2077 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2078 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2079 mDrawingState.colorMatrixChanged = false;
2080 }
2081
2082 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2083
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002084 if (mDebugRegion != 0) {
2085 refreshArgs.devOptFlashDirtyRegionsDelay =
2086 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2087 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002088
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002089 mGeometryInvalid = false;
2090
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002091 // Store the present time just before calling to the composition engine so we could notify
2092 // the scheduler.
2093 const auto presentTime = systemTime();
2094
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002095 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002096 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2097 // Reset the frame start time now that we've recorded this frame.
2098 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002099
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002100 mScheduler->onDisplayRefreshed(presentTime);
2101
David Sodmanfa9b2af2017-12-24 13:28:59 -08002102 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002103 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002104
Alec Mouri8f7a0102020-04-15 12:11:10 -07002105 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2106
Lloyd Pique66d68602019-02-13 14:23:31 -08002107 mHadClientComposition =
2108 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2109 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002110 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2111 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002112 });
2113 mHadDeviceComposition =
2114 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2115 auto& displayDevice = tokenDisplayPair.second;
2116 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2117 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002118 mReusedClientComposition =
2119 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2120 auto& displayDevice = tokenDisplayPair.second;
2121 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2122 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002123
Alec Mouri8f7a0102020-04-15 12:11:10 -07002124 // Only report a strategy change if we move in and out of composition with hw overlays
2125 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2126 mTimeStats->incrementCompositionStrategyChanges();
2127 }
2128
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002129 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002130
David Sodman7e4ae112018-02-09 15:02:28 -08002131 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002132 if (mVisibleRegionsDirty) {
2133 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002134 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002135 mTracing.notify("visibleRegionsDirty");
2136 }
2137 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002138
2139 if (mCompositionEngine->needsAnotherUpdate()) {
2140 signalLayerUpdate();
2141 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002142}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002143
David Sodmanfa9b2af2017-12-24 13:28:59 -08002144
2145bool SurfaceFlinger::handleMessageInvalidate() {
2146 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002147 bool refreshNeeded = handlePageFlip();
2148
Vishnu Nair4351ad52019-02-11 14:13:02 -08002149 if (mVisibleRegionsDirty) {
2150 computeLayerBounds();
2151 }
2152
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002153 for (auto& layer : mLayersPendingRefresh) {
2154 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002155 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002156 invalidateLayerStack(layer, visibleReg);
2157 }
2158 mLayersPendingRefresh.clear();
2159 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002160}
2161
Ana Krulece588e312018-09-18 12:32:24 -07002162void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2163 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002164 // Update queue of past composite+present times and determine the
2165 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002166 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002167 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002168 while (!getBE().mCompositePresentTimes.empty()) {
2169 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002170 // Cached values should have been updated before calling this method,
2171 // which helps avoid duplicate syscalls.
2172 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2173 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2174 break;
2175 }
2176 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002177 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002178 }
2179
2180 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002181 while (getBE().mCompositePresentTimes.size() > 16) {
2182 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002183 }
2184
Ana Krulece588e312018-09-18 12:32:24 -07002185 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002186}
2187
Ana Krulece588e312018-09-18 12:32:24 -07002188void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2189 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002190 // Integer division and modulo round toward 0 not -inf, so we need to
2191 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002192 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2193 ? (stats.vsyncPeriod -
2194 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2195 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002196
Ady Abraham9e16a482019-12-03 17:19:41 -08002197 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002198 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002199 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002200 }
2201
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002202 // Snap the latency to a value that removes scheduling jitter from the
2203 // composition and present times, which often have >1ms of jitter.
2204 // Reducing jitter is important if an app attempts to extrapolate
2205 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002206 // Snapping also allows an app to precisely calculate
2207 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002208 nsecs_t bias = stats.vsyncPeriod / 2;
2209 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2210 nsecs_t snappedCompositeToPresentLatency =
2211 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002212
David Sodman99974d22017-11-28 12:04:33 -08002213 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002214 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2215 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002216 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002217}
2218
David Sodman2b406362017-12-15 13:33:47 -08002219void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002220{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002221 ATRACE_CALL();
2222 ALOGV("postComposition");
2223
Brian Andersonf6386862016-10-31 16:34:13 -07002224 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002225 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002226 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002227 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002228 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002229 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002230
David Sodman73beded2017-11-15 11:56:06 -08002231 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002232 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002233 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002234 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002235 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2236 ->getRenderSurface()
2237 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002238 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002239 } else {
2240 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2241 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002242
David Sodman73beded2017-11-15 11:56:06 -08002243 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002244 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2245 mPreviousPresentFences[0] = displayDevice
2246 ? getHwComposer().getPresentFence(*displayDevice->getId())
2247 : Fence::NO_FENCE;
2248 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002249 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002250
Ana Krulece588e312018-09-18 12:32:24 -07002251 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002252 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002253
Lloyd Piqueab039b52019-02-13 14:22:42 -08002254 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2255 // be sampled a little later than when we started doing work for this frame,
2256 // but that should be okay since updateCompositorTiming has snapping logic.
2257 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2258 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002259 CompositorTiming compositorTiming;
2260 {
David Sodman99974d22017-11-28 12:04:33 -08002261 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2262 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002263 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002264
Edgar Arriaga844fa672020-01-16 14:21:42 -08002265 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002266 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2267 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002268 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002269 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002270 }
Robert Carr2047fae2016-11-28 14:09:09 -08002271 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002272
Valerie Hau4b678442020-04-14 10:50:42 -07002273 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2274 mTransactionCompletedThread.sendCallbacks();
2275
Ady Abraham92fa2f42020-02-11 15:33:56 -08002276 if (displayDevice && displayDevice->isPrimary() &&
Peiyong Lin65248e02020-04-18 21:15:07 -07002277 displayDevice->getPowerMode() == hal::PowerMode::ON && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002278 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002279 }
2280
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002281 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002282 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2283 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002284 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002285 }
2286 }
2287
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002288 if (mAnimCompositionPending) {
2289 mAnimCompositionPending = false;
2290
Brian Anderson4e606e32017-03-16 15:34:57 -07002291 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002292 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002293 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002294 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002295 // The HWC doesn't support present fences, so use the refresh
2296 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002297 const nsecs_t presentTime =
2298 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002299 mAnimFrameTracker.setActualPresentTime(presentTime);
2300 }
2301 mAnimFrameTracker.advanceFrame();
2302 }
Dan Stozab90cf072015-03-05 11:05:59 -08002303
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002304 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002305 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002306 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002307 }
2308
Vishnu Nair9b079a22020-01-21 14:36:08 -08002309 if (mReusedClientComposition) {
2310 mTimeStats->incrementClientCompositionReusedFrames();
2311 }
2312
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002313 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002314
Alec Mouri717bcb62020-02-10 17:07:19 -08002315 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2316 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2317 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2318
Lloyd Pique32cbe282018-10-19 13:09:22 -07002319 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2320 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002321 return;
2322 }
2323
2324 nsecs_t currentTime = systemTime();
2325 if (mHasPoweredOff) {
2326 mHasPoweredOff = false;
2327 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002328 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002329 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002330 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2331 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002332 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002333 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002334 }
David Sodman4a36e932017-11-07 14:29:47 -08002335 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002336 }
David Sodman4a36e932017-11-07 14:29:47 -08002337 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002338
2339 {
2340 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002341 if (mTexturePool.size() < mTexturePoolSize) {
2342 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002343 const size_t offset = mTexturePool.size();
2344 mTexturePool.resize(mTexturePoolSize);
2345 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2346 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002347 } else if (mTexturePool.size() > mTexturePoolSize) {
2348 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2349 const size_t offset = mTexturePoolSize;
2350 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2351 mTexturePool.resize(mTexturePoolSize);
2352 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002353 }
2354 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002355
Kevin DuBois413287f2019-02-25 08:46:47 -08002356 if (mLumaSampling && mRegionSamplingThread) {
2357 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002358 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002359
2360 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2361 // side-effect of getTotalSize(), so we check that again here
2362 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002363 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002364 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2365 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002366}
2367
Lloyd Pique7eebe692020-04-22 22:40:06 -07002368FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2369 return displayDevice.getViewport().toFloatRect();
2370}
2371
Vishnu Nair4351ad52019-02-11 14:13:02 -08002372void SurfaceFlinger::computeLayerBounds() {
2373 for (const auto& pair : mDisplays) {
2374 const auto& displayDevice = pair.second;
2375 const auto display = displayDevice->getCompositionDisplay();
2376 for (const auto& layer : mDrawingState.layersSortedByZ) {
2377 // only consider the layers on the given layer stack
2378 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002379 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002380 }
2381
Lloyd Pique7eebe692020-04-22 22:40:06 -07002382 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002383 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002384 }
2385 }
2386}
2387
David Sodmanfa9b2af2017-12-24 13:28:59 -08002388void SurfaceFlinger::postFrame()
2389{
2390 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002391 const auto display = getDefaultDisplayDeviceLocked();
2392 if (display && getHwComposer().isConnected(*display->getId())) {
2393 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002394 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2395 logFrameStats();
2396 }
2397 }
2398}
2399
Mathias Agopian87baae12012-07-31 12:38:26 -07002400void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002401{
Mathias Agopian841cde52012-03-01 15:44:37 -08002402 ATRACE_CALL();
2403
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002404 // here we keep a copy of the drawing state (that is the state that's
2405 // going to be overwritten by handleTransactionLocked()) outside of
2406 // mStateLock so that the side-effects of the State assignment
2407 // don't happen with mStateLock held (which can cause deadlocks).
2408 State drawingState(mDrawingState);
2409
Mathias Agopianca4d3602011-05-19 15:38:14 -07002410 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002411 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002412
Mathias Agopianca4d3602011-05-19 15:38:14 -07002413 // Here we're guaranteed that some transaction flags are set
2414 // so we can call handleTransactionLocked() unconditionally.
2415 // We call getTransactionFlags(), which will also clear the flags,
2416 // with mStateLock held to guarantee that mCurrentState won't change
2417 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002418
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002419 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002420 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002421 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002422
Mathias Agopianca4d3602011-05-19 15:38:14 -07002423 mDebugInTransaction = 0;
2424 invalidateHwcGeometry();
2425 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002426}
2427
Lloyd Piqueba04e622017-12-14 17:11:26 -08002428void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2429 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 const std::optional<DisplayIdentificationInfo> info =
2431 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002432
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002434 continue;
2435 }
2436
Dominik Laskowski55c85402020-01-21 16:25:47 -08002437 const DisplayId displayId = info->id;
2438 const auto it = mPhysicalDisplayTokens.find(displayId);
2439
Peiyong Line9d809e2020-04-14 13:10:48 -07002440 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002441 if (it == mPhysicalDisplayTokens.end()) {
2442 ALOGV("Creating display %s", to_string(displayId).c_str());
2443
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002444 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002445 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002446 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002447
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 DisplayDeviceState state;
Marin Shalamanov700e6392020-02-12 20:22:26 +01002449 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2450 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002451 state.isSecure = true; // All physical displays are currently considered secure.
2452 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002453
2454 sp<IBinder> token = new BBinder();
2455 mCurrentState.displays.add(token, state);
2456 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2457
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002459 } else {
2460 ALOGV("Recreating display %s", to_string(displayId).c_str());
2461
2462 const auto token = it->second;
2463 auto& state = mCurrentState.displays.editValueFor(token);
2464 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002465 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002466 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002467 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002468
Dominik Laskowski55c85402020-01-21 16:25:47 -08002469 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002470 if (index >= 0) {
2471 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2472 mInterceptor->saveDisplayDeletion(state.sequenceId);
2473 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002474 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002475 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002476 }
2477
2478 processDisplayChangesLocked();
2479 }
2480
2481 mPendingHotplugEvents.clear();
2482}
2483
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002484void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002485 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2486 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002487}
2488
Lloyd Pique99d3da52018-01-22 17:48:03 -08002489sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002490 const wp<IBinder>& displayToken,
2491 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002492 const DisplayDeviceState& state,
2493 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002494 const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique9370a482019-10-03 17:58:30 -07002495 auto displayId = compositionDisplay->getDisplayId();
2496 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002497 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002498 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002499 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002500 creationArgs.hasWideColorGamut = false;
2501 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002502
Dominik Laskowski55c85402020-01-21 16:25:47 -08002503 if (const auto& physical = state.physical) {
2504 creationArgs.connectionType = physical->type;
2505 }
2506
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002507 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002508 creationArgs.isPrimary = isInternalDisplay;
2509
2510 if (useColorManagement && displayId) {
2511 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002512 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002513 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002514 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002516
Dominik Laskowski7e045462018-05-30 13:02:02 -07002517 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002518 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002519 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002520 }
tangrobin6753a022018-08-10 10:58:54 +08002521 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522
Dominik Laskowski075d3172018-05-24 15:50:06 -07002523 if (displayId) {
2524 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002525 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002526 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002527 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002528
Lloyd Pique90c115d2018-09-18 21:39:42 -07002529 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002530 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002531 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002532
Lloyd Pique99d3da52018-01-22 17:48:03 -08002533 // Make sure that composition can never be stalled by a virtual display
2534 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002535 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002536 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002537 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2538 }
2539
Dominik Laskowski718f9602019-11-09 20:01:35 -08002540 creationArgs.physicalOrientation =
2541 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002542
Lloyd Pique99d3da52018-01-22 17:48:03 -08002543 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002544 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002545
Lloyd Pique9370a482019-10-03 17:58:30 -07002546 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547
2548 if (maxFrameBufferAcquiredBuffers >= 3) {
2549 nativeWindowSurface->preallocateBuffers();
2550 }
2551
2552 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002553 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002554 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002555 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002556 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002558 display->getCompositionDisplay()->setColorProfile(
2559 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2560 RenderIntent::COLORIMETRIC,
2561 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002562 if (!state.isVirtual()) {
2563 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002564 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2565 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002566 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002568 display->setLayerStack(state.layerStack);
2569 display->setProjection(state.orientation, state.viewport, state.frame);
2570 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002571
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002572 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002573}
2574
Marin Shalamanovae685592020-02-12 17:12:22 +01002575void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2576 const DisplayDeviceState& state) {
2577 int width = 0;
2578 int height = 0;
2579 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2580 if (state.physical) {
2581 const auto& activeConfig =
2582 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2583 width = activeConfig->getWidth();
2584 height = activeConfig->getHeight();
2585 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2586 } else if (state.surface != nullptr) {
2587 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2588 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2589 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2590 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2591 int intPixelFormat;
2592 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2593 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2594 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2595 } else {
2596 // Virtual displays without a surface are dormant:
2597 // they have external state (layer stack, projection,
2598 // etc.) but no internal state (i.e. a DisplayDevice).
2599 return;
2600 }
2601
2602 compositionengine::DisplayCreationArgsBuilder builder;
2603 if (const auto& physical = state.physical) {
2604 builder.setPhysical({physical->id, physical->type});
2605 }
2606 builder.setPixels(ui::Size(width, height));
2607 builder.setPixelFormat(pixelFormat);
2608 builder.setIsSecure(state.isSecure);
2609 builder.setLayerStackId(state.layerStack);
2610 builder.setPowerAdvisor(&mPowerAdvisor);
2611 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2612 builder.setName(state.displayName);
2613 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2614
2615 sp<compositionengine::DisplaySurface> displaySurface;
2616 sp<IGraphicBufferProducer> producer;
2617 sp<IGraphicBufferProducer> bqProducer;
2618 sp<IGraphicBufferConsumer> bqConsumer;
2619 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2620
2621 std::optional<DisplayId> displayId = compositionDisplay->getId();
2622
2623 if (state.isVirtual()) {
2624 sp<VirtualDisplaySurface> vds =
2625 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2626 bqConsumer, state.displayName);
2627
2628 displaySurface = vds;
2629 producer = vds;
2630 } else {
2631 ALOGE_IF(state.surface != nullptr,
2632 "adding a supported display, but rendering "
2633 "surface is provided (%p), ignoring it",
2634 state.surface.get());
2635
2636 LOG_ALWAYS_FATAL_IF(!displayId);
2637 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2638 maxGraphicsWidth, maxGraphicsHeight);
2639 producer = bqProducer;
2640 }
2641
Marin Shalamanov700e6392020-02-12 20:22:26 +01002642 LOG_FATAL_IF(!displaySurface);
2643 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2644 displaySurface, producer);
2645 mDisplays.emplace(displayToken, display);
2646 if (!state.isVirtual()) {
2647 LOG_FATAL_IF(!displayId);
2648 dispatchDisplayHotplugEvent(displayId->value, true);
2649 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002650
Marin Shalamanov700e6392020-02-12 20:22:26 +01002651 if (display->isPrimary()) {
2652 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanovae685592020-02-12 17:12:22 +01002653 }
2654}
2655
2656void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2657 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2658 // Save display ID before disconnecting.
2659 const auto displayId = display->getId();
2660 display->disconnect();
2661
2662 if (!display->isVirtual()) {
Marin Shalamanov700e6392020-02-12 20:22:26 +01002663 LOG_FATAL_IF(!displayId);
Marin Shalamanovae685592020-02-12 17:12:22 +01002664 dispatchDisplayHotplugEvent(displayId->value, false);
2665 }
2666 }
2667
2668 mDisplays.erase(displayToken);
2669}
2670
2671void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2672 const DisplayDeviceState& currentState,
2673 const DisplayDeviceState& drawingState) {
2674 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2675 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002676 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002677 // changing the surface is like destroying and recreating the DisplayDevice
2678 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2679 display->disconnect();
2680 }
2681 mDisplays.erase(displayToken);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002682 if (const auto& physical = currentState.physical) {
2683 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2684 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002685 processDisplayAdded(displayToken, currentState);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002686 if (currentState.physical) {
2687 initializeDisplays();
2688 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002689 return;
2690 }
2691
2692 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2693 if (currentState.layerStack != drawingState.layerStack) {
2694 display->setLayerStack(currentState.layerStack);
2695 }
2696 if ((currentState.orientation != drawingState.orientation) ||
2697 (currentState.viewport != drawingState.viewport) ||
2698 (currentState.frame != drawingState.frame)) {
2699 display->setProjection(currentState.orientation, currentState.viewport,
2700 currentState.frame);
2701 }
2702 if (currentState.width != drawingState.width ||
2703 currentState.height != drawingState.height) {
2704 display->setDisplaySize(currentState.width, currentState.height);
2705 if (display->isPrimary()) {
2706 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2707 }
2708 }
2709 }
2710}
2711
Lloyd Pique347200f2017-12-14 17:00:15 -08002712void SurfaceFlinger::processDisplayChangesLocked() {
2713 // here we take advantage of Vector's copy-on-write semantics to
2714 // improve performance by skipping the transaction entirely when
2715 // know that the lists are identical
2716 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2717 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2718 if (!curr.isIdenticalTo(draw)) {
2719 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002720
2721 // find the displays that were removed
2722 // (ie: in drawing state but not in current state)
2723 // also handle displays that changed
2724 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01002725 for (size_t i = 0; i < draw.size(); i++) {
2726 const wp<IBinder>& displayToken = draw.keyAt(i);
2727 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002728 if (j < 0) {
2729 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01002730 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002731 } else {
2732 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01002733 const DisplayDeviceState& currentState = curr[j];
2734 const DisplayDeviceState& drawingState = draw[i];
2735 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002737 }
2738
2739 // find displays that were added
2740 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01002741 for (size_t i = 0; i < curr.size(); i++) {
2742 const wp<IBinder>& displayToken = curr.keyAt(i);
2743 if (draw.indexOfKey(displayToken) < 0) {
2744 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 }
2746 }
2747 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002748
2749 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002750}
2751
Mathias Agopian87baae12012-07-31 12:38:26 -07002752void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002753{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002754 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2755
Dan Stoza7dde5992015-05-22 09:51:44 -07002756 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002757 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002758 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002759 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002760
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 /*
2762 * Traversal of the children
2763 * (perform the transaction for each of them if needed)
2764 */
2765
Marissa Wall06255332019-03-27 13:48:27 -07002766 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002767 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002769 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770
2771 const uint32_t flags = layer->doTransaction(0);
2772 if (flags & Layer::eVisibleRegion)
2773 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002774
2775 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002776 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002777 }
Robert Carr2047fae2016-11-28 14:09:09 -08002778 });
Marissa Wall06255332019-03-27 13:48:27 -07002779 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780 }
2781
2782 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002783 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002784 */
2785
Mathias Agopiane57f2922012-08-09 16:29:12 -07002786 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002787 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002788 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002789 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002791 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002792 // The transform hint might have changed for some layers
2793 // (either because a display has changed, or because a layer
2794 // as changed).
2795 //
2796 // Walk through all the layers in currentLayers,
2797 // and update their transform hint.
2798 //
2799 // If a layer is visible only on a single display, then that
2800 // display is used to calculate the hint, otherwise we use the
2801 // default display.
2802 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002803 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002804 // the hint is set before we acquire a buffer from the surface texture.
2805 //
2806 // NOTE: layer transactions have taken place already, so we use their
2807 // drawing state. However, SurfaceFlinger's own transaction has not
2808 // happened yet, so we must use the current state layer list
2809 // (soon to become the drawing state list).
2810 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002811 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002812 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002813 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002814 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002815 // NOTE: we rely on the fact that layers are sorted by
2816 // layerStack first (so we don't have to traverse the list
2817 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002818 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002819 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002820 currentlayerStack = layerStack;
2821 // figure out if this layerstack is mirrored
2822 // (more than one display) if so, pick the default display,
2823 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002824 hintDisplay = nullptr;
2825 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002826 if (display->getCompositionDisplay()
2827 ->belongsInOutput(layer->getLayerStack(),
2828 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002829 if (hintDisplay) {
2830 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002831 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002832 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002833 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002834 }
2835 }
2836 }
2837 }
Chet Haase91d25932013-04-11 15:24:55 -07002838
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002839 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002840 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2841 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002842
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002843 // could be null when this layer is using a layerStack
2844 // that is not visible on any display. Also can occur at
2845 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002846 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002847 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002848
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002849 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002850 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002851 if (hintDisplay) {
2852 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002853 }
Robert Carr2047fae2016-11-28 14:09:09 -08002854
2855 first = false;
2856 });
Mathias Agopian84300952012-11-21 16:02:13 -08002857 }
2858
2859
Mathias Agopian3559b072012-08-15 13:46:03 -07002860 /*
2861 * Perform our own transaction if needed
2862 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002863
2864 if (mLayersAdded) {
2865 mLayersAdded = false;
2866 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002867 mVisibleRegionsDirty = true;
2868 }
2869
2870 // some layers might have been removed, so
2871 // we need to update the regions they're exposing.
2872 if (mLayersRemoved) {
2873 mLayersRemoved = false;
2874 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002875 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002876 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002877 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002878 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002879 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002880 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002881 }
Robert Carr2047fae2016-11-28 14:09:09 -08002882 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883 }
2884
Vishnu Nairec0ab382019-02-13 15:32:56 -08002885 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002887}
2888
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002889void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002890 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002891 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002892 return;
2893 }
2894
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002895 if (mVisibleRegionsDirty || mInputInfoChanged) {
2896 mInputInfoChanged = false;
2897 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002898 } else if (mInputWindowCommands.syncInputWindows) {
2899 // If the caller requested to sync input windows, but there are no
2900 // changes to input windows, notify immediately.
2901 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002902 }
2903
Arthur Hung6cbb9752019-09-05 16:38:18 +08002904 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002905}
2906
2907void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002908 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002909
2910 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2911 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002912 // When calculating the screen bounds we ignore the transparent region since it may
2913 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002914 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002915 }
2916 });
chaviw291d88a2019-02-14 10:33:58 -08002917
2918 mInputFlinger->setInputWindows(inputHandles,
2919 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2920 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002921}
2922
Vishnu Nairec0ab382019-02-13 15:32:56 -08002923void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002924 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002925 mPendingInputWindowCommands.clear();
2926}
2927
Riley Andrews03414a12014-07-01 14:22:59 -07002928void SurfaceFlinger::updateCursorAsync()
2929{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002930 compositionengine::CompositionRefreshArgs refreshArgs;
2931 for (const auto& [_, display] : mDisplays) {
2932 if (display->getId()) {
2933 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002934 }
2935 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002936
2937 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002938}
2939
Ady Abraham2139f732019-11-13 18:56:40 -08002940void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002941 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2942 // If this is called from the main thread mStateLock must be locked before
2943 // Currently the only way to call this function from the main thread is from
2944 // Sheduler::chooseRefreshRateForContent
2945
2946 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002947 changeRefreshRateLocked(refreshRate, event);
2948}
2949
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002950void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2951 if (mScheduler) {
2952 // In practice it's not allowed to hotplug in/out the primary display once it's been
2953 // connected during startup, but some tests do it, so just warn and return.
2954 ALOGW("Can't re-init scheduler");
2955 return;
2956 }
2957
Ady Abraham2139f732019-11-13 18:56:40 -08002958 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002959 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002960 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002961 primaryDisplayId),
2962 currentConfig);
2963 mRefreshRateStats =
2964 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002965 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002966 mRefreshRateStats->setConfigMode(currentConfig);
2967
Ady Abraham9e16a482019-12-03 17:19:41 -08002968 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2969
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002970 // start the EventThread
2971 mScheduler =
2972 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002973 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002974 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002975 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002976 impl::EventThread::InterceptVSyncsCallback());
2977 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002978 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002979 [this](nsecs_t timestamp) {
2980 mInterceptor->saveVSyncEvent(timestamp);
2981 });
2982
2983 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2984 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002985 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002986
2987 mRegionSamplingThread =
2988 new RegionSamplingThread(*this, *mScheduler,
2989 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002990 // Dispatch a config change request for the primary display on scheduler
2991 // initialization, so that the EventThreads always contain a reference to a
2992 // prior configuration.
2993 //
2994 // This is a bit hacky, but this avoids a back-pointer into the main SF
2995 // classes from EventThread, and there should be no run-time binder cost
2996 // anyway since there are no connected apps at this point.
2997 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002998 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Alec Mouri60aee1c2019-10-28 16:18:59 -07002999 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
3000 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003001}
3002
Mathias Agopian4fec8732012-06-29 14:12:52 -07003003void SurfaceFlinger::commitTransaction()
3004{
Vishnu Nair60db8c02020-04-02 11:55:16 -07003005 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003006 mTransactionPending = false;
3007 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003008 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003009}
3010
Lloyd Pique58e24a32019-08-01 15:50:14 -07003011void SurfaceFlinger::commitTransactionLocked() {
3012 if (!mLayersPendingRemoval.isEmpty()) {
3013 // Notify removed layers now that they can't be drawn from
3014 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003015 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003016
3017 // Ensure any buffers set to display on any children are released.
3018 if (l->isRemovedFromCurrentState()) {
3019 l->latchAndReleaseBuffer();
3020 }
3021
3022 // If the layer has been removed and has no parent, then it will not be reachable
3023 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3024 // ensure we can copy its current to drawing state.
3025 if (!l->getParent()) {
3026 mOffscreenLayers.emplace(l.get());
3027 }
3028 }
3029 mLayersPendingRemoval.clear();
3030 }
3031
3032 // If this transaction is part of a window animation then the next frame
3033 // we composite should be considered an animation as well.
3034 mAnimCompositionPending = mAnimTransactionPending;
3035
3036 mDrawingState = mCurrentState;
3037 // clear the "changed" flags in current state
3038 mCurrentState.colorMatrixChanged = false;
3039
Edgar Arriaga844fa672020-01-16 14:21:42 -08003040 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003041 layer->commitChildList();
3042
3043 // If the layer can be reached when traversing mDrawingState, then the layer is no
3044 // longer offscreen. Remove the layer from the offscreenLayer set.
3045 if (mOffscreenLayers.count(layer)) {
3046 mOffscreenLayers.erase(layer);
3047 }
3048 });
3049
3050 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003051 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003052}
3053
chaviw74d90ad2019-04-26 14:45:26 -07003054void SurfaceFlinger::commitOffscreenLayers() {
3055 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003056 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003057 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3058 if (!trFlags) return;
3059
3060 layer->doTransaction(0);
3061 layer->commitChildList();
3062 });
3063 }
3064}
3065
Chia-I Wuab0c3192017-08-01 11:29:00 -07003066void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003067 for (const auto& [token, displayDevice] : mDisplays) {
3068 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003069 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003070 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003071 }
3072 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003073}
3074
Dan Stoza6b9454d2014-11-07 16:00:59 -08003075bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076{
Ady Abraham09bd3922019-04-08 10:44:56 -07003077 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003078 ALOGV("handlePageFlip");
3079
Brian Andersond6927fb2016-07-23 23:37:30 -07003080 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081
Mathias Agopian4fec8732012-06-29 14:12:52 -07003082 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003083 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003084 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003085
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003086 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3087
Eric Penner51c59cd2014-07-28 19:51:58 -07003088 // Store the set of layers that need updates. This set must not change as
3089 // buffers are being latched, as this could result in a deadlock.
3090 // Example: Two producers share the same command stream and:
3091 // 1.) Layer 0 is latched
3092 // 2.) Layer 0 gets a new frame
3093 // 2.) Layer 1 gets a new frame
3094 // 3.) Layer 1 is latched.
3095 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3096 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003097 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003098 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003099 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003100 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003101 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003102 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003103 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003104 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003105 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003106 } else {
3107 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003108 }
Robert Carr2047fae2016-11-28 14:09:09 -08003109 });
3110
chaviw49a108c2019-08-12 11:23:06 -07003111 // The client can continue submitting buffers for offscreen layers, but they will not
3112 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3113 // layers to ensure dequeueBuffer doesn't block indefinitely.
3114 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003115 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003116 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3117 }
3118
Lloyd Piquef2c79392018-12-20 16:23:33 -08003119 if (!mLayersWithQueuedFrames.empty()) {
3120 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3121 // writes to Layer current state. See also b/119481871
3122 Mutex::Autolock lock(mStateLock);
3123
3124 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003125 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003126 mLayersPendingRefresh.push_back(layer);
3127 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003128 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003129 if (layer->isBufferLatched()) {
3130 newDataLatched = true;
3131 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003132 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003133 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003134
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003135 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003136
3137 // If we will need to wake up at some time in the future to deal with a
3138 // queued frame that shouldn't be displayed during this vsync period, wake
3139 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003140 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003141 signalLayerUpdate();
3142 }
3143
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003144 // enter boot animation on first buffer latch
3145 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3146 ALOGI("Enter boot animation");
3147 mBootStage = BootStage::BOOTANIMATION;
3148 }
3149
Edgar Arriaga844fa672020-01-16 14:21:42 -08003150 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003151
Dan Stoza6b9454d2014-11-07 16:00:59 -08003152 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003153 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154}
3155
Mathias Agopianad456f92011-01-13 17:53:01 -08003156void SurfaceFlinger::invalidateHwcGeometry()
3157{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003158 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003159}
3160
Robert Carrc0df3122019-04-11 13:18:21 -07003161status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3162 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3163 const sp<IBinder>& parentHandle,
3164 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003165 // add this layer to the current state list
3166 {
3167 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003168 sp<Layer> parent;
3169 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003170 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003171 if (parent == nullptr) {
3172 return NAME_NOT_FOUND;
3173 }
3174 } else {
3175 parent = parentLayer;
3176 }
3177
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003178 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003179 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003180 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003181 return NO_MEMORY;
3182 }
Robert Carrc0df3122019-04-11 13:18:21 -07003183
3184 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3185
Robert Carrb89ea9d2018-12-10 13:01:14 -08003186 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003187 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003188 } else if (parent == nullptr) {
3189 lbc->onRemovedFromCurrentState();
3190 } else if (parent->isRemovedFromCurrentState()) {
3191 parent->addChild(lbc);
3192 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003193 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003194 parent->addChild(lbc);
3195 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003196
Yiwei Zhang243b3782018-05-15 17:40:04 -07003197 if (gbc != nullptr) {
3198 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3199 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3200 mMaxGraphicBufferProducerListSize,
3201 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3202 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003203 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003204 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3205 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3206 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3207 mNumLayers.load());
3208 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003209 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003210 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003211 }
3212
Mathias Agopian96f08192010-06-02 23:28:45 -07003213 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003214 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003215
Dan Stoza7d89d062015-04-30 13:29:25 -07003216 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003217}
3218
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003219uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003220 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003221}
3222
Mathias Agopian3f844832013-08-07 21:24:32 -07003223uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003224 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225}
3226
Mathias Agopian3f844832013-08-07 21:24:32 -07003227uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003228 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003229}
3230
3231uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003232 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003233 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003234 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003236 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237 }
3238 return old;
3239}
3240
Marissa Wall713b63f2018-10-17 15:42:43 -07003241bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003242 // to prevent onHandleDestroyed from being called while the lock is held,
3243 // we must keep a copy of the transactions (specifically the composer
3244 // states) around outside the scope of the lock
3245 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003246 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003247 {
3248 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003249
Valerie Haufce31b82019-04-30 16:41:14 -07003250 auto it = mTransactionQueues.begin();
3251 while (it != mTransactionQueues.end()) {
3252 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003253
Valerie Haufce31b82019-04-30 16:41:14 -07003254 while (!transactionQueue.empty()) {
3255 const auto& transaction = transactionQueue.front();
3256 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3257 transaction.states)) {
3258 setTransactionFlags(eTransactionFlushNeeded);
3259 break;
3260 }
3261 transactions.push_back(transaction);
3262 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3263 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003264 transaction.buffer, transaction.postTime,
3265 transaction.privileged, transaction.hasListenerCallbacks,
3266 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003267 transactionQueue.pop();
3268 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003269 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003270
Valerie Haufce31b82019-04-30 16:41:14 -07003271 if (transactionQueue.empty()) {
3272 it = mTransactionQueues.erase(it);
3273 mTransactionCV.broadcast();
3274 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003275 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003276 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003277 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003278 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003279 return flushedATransaction;
3280}
3281
3282bool SurfaceFlinger::transactionFlushNeeded() {
3283 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003284}
3285
chaviwca27f252018-02-06 16:46:39 -08003286
Marissa Wall17b4e452018-12-26 16:32:34 -08003287bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3288 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003289
3290 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003291 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3292 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3293 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3294 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3295 return false;
3296 }
3297
Marissa Wall713b63f2018-10-17 15:42:43 -07003298 for (const ComposerState& state : states) {
3299 const layer_state_t& s = state.state;
3300 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3301 continue;
3302 }
3303 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003304 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003305 }
3306 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003307 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003308}
3309
Valerie Hau9dab9732019-08-20 09:29:25 -07003310void SurfaceFlinger::setTransactionState(
3311 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3312 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3313 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3314 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003315 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003316
Valerie Haubc6ddb12019-03-08 11:10:15 -08003317 const int64_t postTime = systemTime();
3318
Robert Carr14167e02019-02-13 13:50:55 -08003319 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3320
Mathias Agopian698c0872011-06-28 19:09:31 -07003321 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003322
Marissa Wall713b63f2018-10-17 15:42:43 -07003323 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003324 auto itr = mTransactionQueues.find(applyToken);
3325 // if this is an animation frame, wait until prior animation frame has
3326 // been applied by SF
3327 if (flags & eAnimation) {
3328 while (itr != mTransactionQueues.end()) {
3329 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3330 if (CC_UNLIKELY(err != NO_ERROR)) {
3331 ALOGW_IF(err == TIMED_OUT,
3332 "setTransactionState timed out "
3333 "waiting for animation frame to apply");
3334 break;
3335 }
3336 itr = mTransactionQueues.find(applyToken);
3337 }
3338 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003339
Ady Abraham5facfb12020-04-22 15:18:31 -07003340 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003341 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003342 if (!pendingTransactions) {
3343 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3344 }
3345
3346 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003347 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003348 uncacheBuffer, postTime, privileged,
3349 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003350 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003351 return;
3352 }
3353
Valerie Haubc6ddb12019-03-08 11:10:15 -08003354 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003355 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3356 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003357}
3358
Valerie Hau9dab9732019-08-20 09:29:25 -07003359void SurfaceFlinger::applyTransactionState(
3360 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3361 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3362 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3363 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3364 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003365 uint32_t transactionFlags = 0;
3366
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003367 if (flags & eAnimation) {
3368 // For window updates that are part of an animation we must wait for
3369 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003370 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003371 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003372 if (CC_UNLIKELY(err != NO_ERROR)) {
3373 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003374 // caller after a few seconds.
3375 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3376 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003377 mAnimTransactionPending = false;
3378 break;
3379 }
3380 }
3381 }
3382
chaviwca27f252018-02-06 16:46:39 -08003383 for (const DisplayState& display : displays) {
3384 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003385 }
3386
Valerie Hau9dab9732019-08-20 09:29:25 -07003387 // start and end registration for listeners w/ no surface so they can get their callback. Note
3388 // that listeners with SurfaceControls will start registration during setClientStateLocked
3389 // below.
3390 for (const auto& listener : listenerCallbacks) {
3391 mTransactionCompletedThread.startRegistration(listener);
3392 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003393 }
3394
Valerie Hau9dab9732019-08-20 09:29:25 -07003395 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003396 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003397 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003398 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3399 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003400 }
3401
Valerie Hau9dab9732019-08-20 09:29:25 -07003402 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003403 mTransactionCompletedThread.endRegistration(listenerCallback);
3404 }
3405
Marissa Walle2ffb422018-10-12 11:33:52 -07003406 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003407 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003408 mTransactionCompletedThread.sendCallbacks();
3409 }
3410 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003411
chaviw273171b2018-12-26 11:46:30 -08003412 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3413
Marissa Wall947d34e2019-03-29 14:03:53 -07003414 if (uncacheBuffer.isValid()) {
3415 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003416 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003417 }
3418
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003419 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3420 // anyway. This can be used as a flush mechanism for previous async transactions.
3421 // Empty animation transaction can be used to simulate back-pressure, so also force a
3422 // transaction for empty animation transactions.
3423 if (transactionFlags == 0 &&
3424 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003425 transactionFlags = eTransactionNeeded;
3426 }
3427
Marissa Wall06255332019-03-27 13:48:27 -07003428 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3429 // so we don't have to wake up again next frame to preform an uneeded traversal.
3430 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3431 transactionFlags = transactionFlags & (~eTraversalNeeded);
3432 mTraversalNeededMainThread = true;
3433 }
3434
Mathias Agopian386aa982011-11-07 21:58:03 -08003435 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003436 if (mInterceptor->isEnabled()) {
3437 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003438 }
Irvel468051e2016-06-13 16:44:44 -07003439
Mathias Agopian386aa982011-11-07 21:58:03 -08003440 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003441 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3442 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003443 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003444
3445 // if this is a synchronous transaction, wait for it to take effect
3446 // before returning.
3447 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003448 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003449 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003450 if (flags & eAnimation) {
3451 mAnimTransactionPending = true;
3452 }
chaviw4fe36852019-04-15 16:25:49 -07003453 if (mPendingInputWindowCommands.syncInputWindows) {
3454 mPendingSyncInputWindows = true;
3455 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003456
3457 // applyTransactionState can be called by either the main SF thread or by
3458 // another process through setTransactionState. While a given process may wish
3459 // to wait on synchronous transactions, the main SF thread should never
3460 // be blocked. Therefore, we only wait if isMainThread is false.
3461 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003462 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3463 if (CC_UNLIKELY(err != NO_ERROR)) {
3464 // just in case something goes wrong in SF, return to the
3465 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003466 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3467 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003468 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003469 break;
3470 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003471 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003472 }
3473}
3474
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003475uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3476 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3477 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003478
Mathias Agopiane57f2922012-08-09 16:29:12 -07003479 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003480 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3481
3482 const uint32_t what = s.what;
3483 if (what & DisplayState::eSurfaceChanged) {
3484 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3485 state.surface = s.surface;
3486 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003487 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003488 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003489 if (what & DisplayState::eLayerStackChanged) {
3490 if (state.layerStack != s.layerStack) {
3491 state.layerStack = s.layerStack;
3492 flags |= eDisplayTransactionNeeded;
3493 }
3494 }
3495 if (what & DisplayState::eDisplayProjectionChanged) {
3496 if (state.orientation != s.orientation) {
3497 state.orientation = s.orientation;
3498 flags |= eDisplayTransactionNeeded;
3499 }
3500 if (state.frame != s.frame) {
3501 state.frame = s.frame;
3502 flags |= eDisplayTransactionNeeded;
3503 }
3504 if (state.viewport != s.viewport) {
3505 state.viewport = s.viewport;
3506 flags |= eDisplayTransactionNeeded;
3507 }
3508 }
3509 if (what & DisplayState::eDisplaySizeChanged) {
3510 if (state.width != s.width) {
3511 state.width = s.width;
3512 flags |= eDisplayTransactionNeeded;
3513 }
3514 if (state.height != s.height) {
3515 state.height = s.height;
3516 flags |= eDisplayTransactionNeeded;
3517 }
3518 }
3519
Mathias Agopiane57f2922012-08-09 16:29:12 -07003520 return flags;
3521}
3522
Steven Thomasd4071902020-03-24 16:02:53 -07003523bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003524 IPCThreadState* ipc = IPCThreadState::self();
3525 const int pid = ipc->getCallingPid();
3526 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003527 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003528 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3529 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003530 return false;
3531 }
3532 return true;
3533}
3534
Marissa Wall3dad52d2019-03-22 14:03:19 -07003535uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003536 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3537 bool privileged,
3538 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003539 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003540
Valerie Hau9dab9732019-08-20 09:29:25 -07003541 for (auto& listener : s.listeners) {
3542 // note that startRegistration will not re-register if the listener has
3543 // already be registered for a prior surface control
3544 mTransactionCompletedThread.startRegistration(listener);
3545 listenerCallbacks.insert(listener);
3546 }
3547
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003548 sp<Layer> layer = nullptr;
3549 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003550 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003551 } else {
3552 // The client may provide us a null handle. Treat it as if the layer was removed.
3553 ALOGW("Attempt to set client state with a null layer handle");
3554 }
chaviw8b3871a2017-11-01 17:41:01 -07003555 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003556 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003557 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003558 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003559 }
chaviw8b3871a2017-11-01 17:41:01 -07003560 return 0;
3561 }
3562
chaviw8b3871a2017-11-01 17:41:01 -07003563 uint32_t flags = 0;
3564
Garfield Tan8a3083e2018-12-03 13:21:07 -08003565 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003566
3567 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3568 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003569 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003570 layer->pushPendingState();
3571 }
3572
Valerie Hau871d6352020-01-29 08:44:02 -08003573 // Only set by BLAST adapter layers
3574 if (what & layer_state_t::eProducerDisconnect) {
3575 layer->onDisconnect();
3576 }
3577
chaviw8b3871a2017-11-01 17:41:01 -07003578 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003579 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003580 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003581 }
chaviw8b3871a2017-11-01 17:41:01 -07003582 }
3583 if (what & layer_state_t::eLayerChanged) {
3584 // NOTE: index needs to be calculated before we update the state
3585 const auto& p = layer->getParent();
3586 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003587 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003588 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003589 mCurrentState.layersSortedByZ.removeAt(idx);
3590 mCurrentState.layersSortedByZ.add(layer);
3591 // we need traversal (state changed)
3592 // AND transaction (list changed)
3593 flags |= eTransactionNeeded|eTraversalNeeded;
3594 }
chaviw8b3871a2017-11-01 17:41:01 -07003595 } else {
3596 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003597 flags |= eTransactionNeeded|eTraversalNeeded;
3598 }
3599 }
chaviw8b3871a2017-11-01 17:41:01 -07003600 }
3601 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003602 // NOTE: index needs to be calculated before we update the state
3603 const auto& p = layer->getParent();
3604 if (p == nullptr) {
3605 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3606 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3607 mCurrentState.layersSortedByZ.removeAt(idx);
3608 mCurrentState.layersSortedByZ.add(layer);
3609 // we need traversal (state changed)
3610 // AND transaction (list changed)
3611 flags |= eTransactionNeeded|eTraversalNeeded;
3612 }
3613 } else {
3614 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3615 flags |= eTransactionNeeded|eTraversalNeeded;
3616 }
chaviw8b3871a2017-11-01 17:41:01 -07003617 }
3618 }
3619 if (what & layer_state_t::eSizeChanged) {
3620 if (layer->setSize(s.w, s.h)) {
3621 flags |= eTraversalNeeded;
3622 }
3623 }
3624 if (what & layer_state_t::eAlphaChanged) {
3625 if (layer->setAlpha(s.alpha))
3626 flags |= eTraversalNeeded;
3627 }
3628 if (what & layer_state_t::eColorChanged) {
3629 if (layer->setColor(s.color))
3630 flags |= eTraversalNeeded;
3631 }
Peiyong Lind3788632018-09-18 16:01:31 -07003632 if (what & layer_state_t::eColorTransformChanged) {
3633 if (layer->setColorTransform(s.colorTransform)) {
3634 flags |= eTraversalNeeded;
3635 }
3636 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003637 if (what & layer_state_t::eBackgroundColorChanged) {
3638 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3639 flags |= eTraversalNeeded;
3640 }
3641 }
chaviw8b3871a2017-11-01 17:41:01 -07003642 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003643 // TODO: b/109894387
3644 //
3645 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3646 // rotation. To see the problem observe that if we have a square parent, and a child
3647 // of the same size, then we rotate the child 45 degrees around it's center, the child
3648 // must now be cropped to a non rectangular 8 sided region.
3649 //
3650 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3651 // private API, and the WindowManager only uses rotation in one case, which is on a top
3652 // level layer in which cropping is not an issue.
3653 //
3654 // However given that abuse of rotation matrices could lead to surfaces extending outside
3655 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3656 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3657 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003658 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003659 flags |= eTraversalNeeded;
3660 }
3661 if (what & layer_state_t::eTransparentRegionChanged) {
3662 if (layer->setTransparentRegionHint(s.transparentRegion))
3663 flags |= eTraversalNeeded;
3664 }
3665 if (what & layer_state_t::eFlagsChanged) {
3666 if (layer->setFlags(s.flags, s.mask))
3667 flags |= eTraversalNeeded;
3668 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003669 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003670 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003671 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003672 if (what & layer_state_t::eCornerRadiusChanged) {
3673 if (layer->setCornerRadius(s.cornerRadius))
3674 flags |= eTraversalNeeded;
3675 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003676 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003677 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3678 }
chaviw8b3871a2017-11-01 17:41:01 -07003679 if (what & layer_state_t::eLayerStackChanged) {
3680 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3681 // We only allow setting layer stacks for top level layers,
3682 // everything else inherits layer stack from its parent.
3683 if (layer->hasParent()) {
3684 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003685 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003686 } else if (idx < 0) {
3687 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003688 "that also does not appear in the top level layer list. Something"
3689 " has gone wrong.",
3690 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003691 } else if (layer->setLayerStack(s.layerStack)) {
3692 mCurrentState.layersSortedByZ.removeAt(idx);
3693 mCurrentState.layersSortedByZ.add(layer);
3694 // we need traversal (state changed)
3695 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003696 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003697 }
3698 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003699 if (what & layer_state_t::eDeferTransaction_legacy) {
3700 if (s.barrierHandle_legacy != nullptr) {
3701 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3702 } else if (s.barrierGbp_legacy != nullptr) {
3703 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003704 if (authenticateSurfaceTextureLocked(gbp)) {
3705 const auto& otherLayer =
3706 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003707 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003708 } else {
3709 ALOGE("Attempt to defer transaction to to an"
3710 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003711 }
3712 }
chaviw8b3871a2017-11-01 17:41:01 -07003713 // We don't trigger a traversal here because if no other state is
3714 // changed, we don't want this to cause any more work
3715 }
chaviw8b3871a2017-11-01 17:41:01 -07003716 if (what & layer_state_t::eReparentChildren) {
3717 if (layer->reparentChildren(s.reparentHandle)) {
3718 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003719 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003720 }
chaviw8b3871a2017-11-01 17:41:01 -07003721 if (what & layer_state_t::eDetachChildren) {
3722 layer->detachChildren();
3723 }
3724 if (what & layer_state_t::eOverrideScalingModeChanged) {
3725 layer->setOverrideScalingMode(s.overrideScalingMode);
3726 // We don't trigger a traversal here because if no other state is
3727 // changed, we don't want this to cause any more work
3728 }
Marissa Wall61c58622018-07-18 10:12:20 -07003729 if (what & layer_state_t::eTransformChanged) {
3730 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3731 }
3732 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3733 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3734 flags |= eTraversalNeeded;
3735 }
3736 if (what & layer_state_t::eCropChanged) {
3737 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3738 }
Marissa Wall861616d2018-10-22 12:52:23 -07003739 if (what & layer_state_t::eFrameChanged) {
3740 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3741 }
Marissa Wall61c58622018-07-18 10:12:20 -07003742 if (what & layer_state_t::eAcquireFenceChanged) {
3743 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3744 }
3745 if (what & layer_state_t::eDataspaceChanged) {
3746 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3747 }
3748 if (what & layer_state_t::eHdrMetadataChanged) {
3749 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3750 }
3751 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3752 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3753 }
3754 if (what & layer_state_t::eApiChanged) {
3755 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3756 }
3757 if (what & layer_state_t::eSidebandStreamChanged) {
3758 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3759 }
Robert Carr720e5062018-07-30 17:45:14 -07003760 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003761 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003762 layer->setInputInfo(s.inputInfo);
3763 flags |= eTraversalNeeded;
3764 } else {
3765 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3766 }
Robert Carr720e5062018-07-30 17:45:14 -07003767 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003768 if (what & layer_state_t::eMetadataChanged) {
3769 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3770 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003771 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3772 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3773 flags |= eTraversalNeeded;
3774 }
3775 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003776 if (what & layer_state_t::eShadowRadiusChanged) {
3777 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3778 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003779 if (what & layer_state_t::eFrameRateSelectionPriority) {
3780 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3781 flags |= eTraversalNeeded;
3782 }
3783 }
Steven Thomas3172e202020-01-06 19:25:30 -08003784 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003785 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3786 "SurfaceFlinger::setClientStateLocked") &&
3787 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3788 Layer::FrameRate::convertCompatibility(
3789 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003790 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003791 }
Steven Thomas3172e202020-01-06 19:25:30 -08003792 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003793 // This has to happen after we reparent children because when we reparent to null we remove
3794 // child layers from current state and remove its relative z. If the children are reparented in
3795 // the same transaction, then we have to make sure we reparent the children first so we do not
3796 // lose its relative z order.
3797 if (what & layer_state_t::eReparent) {
3798 bool hadParent = layer->hasParent();
3799 if (layer->reparent(s.parentHandleForChild)) {
3800 if (!hadParent) {
3801 mCurrentState.layersSortedByZ.remove(layer);
3802 }
3803 flags |= eTransactionNeeded | eTraversalNeeded;
3804 }
3805 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003806 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003807 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3808 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003809 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3810 }
3811 }
Marissa Wall78b72202019-03-15 14:58:34 -07003812 bool bufferChanged = what & layer_state_t::eBufferChanged;
3813 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3814 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003815 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003816 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003817 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3818 if (success) {
3819 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3820 success = ClientCache::getInstance()
3821 .registerErasedRecipient(s.cachedBuffer,
3822 wp<ClientCache::ErasedRecipient>(this));
3823 if (!success) {
3824 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3825 }
3826 }
Marissa Wall78b72202019-03-15 14:58:34 -07003827 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003828 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003829 } else if (bufferChanged) {
3830 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003831 }
Marissa Wall78b72202019-03-15 14:58:34 -07003832 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003833 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3834 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003835 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003836 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003837 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003838 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3839 // Do not put anything that updates layer state or modifies flags after
3840 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003841 return flags;
3842}
3843
chaviw273171b2018-12-26 11:46:30 -08003844uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3845 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003846 if (inputWindowCommands.syncInputWindows) {
3847 flags |= eTraversalNeeded;
3848 }
3849
Vishnu Nairec0ab382019-02-13 15:32:56 -08003850 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003851 return flags;
3852}
3853
chaviwfe94a222019-08-21 13:52:59 -07003854status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3855 sp<IBinder>* outHandle) {
3856 if (!mirrorFromHandle) {
3857 return NAME_NOT_FOUND;
3858 }
3859
3860 sp<Layer> mirrorLayer;
3861 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003862 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003863
3864 {
3865 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003866 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003867 if (!mirrorFrom) {
3868 return NAME_NOT_FOUND;
3869 }
3870
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003871 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3872 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003873 if (result != NO_ERROR) {
3874 return result;
3875 }
3876
3877 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3878 }
3879
3880 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3881}
3882
Marissa Wall2d814fb2019-04-09 18:52:57 +00003883status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3884 uint32_t h, PixelFormat format, uint32_t flags,
3885 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003886 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003887 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3888 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003889 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003890 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003891 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003892 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003893 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003894
Robert Carrc0df3122019-04-11 13:18:21 -07003895 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3896 "Expected only one of parentLayer or parentHandle to be non-null. "
3897 "Programmer error?");
3898
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003899 status_t result = NO_ERROR;
3900
3901 sp<Layer> layer;
3902
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003903 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003904
Evan Roskya1f1e152019-01-24 16:17:46 -08003905 bool primaryDisplayOnly = false;
3906
3907 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3908 // TODO b/64227542
3909 if (metadata.has(METADATA_WINDOW_TYPE)) {
3910 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3911 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003912 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003913 primaryDisplayOnly = true;
3914 }
3915 }
3916
Mathias Agopian3165cc22012-08-08 19:42:09 -07003917 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003918 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003919 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3920 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003921
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003922 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003923 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003924 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003925 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003926 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003927 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003928 // check if buffer size is set for color layer.
3929 if (w > 0 || h > 0) {
3930 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3931 int(w), int(h));
3932 return BAD_VALUE;
3933 }
3934
Vishnu Nairfa247b12020-02-11 08:58:26 -08003935 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3936 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003937 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003938 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003939 // check if buffer size is set for container layer.
3940 if (w > 0 || h > 0) {
3941 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3942 int(w), int(h));
3943 return BAD_VALUE;
3944 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003945 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3946 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003947 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003948 default:
3949 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003950 break;
3951 }
3952
Dan Stoza7d89d062015-04-30 13:29:25 -07003953 if (result != NO_ERROR) {
3954 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003955 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003956
Evan Roskya1f1e152019-01-24 16:17:46 -08003957 if (primaryDisplayOnly) {
3958 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003959 }
3960
Robert Carrb89ea9d2018-12-10 13:01:14 -08003961 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003962 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3963 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003964 if (result != NO_ERROR) {
3965 return result;
3966 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003967 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003968
3969 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003970 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003971}
3972
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003973std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3974 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003975
3976 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003977 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003978
Dan Stoza436ccf32018-06-21 12:10:12 -07003979 // Grab the state lock since we're accessing mCurrentState
3980 Mutex::Autolock lock(mStateLock);
3981
Cody Northropbc755282017-03-31 12:00:08 -06003982 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003983 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003984 while (matchFound) {
3985 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003986 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003987 if (layer->getName() == uniqueName) {
3988 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003989 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003990 }
3991 });
3992 }
3993
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003994 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003995 return uniqueName;
3996}
3997
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003998status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003999 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004000 LayerMetadata metadata, PixelFormat& format,
4001 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004002 sp<IGraphicBufferProducer>* gbp,
4003 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004004 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004005 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004006 case PIXEL_FORMAT_TRANSPARENT:
4007 case PIXEL_FORMAT_TRANSLUCENT:
4008 format = PIXEL_FORMAT_RGBA_8888;
4009 break;
4010 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004011 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004012 break;
4013 }
4014
chaviwb4c6e582019-08-16 14:35:07 -07004015 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004016 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004017 args.textureName = getNewTexture();
4018 {
4019 // Grab the SF state lock during this since it's the only safe way to access
4020 // RenderEngine when creating a BufferLayerConsumer
4021 // TODO: Check if this lock is still needed here
4022 Mutex::Autolock lock(mStateLock);
4023 layer = getFactory().createBufferQueueLayer(args);
4024 }
4025
Marissa Wallfd668622018-05-10 10:21:13 -07004026 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004027 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004028 *handle = layer->getHandle();
4029 *gbp = layer->getProducer();
4030 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004031 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004032
Marissa Wallfd668622018-05-10 10:21:13 -07004033 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004034 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004035}
4036
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004037status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004038 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004039 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004040 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004041 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004042 args.displayDevice = getDefaultDisplayDevice();
4043 args.textureName = getNewTexture();
4044 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004045 if (outTransformHint) {
4046 *outTransformHint = layer->getTransformHint();
4047 }
Marissa Wall61c58622018-07-18 10:12:20 -07004048 *handle = layer->getHandle();
4049 *outLayer = layer;
4050
4051 return NO_ERROR;
4052}
4053
Vishnu Nairfa247b12020-02-11 08:58:26 -08004054status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4055 uint32_t h, uint32_t flags, LayerMetadata metadata,
4056 sp<IBinder>* handle, sp<Layer>* outLayer) {
4057 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004058 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004059 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004060 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004061}
4062
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004063status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004064 uint32_t w, uint32_t h, uint32_t flags,
4065 LayerMetadata metadata, sp<IBinder>* handle,
4066 sp<Layer>* outLayer) {
4067 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004068 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004069 *handle = (*outLayer)->getHandle();
4070 return NO_ERROR;
4071}
4072
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004073void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004074 mLayersPendingRemoval.add(layer);
4075 mLayersRemoved = true;
4076 setTransactionFlags(eTransactionNeeded);
4077}
4078
Robert Carr695d5282018-12-18 15:27:58 -08004079void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004080{
Robert Carr2e102c92018-10-23 12:11:15 -07004081 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004082 // If a layer has a parent, we allow it to out-live it's handle
4083 // with the idea that the parent holds a reference and will eventually
4084 // be cleaned up. However no one cleans up the top-level so we do so
4085 // here.
4086 if (layer->getParent() == nullptr) {
4087 mCurrentState.layersSortedByZ.remove(layer);
4088 }
4089 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004090
4091 auto it = mLayersByLocalBinderToken.begin();
4092 while (it != mLayersByLocalBinderToken.end()) {
4093 if (it->second == layer) {
4094 it = mLayersByLocalBinderToken.erase(it);
4095 } else {
4096 it++;
4097 }
4098 }
4099
Robert Carr695d5282018-12-18 15:27:58 -08004100 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004101}
4102
Mathias Agopianb60314a2012-04-10 22:09:54 -07004103// ---------------------------------------------------------------------------
4104
Andy McFadden13a082e2012-08-24 10:16:42 -07004105void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004106 const auto display = getDefaultDisplayDeviceLocked();
4107 if (!display) return;
4108
4109 const sp<IBinder> token = display->getDisplayToken().promote();
4110 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004111
Jesse Hall01e29052013-02-19 16:13:35 -08004112 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004113 Vector<ComposerState> state;
4114 Vector<DisplayState> displays;
4115 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004116 d.what = DisplayState::eDisplayProjectionChanged |
4117 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004118 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004119 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004120 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004121 d.frame.makeInvalid();
4122 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004123 d.width = 0;
4124 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004125 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004126 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4127 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004128
Peiyong Lin65248e02020-04-18 21:15:07 -07004129 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004130
Dominik Laskowski83b88212018-12-11 13:34:06 -08004131 const nsecs_t vsyncPeriod = getVsyncPeriod();
4132 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004133
Brian Andersond0010582017-03-07 13:20:31 -08004134 // Use phase of 0 since phase is not known.
4135 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004136 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004137 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004138}
4139
4140void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004141 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004142 postMessageAsync(
4143 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004144}
4145
Peiyong Line9d809e2020-04-14 13:10:48 -07004146void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, hal::Vsync enabled) {
Ady Abraham27c70212019-06-11 10:52:26 -07004147 if (mHWCVsyncState != enabled) {
4148 getHwComposer().setVsyncEnabled(displayId, enabled);
4149 mHWCVsyncState = enabled;
4150 }
4151}
4152
Peiyong Lin65248e02020-04-18 21:15:07 -07004153void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004154 if (display->isVirtual()) {
4155 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004156 return;
4157 }
4158
Dominik Laskowski075d3172018-05-24 15:50:06 -07004159 const auto displayId = display->getId();
4160 LOG_ALWAYS_FATAL_IF(!displayId);
4161
Dominik Laskowski34157762018-10-31 13:07:19 -07004162 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004163
Peiyong Lin65248e02020-04-18 21:15:07 -07004164 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004165 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004166 return;
4167 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004169 display->setPowerMode(mode);
4170
Lloyd Pique4dccc412018-01-22 17:21:36 -08004171 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004172 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004173 }
4174
Peiyong Lin65248e02020-04-18 21:15:07 -07004175 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004176 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4177 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4178 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004179 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004180 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004181 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004182 mScheduler->onScreenAcquired(mAppConnectionHandle);
4183 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004184 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004185
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004186 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004187 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004188 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004189 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004190 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004191 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4192 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004193 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004194 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004195 mScheduler->disableHardwareVsync(true);
4196 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004197 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004198
Ady Abraham27c70212019-06-11 10:52:26 -07004199 // Make sure HWVsync is disabled before turning off the display
Peiyong Line9d809e2020-04-14 13:10:48 -07004200 setVsyncEnabledInHWC(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004201
Dominik Laskowski075d3172018-05-24 15:50:06 -07004202 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004203 mVisibleRegionsDirty = true;
4204 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004205 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004206 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004207 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004208 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004209 mScheduler->onScreenAcquired(mAppConnectionHandle);
4210 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004211 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004212 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004213 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004214 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004215 mScheduler->disableHardwareVsync(true);
4216 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004217 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004218 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004219 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004220 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004221 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004222 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004223
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004224 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004225 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004226 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004227 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004228 }
4229
Dominik Laskowski34157762018-10-31 13:07:19 -07004230 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004231}
4232
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004233void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004234 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004235 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004236 if (!display) {
4237 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4238 displayToken.get());
4239 } else if (display->isVirtual()) {
4240 ALOGW("Attempt to set power mode %d for virtual display", mode);
4241 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004242 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004243 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004244 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004245}
4246
4247// ---------------------------------------------------------------------------
4248
Dominik Laskowskic2867142019-01-21 11:33:38 -08004249status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4250 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004251 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004252
Mathias Agopianbd115332013-04-18 16:41:04 -07004253 IPCThreadState* ipc = IPCThreadState::self();
4254 const int pid = ipc->getCallingPid();
4255 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004256
Mathias Agopianbd115332013-04-18 16:41:04 -07004257 if ((uid != AID_SHELL) &&
4258 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004259 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4260 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004261 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004262 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004263 // (this would indicate SF is stuck, but we want to be able to
4264 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004265 status_t err = mStateLock.timedLock(s2ns(1));
4266 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004267 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004268 StringAppendF(&result,
4269 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4270 "(no locks held)\n",
4271 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004272 }
4273
Dominik Laskowskic2867142019-01-21 11:33:38 -08004274 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004275 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004276 {"--dispsync"s,
4277 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004278 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004279 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4280 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4281 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4282 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4283 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4284 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004285 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004286 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4287 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004288
Dominik Laskowskic2867142019-01-21 11:33:38 -08004289 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004290
Dominik Laskowski46470112019-08-02 13:13:11 -07004291 const auto it = dumpers.find(flag);
4292 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004293 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004294 } else if (!asProto) {
4295 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004296 }
4297
Mathias Agopian9795c422009-08-26 16:36:26 -07004298 if (locked) {
4299 mStateLock.unlock();
4300 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004301
Dominik Laskowski46470112019-08-02 13:13:11 -07004302 if (it == dumpers.end()) {
4303 const LayersProto layersProto = dumpProtoFromMainThread();
4304 if (asProto) {
4305 result.append(layersProto.SerializeAsString());
4306 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004307 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004308 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4309 result.append(LayerProtoParser::layerTreeToString(layerTree));
4310 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004311 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004312 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004313 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004314 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004315 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004316 return NO_ERROR;
4317}
4318
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004319status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4320 if (asProto && mTracing.isEnabled()) {
4321 mTracing.writeToFileAsync();
4322 }
4323
4324 return doDump(fd, DumpArgs(), asProto);
4325}
4326
Dominik Laskowskic2867142019-01-21 11:33:38 -08004327void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004328 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004329 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004330}
4331
Dominik Laskowskic2867142019-01-21 11:33:38 -08004332void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004333 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004334
Dominik Laskowskic2867142019-01-21 11:33:38 -08004335 if (args.size() > 1) {
4336 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004337 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004338 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004339 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004340 }
Robert Carr2047fae2016-11-28 14:09:09 -08004341 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004342 } else {
4343 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004344 }
4345}
4346
Dominik Laskowskic2867142019-01-21 11:33:38 -08004347void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004348 const bool clearAll = args.size() < 2;
4349 const auto name = clearAll ? String8() : String8(args[1]);
4350
Edgar Arriaga844fa672020-01-16 14:21:42 -08004351 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004352 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004353 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004354 }
Robert Carr2047fae2016-11-28 14:09:09 -08004355 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004356
Svetoslavd85084b2014-03-20 10:28:31 -07004357 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004358}
4359
Dominik Laskowskic2867142019-01-21 11:33:38 -08004360void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4361 mTimeStats->parseArgs(asProto, args, result);
4362}
4363
Jamie Gennis6547ff42013-07-16 20:12:42 -07004364// This should only be called from the main thread. Otherwise it would need
4365// the lock and should use mCurrentState rather than mDrawingState.
4366void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004367 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004368 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004369 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004370
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004371 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004372}
4373
Yiwei Zhang5434a782018-12-05 18:06:32 -08004374void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004375 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004376
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004377 if (isLayerTripleBufferingDisabled())
4378 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004379
Yiwei Zhang5434a782018-12-05 18:06:32 -08004380 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4381 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4382 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4383 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4384 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4385 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004386 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004387}
4388
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004389void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004390 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004391
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004392 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004393 result.append("\n");
4394
Ady Abraham9e16a482019-12-03 17:19:41 -08004395 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004396 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004397 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004398 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004399
Steven Thomasd4071902020-03-24 16:02:53 -07004400 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004401 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004402 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004403 ", min: %.2f Hz, max: %.2f Hz",
Steven Thomasd4071902020-03-24 16:02:53 -07004404 policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004405 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4406 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004407 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4408 if (currentPolicy != policy) {
4409 StringAppendF(&result,
4410 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
4411 ", min: %.2f Hz, max: %.2f Hz\n\n",
4412 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
4413 currentPolicy.maxRefreshRate);
4414 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004415
Ana Krulecc2870422019-01-29 19:00:58 -08004416 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004417 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004418}
4419
Yiwei Zhang5434a782018-12-05 18:06:32 -08004420void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4421 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004422 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4423 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004424 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004425 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004426 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004427 }
David Sodman4a36e932017-11-07 14:29:47 -08004428 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004429 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004430 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004431 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4432 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004433}
4434
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004435void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4436 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004437 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4438 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004439 for (const auto& segment : history) {
4440 if (!segment.usedThirdBuffer) {
4441 stats.twoBufferTime += segment.totalTime;
4442 }
4443 if (segment.occupancyAverage < 1.0f) {
4444 stats.doubleBufferedTime += segment.totalTime;
4445 } else if (segment.occupancyAverage < 2.0f) {
4446 stats.tripleBufferedTime += segment.totalTime;
4447 }
4448 ++stats.numSegments;
4449 stats.totalTime += segment.totalTime;
4450 }
4451}
4452
Yiwei Zhang5434a782018-12-05 18:06:32 -08004453void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4454 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004455
4456 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4457 const size_t count = currentLayers.size();
4458 for (size_t i=0 ; i<count ; i++) {
4459 currentLayers[i]->dumpFrameEvents(result);
4460 }
4461}
4462
Yiwei Zhang5434a782018-12-05 18:06:32 -08004463void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004464 result.append("Buffering stats:\n");
4465 result.append(" [Layer name] <Active time> <Two buffer> "
4466 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004467 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004468 typedef std::tuple<std::string, float, float, float> BufferTuple;
4469 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004470 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004471 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004472 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004473 if (stats.numSegments == 0) {
4474 continue;
4475 }
4476 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4477 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4478 stats.totalTime;
4479 float doubleBufferRatio = static_cast<float>(
4480 stats.doubleBufferedTime) / stats.totalTime;
4481 float tripleBufferRatio = static_cast<float>(
4482 stats.tripleBufferedTime) / stats.totalTime;
4483 sorted.insert({activeTime, {name, twoBufferRatio,
4484 doubleBufferRatio, tripleBufferRatio}});
4485 }
4486 for (const auto& sortedPair : sorted) {
4487 float activeTime = sortedPair.first;
4488 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4490 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004491 }
4492 result.append("\n");
4493}
4494
Yiwei Zhang5434a782018-12-05 18:06:32 -08004495void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004496 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004497 const auto displayId = display->getId();
4498 if (!displayId) {
4499 continue;
4500 }
4501 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004502 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004503 continue;
4504 }
4505
Yiwei Zhang5434a782018-12-05 18:06:32 -08004506 StringAppendF(&result,
4507 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4508 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004509 uint8_t port;
4510 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004511 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004512 result.append("no identification data\n");
4513 continue;
4514 }
4515
4516 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004517 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004518 continue;
4519 }
4520
4521 const auto edid = parseEdid(data);
4522 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004523 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004524 continue;
4525 }
4526
Yiwei Zhang5434a782018-12-05 18:06:32 -08004527 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004528 result.append(edid->displayName.data(), edid->displayName.length());
4529 result.append("\"\n");
4530 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004531}
4532
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004533void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4534 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004535 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004536 uint8_t port;
4537 DisplayIdentificationData data;
4538
4539 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4540 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4541 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4542 }
4543}
4544
Yiwei Zhang5434a782018-12-05 18:06:32 -08004545void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004546 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004547 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4548 StringAppendF(&result, "DisplayColorSetting: %s\n",
4549 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004550
4551 // TODO: print out if wide-color mode is active or not
4552
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004553 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004554 const auto displayId = display->getId();
4555 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004556 continue;
4557 }
4558
Yiwei Zhang5434a782018-12-05 18:06:32 -08004559 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004560 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004561 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004562 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004563 }
4564
Lloyd Pique32cbe282018-10-19 13:09:22 -07004565 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004566 StringAppendF(&result, " Current color mode: %s (%d)\n",
4567 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004568 }
4569 result.append("\n");
4570}
4571
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004572LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4573 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
4574 const auto display = getDefaultDisplayDeviceLocked();
4575
chaviw1d044282017-09-27 12:19:28 -07004576 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004577 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004578 layer->writeToProto(layersProto, traceFlags, display);
chaviw08f3cb22020-01-13 13:17:21 -08004579 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004580
chaviw1d044282017-09-27 12:19:28 -07004581 return layersProto;
4582}
4583
Alec Mouri6b9e9912020-01-21 10:50:24 -08004584void SurfaceFlinger::dumpHwc(std::string& result) const {
4585 getHwComposer().dump(result);
4586}
4587
Vishnu Nair0f085c62019-08-30 08:49:12 -07004588void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4589 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4590 // it.
4591 LayerProto* rootProto = layersProto.add_layers();
4592 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4593 rootProto->set_id(offscreenRootLayerId);
4594 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004595 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004596
4597 for (Layer* offscreenLayer : mOffscreenLayers) {
4598 // Add layer as child of the fake root
4599 rootProto->add_children(offscreenLayer->sequence);
4600
4601 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004602 LayerProto* layerProto =
4603 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004604 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004605 }
4606}
4607
Vishnu Nair8406fd72019-07-30 11:29:31 -07004608LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4609 LayersProto layersProto;
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004610 postMessageSync(new LambdaMessage([&] { layersProto = dumpDrawingStateProto(traceFlags); }));
Vishnu Nair8406fd72019-07-30 11:29:31 -07004611 return layersProto;
4612}
4613
Vishnu Nair0f085c62019-08-30 08:49:12 -07004614void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4615 result.append("Offscreen Layers:\n");
4616 postMessageSync(new LambdaMessage([&]() {
4617 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004618 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004619 layer->dumpCallingUidPid(result);
4620 });
4621 }
4622 }));
4623}
4624
Dominik Laskowskic2867142019-01-21 11:33:38 -08004625void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4626 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004627 Colorizer colorizer(colorize);
4628
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004629 // figure out if we're stuck somewhere
4630 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004631 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004632 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4633
4634 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004635 * Dump library configuration.
4636 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004637
4638 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004639 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004640 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004641 appendSfConfigString(result);
4642 appendUiConfigString(result);
4643 appendGuiConfigString(result);
4644 result.append("\n");
4645
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004646 result.append("\nDisplay identification data:\n");
4647 dumpDisplayIdentificationData(result);
4648
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004649 result.append("\nWide-Color information:\n");
4650 dumpWideColorInfo(result);
4651
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004652 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004653 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004654 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004655 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004656 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004657
Andy McFadden41d67d72014-04-25 16:58:34 -07004658 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004659 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004660 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004661 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004662 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004663
Dan Stozab90cf072015-03-05 11:05:59 -08004664 dumpStaticScreenStats(result);
4665 result.append("\n");
4666
Alec Mouri40189b02019-03-05 15:07:54 -08004667 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4668 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4669 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004670
Dan Stozae77c7662016-05-13 11:37:28 -07004671 dumpBufferingStats(result);
4672
Andy McFadden4803b742012-09-24 19:07:20 -07004673 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004674 * Dump the visible layer list
4675 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004676 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004677 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004678 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4679 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004680 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004681
Chia-I Wu2f884132018-09-13 15:17:58 -07004682 {
Lloyd Pique207def92019-02-28 16:09:52 -08004683 StringAppendF(&result, "Composition layers\n");
4684 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004685 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08004686 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08004687
4688 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4689 layer->getDebugName() ? layer->getDebugName()
4690 : "<unknown>");
4691 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004692 });
4693 }
4694
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004695 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004696 * Dump Display state
4697 */
4698
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004699 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004700 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004701 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004702 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004703 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004704 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004705 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004706
4707 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004708 * Dump CompositionEngine state
4709 */
4710
4711 mCompositionEngine->dump(result);
4712
4713 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004714 * Dump SurfaceFlinger global state
4715 */
4716
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004717 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004718 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004719 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004720
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004721 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004722
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004723 DebugEGLImageTracker::getInstance()->dump(result);
4724
Dominik Laskowski075d3172018-05-24 15:50:06 -07004725 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004726 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4727 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004728 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4729 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004730 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004731 StringAppendF(&result,
4732 " transaction-flags : %08x\n"
4733 " gpu_to_cpu_unsupported : %d\n",
4734 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004735
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004736 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004737 displayId && getHwComposer().isConnected(*displayId)) {
4738 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004739 StringAppendF(&result,
4740 " refresh-rate : %f fps\n"
4741 " x-dpi : %f\n"
4742 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004743 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4744 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004745 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004746
Yiwei Zhang5434a782018-12-05 18:06:32 -08004747 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004748
Dan Stozae22aec72016-08-01 13:20:59 -07004749 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004750 * Tracing state
4751 */
4752 mTracing.dump(result);
4753 result.append("\n");
4754
4755 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004756 * HWC layer minidump
4757 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004758 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004759 const auto displayId = display->getId();
4760 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004761 continue;
4762 }
4763
Yiwei Zhang5434a782018-12-05 18:06:32 -08004764 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004765 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004766 const sp<DisplayDevice> displayDevice = display;
4767 mCurrentState.traverseInZOrder(
4768 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004769 result.append("\n");
4770 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004771
4772 /*
4773 * Dump HWComposer state
4774 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004775 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004776 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004777 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004778 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004779 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004780 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004781
4782 /*
4783 * Dump gralloc state
4784 */
4785 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4786 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004787
4788 /*
4789 * Dump VrFlinger state if in use.
4790 */
4791 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4792 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004793 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004794 result.append("\n");
4795 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004796
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004797 result.append(mTimeStats->miniDump());
4798 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004799}
4800
Chia-I Wu28f320b2018-05-03 11:02:56 -07004801void SurfaceFlinger::updateColorMatrixLocked() {
4802 mat4 colorMatrix;
4803 if (mGlobalSaturationFactor != 1.0f) {
4804 // Rec.709 luma coefficients
4805 float3 luminance{0.213f, 0.715f, 0.072f};
4806 luminance *= 1.0f - mGlobalSaturationFactor;
4807 mat4 saturationMatrix = mat4(
4808 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4809 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4810 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4811 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4812 );
4813 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4814 } else {
4815 colorMatrix = mClientColorMatrix * mDaltonizer();
4816 }
4817
4818 if (mCurrentState.colorMatrix != colorMatrix) {
4819 mCurrentState.colorMatrix = colorMatrix;
4820 mCurrentState.colorMatrixChanged = true;
4821 setTransactionFlags(eTransactionNeeded);
4822 }
4823}
4824
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004825status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004826#pragma clang diagnostic push
4827#pragma clang diagnostic error "-Wswitch-enum"
4828 switch (static_cast<ISurfaceComposerTag>(code)) {
4829 // These methods should at minimum make sure that the client requested
4830 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004831 case BOOT_FINISHED:
4832 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004833 case CREATE_DISPLAY:
4834 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004835 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004836 case GET_ANIMATION_FRAME_STATS:
4837 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004838 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004839 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004840 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004841 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4842 case SET_AUTO_LOW_LATENCY_MODE:
4843 case GET_GAME_CONTENT_TYPE_SUPPORT:
4844 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004845 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004846 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004847 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004848 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004849 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004850 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004851 case SET_GLOBAL_SHADOW_SETTINGS:
4852 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4853 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4854 // necessary permission dynamically. Don't use the permission cache for this check.
4855 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4856 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004857 IPCThreadState* ipc = IPCThreadState::self();
4858 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4859 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004860 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004861 }
Robert Carr1db73f62016-12-21 12:58:51 -08004862 return OK;
4863 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004865 IPCThreadState* ipc = IPCThreadState::self();
4866 const int pid = ipc->getCallingPid();
4867 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004868 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4869 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004870 return PERMISSION_DENIED;
4871 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004872 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004873 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004874 // Used by apps to hook Choreographer to SurfaceFlinger.
4875 case CREATE_DISPLAY_EVENT_CONNECTION:
4876 // The following calls are currently used by clients that do not
4877 // request necessary permissions. However, they do not expose any secret
4878 // information, so it is OK to pass them.
4879 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004880 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004881 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004882 case GET_PHYSICAL_DISPLAY_IDS:
4883 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004884 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004885 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004886 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004887 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004888 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004889 case GET_DISPLAY_STATS:
4890 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4891 // Calling setTransactionState is safe, because you need to have been
4892 // granted a reference to Client* and Handle* to do anything with it.
4893 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004894 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004895 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004896 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004897 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004898 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004899 // setFrameRate() is deliberately available for apps to call without any
4900 // special permissions.
4901 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004902 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4903 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004904 return OK;
4905 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004906 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004907 case CAPTURE_SCREEN:
4908 case ADD_REGION_SAMPLING_LISTENER:
4909 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004910 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004911 IPCThreadState* ipc = IPCThreadState::self();
4912 const int pid = ipc->getCallingPid();
4913 const int uid = ipc->getCallingUid();
4914 if ((uid != AID_GRAPHICS) &&
4915 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4916 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4917 return PERMISSION_DENIED;
4918 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004919 return OK;
4920 }
chaviw93df2ea2019-04-30 16:45:12 -07004921 case CAPTURE_SCREEN_BY_ID: {
4922 IPCThreadState* ipc = IPCThreadState::self();
4923 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004924 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004925 return OK;
4926 }
4927 return PERMISSION_DENIED;
4928 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004929 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004930
4931 // These codes are used for the IBinder protocol to either interrogate the recipient
4932 // side of the transaction for its canonical interface descriptor or to dump its state.
4933 // We let them pass by default.
4934 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4935 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4936 code == IBinder::SYSPROPS_TRANSACTION) {
4937 return OK;
4938 }
Ady Abraham07e54702020-04-16 15:05:37 -07004939 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004940 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004941 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004942 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4943 return OK;
4944 }
4945 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4946 return PERMISSION_DENIED;
4947#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004948}
4949
Ana Krulec13be8ad2018-08-21 02:43:56 +00004950status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4951 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004952 status_t credentialCheck = CheckTransactCodeCredentials(code);
4953 if (credentialCheck != OK) {
4954 return credentialCheck;
4955 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004956
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004957 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4958 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004959 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004960 IPCThreadState* ipc = IPCThreadState::self();
4961 const int uid = ipc->getCallingUid();
4962 if (CC_UNLIKELY(uid != AID_SYSTEM
4963 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004964 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004965 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004966 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004967 return PERMISSION_DENIED;
4968 }
4969 int n;
4970 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004971 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004972 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004973 return NO_ERROR;
4974 case 1002: // SHOW_UPDATES
4975 n = data.readInt32();
4976 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004977 invalidateHwcGeometry();
4978 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004979 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004980 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004981 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004982 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004983 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004984 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004985 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004986 setTransactionFlags(
4987 eTransactionNeeded|
4988 eDisplayTransactionNeeded|
4989 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004990 return NO_ERROR;
4991 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004992 case 1006:{ // send empty update
4993 signalRefresh();
4994 return NO_ERROR;
4995 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004996 case 1008: // toggle use of hw composer
4997 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004998 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004999 invalidateHwcGeometry();
5000 repaintEverything();
5001 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005002 case 1009: // toggle use of transform hint
5003 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005004 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005005 invalidateHwcGeometry();
5006 repaintEverything();
5007 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005008 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005009 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005010 reply->writeInt32(0);
5011 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005012 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005013 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005014 return NO_ERROR;
5015 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005016 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005017 if (!display) {
5018 return NAME_NOT_FOUND;
5019 }
5020
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005021 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005022 return NO_ERROR;
5023 }
5024 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005025 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005026 // daltonize
5027 n = data.readInt32();
5028 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005029 case 1:
5030 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5031 break;
5032 case 2:
5033 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5034 break;
5035 case 3:
5036 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5037 break;
5038 default:
5039 mDaltonizer.setType(ColorBlindnessType::None);
5040 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005041 }
5042 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005043 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005044 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005045 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005046 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005047
5048 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005049 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005050 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005051 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005052 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005053 // apply a color matrix
5054 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005055 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005056 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005057 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005058 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005059 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005060 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005061 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005062 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005063 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005064 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005065
5066 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5067 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005068 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005069 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5070 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5071 }
5072
Chia-I Wu28f320b2018-05-03 11:02:56 -07005073 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005074 return NO_ERROR;
5075 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005076 case 1016: { // Unused.
5077 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005078 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005079 case 1017: {
5080 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005081 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005082 return NO_ERROR;
5083 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005084 case 1018: { // Modify Choreographer's phase offset
5085 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005086 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005087 return NO_ERROR;
5088 }
5089 case 1019: { // Modify SurfaceFlinger's phase offset
5090 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005091 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005092 return NO_ERROR;
5093 }
Irvel468051e2016-06-13 16:44:44 -07005094 case 1020: { // Layer updates interceptor
5095 n = data.readInt32();
5096 if (n) {
5097 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005098 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005099 }
5100 else{
5101 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005102 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005103 }
5104 return NO_ERROR;
5105 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005106 case 1021: { // Disable HWC virtual displays
5107 n = data.readInt32();
5108 mUseHwcVirtualDisplays = !n;
5109 return NO_ERROR;
5110 }
Romain Guy0147a172017-06-01 13:53:56 -07005111 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005112 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005113 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005114
Chia-I Wu28f320b2018-05-03 11:02:56 -07005115 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005116 return NO_ERROR;
5117 }
Romain Guy54f154a2017-10-24 21:40:32 +01005118 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005119 int32_t colorMode;
5120
Chia-I Wu0d711262018-05-21 15:19:35 -07005121 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005122 if (data.readInt32(&colorMode) == NO_ERROR) {
5123 mForceColorMode = static_cast<ColorMode>(colorMode);
5124 }
Romain Guy54f154a2017-10-24 21:40:32 +01005125 invalidateHwcGeometry();
5126 repaintEverything();
5127 return NO_ERROR;
5128 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005129 // Deprecate, use 1030 to check whether the device is color managed.
5130 case 1024: {
5131 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005132 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005133 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005134 n = data.readInt32();
5135 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005136 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005137 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005138 reply->writeInt32(NO_ERROR);
5139 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005140 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005141 mTracingEnabledChanged = mTracing.disable();
5142 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005143 reply->writeInt32(mTracing.writeToFile());
5144 } else {
5145 reply->writeInt32(NO_ERROR);
5146 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005147 }
5148 return NO_ERROR;
5149 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005150 case 1026: { // Get layer tracing status
5151 reply->writeBool(mTracing.isEnabled());
5152 return NO_ERROR;
5153 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005154 // Is a DisplayColorSetting supported?
5155 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005156 const auto display = getDefaultDisplayDevice();
5157 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005158 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005159 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005160
5161 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5162 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005163 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005164 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005165 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005166 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005167 reply->writeBool(true);
5168 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005169 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005170 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005171 break;
5172 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005173 reply->writeBool(
5174 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005175 break;
5176 }
5177 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005178 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005179 // Is VrFlinger active?
5180 case 1028: {
5181 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005182 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005183 return NO_ERROR;
5184 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005185 // Set buffer size for SF tracing (value in KB)
5186 case 1029: {
5187 n = data.readInt32();
5188 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5189 ALOGW("Invalid buffer size: %d KB", n);
5190 reply->writeInt32(BAD_VALUE);
5191 return BAD_VALUE;
5192 }
5193
5194 ALOGD("Updating trace buffer to %d KB", n);
5195 mTracing.setBufferSize(n * 1024);
5196 reply->writeInt32(NO_ERROR);
5197 return NO_ERROR;
5198 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005199 // Is device color managed?
5200 case 1030: {
5201 reply->writeBool(useColorManagement);
5202 return NO_ERROR;
5203 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005204 // Override default composition data space
5205 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5206 // && adb shell stop zygote && adb shell start zygote
5207 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5208 // adb shell stop zygote && adb shell start zygote
5209 case 1031: {
5210 Mutex::Autolock _l(mStateLock);
5211 n = data.readInt32();
5212 if (n) {
5213 n = data.readInt32();
5214 if (n) {
5215 Dataspace dataspace = static_cast<Dataspace>(n);
5216 if (!validateCompositionDataspace(dataspace)) {
5217 return BAD_VALUE;
5218 }
5219 mDefaultCompositionDataspace = dataspace;
5220 }
5221 n = data.readInt32();
5222 if (n) {
5223 Dataspace dataspace = static_cast<Dataspace>(n);
5224 if (!validateCompositionDataspace(dataspace)) {
5225 return BAD_VALUE;
5226 }
5227 mWideColorGamutCompositionDataspace = dataspace;
5228 }
5229 } else {
5230 // restore composition data space.
5231 mDefaultCompositionDataspace = defaultCompositionDataspace;
5232 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5233 }
5234 return NO_ERROR;
5235 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005236 // Set trace flags
5237 case 1033: {
5238 n = data.readUint32();
5239 ALOGD("Updating trace flags to 0x%x", n);
5240 mTracing.setTraceFlags(n);
5241 reply->writeInt32(NO_ERROR);
5242 return NO_ERROR;
5243 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005244 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005245 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005246 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005247 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005248 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005249 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005250 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005251 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005252 } else {
5253 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005254 }
5255 return NO_ERROR;
5256 }
Ady Abraham34392f72019-04-10 11:29:27 -07005257 case 1035: {
5258 n = data.readInt32();
5259 mDebugDisplayConfigSetByBackdoor = false;
5260 if (n >= 0) {
5261 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005262 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005263 if (result != NO_ERROR) {
5264 return result;
5265 }
5266 mDebugDisplayConfigSetByBackdoor = true;
5267 }
5268 return NO_ERROR;
5269 }
Ady Abraham07e54702020-04-16 15:05:37 -07005270 case 1036: {
5271 if (data.readInt32() > 0) {
5272 status_t result =
5273 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5274 if (result != NO_ERROR) {
5275 return result;
5276 }
5277 } else {
5278 mDebugFrameRateFlexibilityToken = nullptr;
5279 }
5280 return NO_ERROR;
5281 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005282 }
5283 }
5284 return err;
5285}
5286
Steven Thomas6d8110b2017-08-31 18:24:21 -07005287void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005288 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005289 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005290}
5291
Ana Krulec7d1d6832018-12-27 11:10:09 -08005292void SurfaceFlinger::repaintEverythingForHWC() {
5293 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005294 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005295 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005296}
5297
Ady Abrahama09852a2020-02-20 14:23:42 -08005298void SurfaceFlinger::kernelTimerChanged(bool expired) {
5299 static bool updateOverlay =
5300 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5301 if (!updateOverlay || !mRefreshRateOverlay) return;
5302
5303 // Update the overlay on the main thread to avoid race conditions with
5304 // mRefreshRateConfigs->getCurrentRefreshRate()
5305 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5306 if (mRefreshRateOverlay) {
5307 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5308 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005309 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005310 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5311 if (mDesiredActiveConfigChanged) {
5312 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5313 mDesiredActiveConfig.configId);
5314 }
5315
5316 return mRefreshRateConfigs->getCurrentRefreshRate();
5317 }();
5318 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5319
5320 if (current != min) {
5321 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5322 mEventQueue->invalidate();
5323 }
5324 }
5325 }));
5326}
5327
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005328// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5329class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005330public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005331 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5332 ~WindowDisconnector() {
5333 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005334 }
5335
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005336private:
5337 ANativeWindow* mWindow;
5338 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005339};
5340
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005341status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005342 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005343 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5344 const Rect& sourceCrop, uint32_t reqWidth,
5345 uint32_t reqHeight, bool useIdentityTransform,
5346 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005347 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005348
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005349 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005350
Dominik Laskowski718f9602019-11-09 20:01:35 -08005351 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5352 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5353 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5354 renderAreaRotation = ui::Transform::ROT_0;
5355 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005356
Chia-I Wu20261cb2018-08-23 12:55:44 -07005357 sp<DisplayDevice> display;
5358 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005359 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005360
Chia-I Wu20261cb2018-08-23 12:55:44 -07005361 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005362 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005363
Chia-I Wucb023152018-08-28 12:57:23 -07005364 // set the requested width/height to the logical display viewport size
5365 // by default
5366 if (reqWidth == 0 || reqHeight == 0) {
5367 reqWidth = uint32_t(display->getViewport().width());
5368 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005369 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005370 }
5371
Peiyong Lin0e003c92018-09-17 11:09:51 -07005372 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005373 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005374 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5375 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005376 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005377 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005378}
5379
chaviw93df2ea2019-04-30 16:45:12 -07005380static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5381 switch (colorMode) {
5382 case ColorMode::DISPLAY_P3:
5383 case ColorMode::BT2100_PQ:
5384 case ColorMode::BT2100_HLG:
5385 case ColorMode::DISPLAY_BT2020:
5386 return Dataspace::DISPLAY_P3;
5387 default:
5388 return Dataspace::V0_SRGB;
5389 }
5390}
5391
Martin Liu4a322352020-03-24 21:30:38 +08005392status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5393 static constexpr int kFifoPriority = 2;
5394 static constexpr int kOtherPriority = 0;
5395
5396 struct sched_param param = {0};
5397 int sched_policy;
5398 if (enabled) {
5399 sched_policy = SCHED_FIFO;
5400 param.sched_priority = kFifoPriority;
5401 } else {
5402 sched_policy = SCHED_OTHER;
5403 param.sched_priority = kOtherPriority;
5404 }
5405
5406 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5407 return -errno;
5408 }
5409 return NO_ERROR;
5410}
5411
chaviw93df2ea2019-04-30 16:45:12 -07005412const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5413 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5414 if (displayToken) {
5415 return getDisplayDeviceLocked(displayToken);
5416 }
5417 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5418 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005419 return getDisplayByLayerStack(displayOrLayerStack);
5420}
5421
5422const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005423 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005424 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005425 return display;
5426 }
5427 }
5428 return nullptr;
5429}
5430
5431status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5432 sp<GraphicBuffer>* outBuffer) {
5433 sp<DisplayDevice> display;
5434 uint32_t width;
5435 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005436 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005437 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005438 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005439 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5440 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005441 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005442 }
5443
5444 width = uint32_t(display->getViewport().width());
5445 height = uint32_t(display->getViewport().height());
5446
Dominik Laskowski718f9602019-11-09 20:01:35 -08005447 const auto orientation = display->getOrientation();
5448 captureOrientation = ui::Transform::toRotationFlags(orientation);
5449
5450 switch (captureOrientation) {
5451 case ui::Transform::ROT_90:
5452 captureOrientation = ui::Transform::ROT_270;
5453 break;
5454
5455 case ui::Transform::ROT_270:
5456 captureOrientation = ui::Transform::ROT_90;
5457 break;
5458
5459 case ui::Transform::ROT_INVALID:
5460 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5461 captureOrientation = ui::Transform::ROT_0;
5462 break;
5463
5464 default:
5465 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005466 }
chaviw93df2ea2019-04-30 16:45:12 -07005467 *outDataspace =
5468 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5469 }
5470
5471 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5472 false /* captureSecureLayers */);
5473
5474 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5475 std::placeholders::_1);
5476 bool ignored = false;
5477 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5478 false /* useIdentityTransform */,
5479 ignored /* outCapturedSecureLayers */);
5480}
5481
Robert Carr866455f2019-04-02 16:28:26 -07005482status_t SurfaceFlinger::captureLayers(
5483 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5484 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5485 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5486 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005487 ATRACE_CALL();
5488
5489 class LayerRenderArea : public RenderArea {
5490 public:
Robert Carr578038f2018-03-09 12:25:24 -08005491 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005492 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005493 bool childrenOnly, const Rect& displayViewport)
5494 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005495 mLayer(layer),
5496 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005497 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005498 mFlinger(flinger),
5499 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005500 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005501 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005502 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005503 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005504 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005505 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005506 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005507 }
chaviwa76b2712017-09-20 12:02:26 -07005508 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005509 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005510 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005511 Rect getSourceCrop() const override {
5512 if (mCrop.isEmpty()) {
5513 return getBounds();
5514 } else {
5515 return mCrop;
5516 }
5517 }
Robert Carr578038f2018-03-09 12:25:24 -08005518 class ReparentForDrawing {
5519 public:
5520 const sp<Layer>& oldParent;
5521 const sp<Layer>& newParent;
5522
Vishnu Nair4351ad52019-02-11 14:13:02 -08005523 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5524 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005525 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005526 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005527 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5528 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005529 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005530 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005531 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005532 };
5533
5534 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005535 const Rect sourceCrop = getSourceCrop();
5536 // no need to check rotation because there is none
5537 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5538 sourceCrop.height() != getReqHeight();
5539
Robert Carr578038f2018-03-09 12:25:24 -08005540 if (!mChildrenOnly) {
5541 mTransform = mLayer->getTransform().inverse();
5542 drawLayers();
5543 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005544 uint32_t w = static_cast<uint32_t>(getWidth());
5545 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005546 // In the "childrenOnly" case we reparent the children to a screenshot
5547 // layer which has no properties set and which does not draw.
5548 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005549 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5550 "Screenshot Parent"s, w, h, 0,
5551 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005552
Vishnu Nair4351ad52019-02-11 14:13:02 -08005553 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005554 drawLayers();
5555 }
5556 }
chaviwa76b2712017-09-20 12:02:26 -07005557
chaviwa76b2712017-09-20 12:02:26 -07005558 private:
chaviw7206d492017-11-10 16:16:12 -08005559 const sp<Layer> mLayer;
5560 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005561
Peiyong Linefefaac2018-08-17 12:27:51 -07005562 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005563 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005564
5565 SurfaceFlinger* mFlinger;
5566 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005567 };
5568
Robert Carrc0df3122019-04-11 13:18:21 -07005569 int reqWidth = 0;
5570 int reqHeight = 0;
5571 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005572 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005573 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005574 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005575 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005576 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005577
Alec Mouri9a02eda2020-04-21 17:39:34 -07005578 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005579 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5580 ALOGE("captureLayers called with an invalid or removed parent");
5581 return NAME_NOT_FOUND;
5582 }
5583
5584 const int uid = IPCThreadState::self()->getCallingUid();
5585 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5586 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5587 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5588 return PERMISSION_DENIED;
5589 }
5590
Vishnu Nairefc42e22019-12-03 17:36:12 -08005591 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005592 if (sourceCrop.width() <= 0) {
5593 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005594 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005595 }
5596
5597 if (sourceCrop.height() <= 0) {
5598 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005599 crop.bottom = parentSourceBounds.getHeight();
5600 }
5601
5602 if (crop.isEmpty() || frameScale <= 0.0f) {
5603 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5604 // crop was not specified, or an invalid frame scale was provided.
5605 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005606 }
5607 reqWidth = crop.width() * frameScale;
5608 reqHeight = crop.height() * frameScale;
5609
5610 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005611 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005612 if (excludeLayer != nullptr) {
5613 excludeLayers.emplace(excludeLayer);
5614 } else {
5615 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5616 return NAME_NOT_FOUND;
5617 }
5618 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005619
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005620 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005621 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005622 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005623 }
5624
5625 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005626 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005627
Chia-I Wu20261cb2018-08-23 12:55:44 -07005628 // really small crop or frameScale
5629 if (reqWidth <= 0) {
5630 reqWidth = 1;
5631 }
5632 if (reqHeight <= 0) {
5633 reqHeight = 1;
5634 }
5635
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005636 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5637 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005638 auto traverseLayers = [parent, childrenOnly,
5639 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005640 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5641 if (!layer->isVisible()) {
5642 return;
Robert Carr578038f2018-03-09 12:25:24 -08005643 } else if (childrenOnly && layer == parent.get()) {
5644 return;
chaviwa76b2712017-09-20 12:02:26 -07005645 }
Robert Carr866455f2019-04-02 16:28:26 -07005646
5647 sp<Layer> p = layer;
5648 while (p != nullptr) {
5649 if (excludeLayers.count(p) != 0) {
5650 return;
5651 }
5652 p = p->getParent();
5653 }
5654
chaviwa76b2712017-09-20 12:02:26 -07005655 visitor(layer);
5656 });
5657 };
Robert Carr108b2c72019-04-02 16:32:58 -07005658
5659 bool outCapturedSecureLayers = false;
5660 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5661 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005662}
5663
5664status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5665 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005666 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005667 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005668 bool useIdentityTransform,
5669 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005670 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005671
Peiyong Lin0e003c92018-09-17 11:09:51 -07005672 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005673 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5674 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005675 *outBuffer =
5676 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5677 static_cast<android_pixel_format>(reqPixelFormat), 1,
5678 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005679
Robert Carr108b2c72019-04-02 16:32:58 -07005680 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005681 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005682}
5683
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005684status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5685 TraverseLayersFunction traverseLayers,
5686 const sp<GraphicBuffer>& buffer,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005687 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005688 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005689 // This mutex protects syncFd and captureResult for communication of the return values from the
5690 // main thread back to this Binder thread
5691 std::mutex captureMutex;
5692 std::condition_variable captureCondition;
5693 std::unique_lock<std::mutex> captureLock(captureMutex);
5694 int syncFd = -1;
5695 std::optional<status_t> captureResult;
5696
Robert Carr03480e22018-01-04 16:02:06 -08005697 const int uid = IPCThreadState::self()->getCallingUid();
5698 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5699
Dominik Laskowski8c001672018-05-30 16:52:06 -07005700 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005701 // If there is a refresh pending, bug out early and tell the binder thread to try again
5702 // after the refresh.
5703 if (mRefreshPending) {
5704 ATRACE_NAME("Skipping screenshot for now");
5705 std::unique_lock<std::mutex> captureLock(captureMutex);
5706 captureResult = std::make_optional<status_t>(EAGAIN);
5707 captureCondition.notify_one();
5708 return;
5709 }
5710
5711 status_t result = NO_ERROR;
5712 int fd = -1;
5713 {
5714 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005715 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005716 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005717 useIdentityTransform, forSystem, &fd,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005718 regionSampling, outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005719 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005720 }
5721
5722 {
5723 std::unique_lock<std::mutex> captureLock(captureMutex);
5724 syncFd = fd;
5725 captureResult = std::make_optional<status_t>(result);
5726 captureCondition.notify_one();
5727 }
5728 });
5729
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005730 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005731 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005732 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005733 while (*captureResult == EAGAIN) {
5734 captureResult.reset();
5735 result = postMessageAsync(message);
5736 if (result != NO_ERROR) {
5737 return result;
5738 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005739 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005740 }
5741 result = *captureResult;
5742 }
5743
5744 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005745 sync_wait(syncFd, -1);
5746 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005747 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005748
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005749 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005750}
5751
chaviwa76b2712017-09-20 12:02:26 -07005752void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005753 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005754 const sp<GraphicBuffer>& buffer,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005755 bool useIdentityTransform, bool regionSampling,
5756 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005757 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005758
chaviwa76b2712017-09-20 12:02:26 -07005759 const auto reqWidth = renderArea.getReqWidth();
5760 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005761 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005762 const auto transform = renderArea.getTransform();
5763 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005764 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005765
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005766 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005767 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005768
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005769 // assume that bounds are never offset, and that they are the same as the
5770 // buffer bounds.
5771 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005772 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005773 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005774
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005775 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5776 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005777
chaviw50da5042018-04-09 13:49:37 -07005778 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005779
Vishnu Nair9b079a22020-01-21 14:36:08 -08005780 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005781 fillLayer.source.buffer.buffer = nullptr;
5782 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005783 fillLayer.geometry.boundaries =
5784 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005785 fillLayer.alpha = half(alpha);
5786 clientCompositionLayers.push_back(fillLayer);
5787
Yichi Chen40773d92020-04-01 10:10:18 +08005788 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005789 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005790 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005791 const bool supportProtectedContent = false;
5792 Region clip(renderArea.getBounds());
5793 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5794 clip,
5795 useIdentityTransform,
Alec Mouri5a6d8572020-03-23 23:56:15 -07005796 layer->needsFilteringForScreenshots(renderArea.getDisplayDevice(), transform) ||
5797 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005798 renderArea.isSecure(),
5799 supportProtectedContent,
5800 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005801 displayViewport,
5802 clientCompositionDisplay.outputDataspace,
5803 true, /* realContentIsVisible */
5804 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005805 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005806 std::vector<compositionengine::LayerFE::LayerSettings> results =
5807 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005808 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005809 for (auto& settings : results) {
5810 settings.geometry.positionTransform =
5811 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07005812 // There's no need to process blurs when we're executing region sampling,
5813 // we're just trying to understand what we're drawing, and doing so without
5814 // blurs is already a pretty good approximation.
5815 if (regionSampling) {
5816 settings.backgroundBlurRadius = 0;
5817 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005818 }
Yichi Chen40773d92020-04-01 10:10:18 +08005819 clientCompositionLayers.insert(clientCompositionLayers.end(),
5820 std::make_move_iterator(results.begin()),
5821 std::make_move_iterator(results.end()));
5822 renderedLayers.push_back(layer);
5823 }
chaviwa76b2712017-09-20 12:02:26 -07005824 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005825
Yichi Chen40773d92020-04-01 10:10:18 +08005826 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5827 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005828 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005829 clientCompositionLayerPointers.begin(),
5830 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005831
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005832 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005833 // Use an empty fence for the buffer fence, since we just created the buffer so
5834 // there is no need for synchronization with the GPU.
5835 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005836 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005837 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005838 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005839 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005840
5841 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005842
5843 if (*outSyncFd >= 0) {
5844 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5845 for (auto* layer : renderedLayers) {
5846 layer->onLayerDisplayed(releaseFence);
5847 }
5848 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005849}
5850
chaviwa76b2712017-09-20 12:02:26 -07005851status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5852 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005853 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005854 bool useIdentityTransform, bool forSystem,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005855 int* outSyncFd, bool regionSampling,
5856 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005857 ATRACE_CALL();
5858
chaviwa76b2712017-09-20 12:02:26 -07005859 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005860 outCapturedSecureLayers =
5861 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005862 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005863
Robert Carr03480e22018-01-04 16:02:06 -08005864 // We allow the system server to take screenshots of secure layers for
5865 // use in situations like the Screen-rotation animation and place
5866 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005867 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005868 ALOGW("FB is protected: PERMISSION_DENIED");
5869 return PERMISSION_DENIED;
5870 }
Lucas Dupin9d763b72020-04-20 18:42:31 -07005871 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5872 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005873 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005874}
5875
chaviw95ef3c42019-02-14 10:55:09 -08005876void SurfaceFlinger::setInputWindowsFinished() {
5877 Mutex::Autolock _l(mStateLock);
5878
5879 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005880
chaviw95ef3c42019-02-14 10:55:09 -08005881 mTransactionCV.broadcast();
5882}
chaviw5f21a5e2019-02-14 10:00:34 -08005883
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005884// ---------------------------------------------------------------------------
5885
Edgar Arriaga844fa672020-01-16 14:21:42 -08005886void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5887 layersSortedByZ.traverse(visitor);
5888}
5889
Dan Stoza412903f2017-04-27 13:42:17 -07005890void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5891 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005892}
5893
Dan Stoza412903f2017-04-27 13:42:17 -07005894void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5895 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005896}
5897
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005898void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005899 const LayerVector::Visitor& visitor) {
5900 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005901 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005902 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005903 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005904 continue;
5905 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005906 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005907 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005908 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005909 return;
5910 }
chaviwa76b2712017-09-20 12:02:26 -07005911 if (!layer->isVisible()) {
5912 return;
5913 }
5914 visitor(layer);
5915 });
5916 }
5917}
5918
Steven Thomasd4071902020-03-24 16:02:53 -07005919status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5920 const sp<DisplayDevice>& display,
5921 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005922 Mutex::Autolock lock(mStateLock);
5923
Steven Thomasd4071902020-03-24 16:02:53 -07005924 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5925 "Can only set override policy on the primary display");
5926 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5927
Dominik Laskowski22488f62019-03-28 09:53:04 -07005928 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005929 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5930 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5931 // it should go thru setDesiredActiveConfig, similar to primary display.
5932 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5933 const auto displayId = display->getId();
5934 LOG_ALWAYS_FATAL_IF(!displayId);
5935
Peiyong Line9d809e2020-04-14 13:10:48 -07005936 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005937 constraints.desiredTimeNanos = systemTime();
5938 constraints.seamlessRequired = false;
5939
Peiyong Line9d809e2020-04-14 13:10:48 -07005940 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005941 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5942 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005943 constraints, &timeline) < 0) {
5944 return BAD_VALUE;
5945 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005946 if (timeline.refreshRequired) {
5947 repaintEverythingForHWC();
5948 }
5949
Steven Thomasd4071902020-03-24 16:02:53 -07005950 display->setActiveConfig(policy->defaultConfig);
5951 const nsecs_t vsyncPeriod = getHwComposer()
5952 .getConfigs(*displayId)[policy->defaultConfig.value()]
5953 ->getVsyncPeriod();
5954 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5955 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005956 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005957 }
5958
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005959 if (mDebugDisplayConfigSetByBackdoor) {
5960 // ignore this request as config is overridden by backdoor
5961 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005962 }
5963
Steven Thomasd4071902020-03-24 16:02:53 -07005964 status_t setPolicyResult = overridePolicy
5965 ? mRefreshRateConfigs->setOverridePolicy(policy)
5966 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5967 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005968 return BAD_VALUE;
5969 }
Steven Thomasd4071902020-03-24 16:02:53 -07005970 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005971 return NO_ERROR;
5972 }
Steven Thomasd4071902020-03-24 16:02:53 -07005973 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005974
5975 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
Steven Thomasd4071902020-03-24 16:02:53 -07005976 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
5977 currentPolicy.maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005978
5979 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5980 // that listeners that care about a change in allowed configs can get the notification.
5981 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005982 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005983 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5984 .getVsyncPeriod();
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005985 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005986 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005987
Ana Krulec3f6a2062020-01-23 15:48:01 -08005988 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005989 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005990 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5991 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005992 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005993 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005994 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005995
Ady Abrahamabc27602020-04-08 17:20:29 -07005996 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5997 ALOGV("switching to Scheduler preferred config %d",
5998 preferredRefreshRate.getConfigId().value());
5999 setDesiredActiveConfig(
6000 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006001 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07006002 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
6003 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006004 }
6005
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006006 return NO_ERROR;
6007}
6008
Ana Krulec0782b882019-10-15 17:34:54 -07006009status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006010 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07006011 float maxRefreshRate) {
6012 ATRACE_CALL();
6013
6014 if (!displayToken) {
6015 return BAD_VALUE;
6016 }
6017
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006018 status_t result = NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006019
Ana Krulec234bb162019-11-10 22:55:55 +01006020 postMessageSync(new LambdaMessage([&]() {
6021 const auto display = getDisplayDeviceLocked(displayToken);
6022 if (!display) {
6023 ALOGE("Attempt to set desired display configs for invalid display token %p",
6024 displayToken.get());
6025 } else if (display->isVirtual()) {
6026 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006027 result = INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006028 } else {
Steven Thomasd4071902020-03-24 16:02:53 -07006029 result = setDesiredDisplayConfigSpecsInternal(display,
6030 scheduler::RefreshRateConfigs::
6031 Policy{HwcConfigIndexType(
6032 defaultConfig),
6033 minRefreshRate,
6034 maxRefreshRate},
6035 /*overridePolicy=*/false);
Ana Krulec234bb162019-11-10 22:55:55 +01006036 }
6037 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006038
6039 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01006040}
6041
6042status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006043 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01006044 float* outMinRefreshRate,
6045 float* outMaxRefreshRate) {
6046 ATRACE_CALL();
6047
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006048 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01006049 return BAD_VALUE;
6050 }
6051
6052 Mutex::Autolock lock(mStateLock);
6053 const auto display = getDisplayDeviceLocked(displayToken);
6054 if (!display) {
6055 return NAME_NOT_FOUND;
6056 }
6057
6058 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006059 scheduler::RefreshRateConfigs::Policy policy =
6060 mRefreshRateConfigs->getDisplayManagerPolicy();
6061 *outDefaultConfig = policy.defaultConfig.value();
6062 *outMinRefreshRate = policy.minRefreshRate;
6063 *outMaxRefreshRate = policy.maxRefreshRate;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006064 return NO_ERROR;
6065 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006066 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006067 } else {
6068 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006069 LOG_FATAL_IF(!displayId);
6070
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006071 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6072 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6073 *outMinRefreshRate = 1e9f / vsyncPeriod;
6074 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6075 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006076 }
Ana Krulec0782b882019-10-15 17:34:54 -07006077}
6078
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006079void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006080 mFlinger->setInputWindowsFinished();
6081}
6082
Alec Mouri9a02eda2020-04-21 17:39:34 -07006083wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6084 Mutex::Autolock _l(mStateLock);
6085 return fromHandleLocked(handle);
6086}
6087
6088wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006089 BBinder* b = nullptr;
6090 if (handle) {
6091 b = handle->localBinder();
6092 }
Robert Carrc0df3122019-04-11 13:18:21 -07006093 if (b == nullptr) {
6094 return nullptr;
6095 }
6096 auto it = mLayersByLocalBinderToken.find(b);
6097 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006098 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006099 }
6100 return nullptr;
6101}
6102
Dominik Laskowski75848362019-11-11 17:57:20 -08006103void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006104 mNumLayers++;
6105 mScheduler->registerLayer(layer);
6106}
6107
6108void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6109 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006110 removeFromOffscreenLayers(layer);
6111}
6112
6113// WARNING: ONLY CALL THIS FROM LAYER DTOR
6114// Here we add children in the current state to offscreen layers and remove the
6115// layer itself from the offscreen layer list. Since
6116// this is the dtor, it is safe to access the current state. This keeps us
6117// from dangling children layers such that they are not reachable from the
6118// Drawing state nor the offscreen layer list
6119// See b/141111965
6120void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6121 for (auto& child : layer->getCurrentChildren()) {
6122 mOffscreenLayers.emplace(child.get());
6123 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006124 mOffscreenLayers.erase(layer);
6125}
6126
Alec Mouri4545a8a2019-08-08 20:05:32 -07006127void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6128 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6129}
6130
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006131status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6132 float lightPosY, float lightPosZ,
6133 float lightRadius) {
6134 Mutex::Autolock _l(mStateLock);
6135 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6136 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6137 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6138 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6139 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6140
6141 // these values are overridden when calculating the shadow settings for a layer.
6142 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6143 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006144 return NO_ERROR;
6145}
6146
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006147const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6148 const {
6149 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6150 // on the work to remove the table in that bug rather than adding more to
6151 // it.
6152 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6153 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6154 // supported, and exposed via the
6155 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6156 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6157 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6158 };
6159 return genericLayerMetadataKeyMap;
6160}
6161
Steven Thomas62a4cf82020-01-31 12:04:03 -08006162status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6163 int8_t compatibility) {
6164 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6165 return BAD_VALUE;
6166 }
6167
Ady Abraham60e42ea2020-03-09 19:17:31 -07006168 postMessageAsync(new LambdaMessage([=]() NO_THREAD_SAFETY_ANALYSIS {
6169 Mutex::Autolock lock(mStateLock);
6170 if (authenticateSurfaceTextureLocked(surface)) {
6171 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6172 if (layer->setFrameRate(
6173 Layer::FrameRate(frameRate,
6174 Layer::FrameRate::convertCompatibility(compatibility)))) {
6175 setTransactionFlags(eTraversalNeeded);
6176 }
6177 } else {
6178 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6179 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006180 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006181 return NO_ERROR;
6182 }));
6183
Steven Thomas62a4cf82020-01-31 12:04:03 -08006184 return NO_ERROR;
6185}
6186
Steven Thomasd4071902020-03-24 16:02:53 -07006187status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6188 if (!outToken) {
6189 return BAD_VALUE;
6190 }
6191 status_t result = NO_ERROR;
6192 postMessageSync(new LambdaMessage([&]() {
6193 if (mFrameRateFlexibilityTokenCount == 0) {
6194 // |mStateLock| not needed as we are on the main thread
6195 const auto display = getDefaultDisplayDeviceLocked();
6196
6197 // This is a little racy, but not in a way that hurts anything. As we grab the
6198 // defaultConfig from the display manager policy, we could be setting a new display
6199 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6200 // matter for the override policy though, since we set allowGroupSwitching to true, so
6201 // it's not a problem.
6202 scheduler::RefreshRateConfigs::Policy overridePolicy;
6203 overridePolicy.defaultConfig =
6204 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6205 overridePolicy.allowGroupSwitching = true;
6206 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy,
6207 /*overridePolicy=*/true);
6208 }
6209
6210 if (result == NO_ERROR) {
6211 mFrameRateFlexibilityTokenCount++;
6212 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6213 // below, is something to consider carefully. The lifetime of the
6214 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6215 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6216 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6217 // in this case, for two reasons:
6218 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6219 // the program exits is via a crash. So we won't have a situation where the
6220 // SurfaceFlinger object is dead but the process is still up.
6221 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6222 // if condition 1 were changed, the problem would only show up when running CTS tests,
6223 // not on end user devices, so we could spot it and fix it without serious impact.
6224 *outToken = new FrameRateFlexibilityToken(
6225 [this]() { onFrameRateFlexibilityTokenReleased(); });
6226 ALOGD("Frame rate flexibility token acquired. count=%d",
6227 mFrameRateFlexibilityTokenCount);
6228 }
6229 }));
6230 return result;
6231}
6232
6233void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
6234 postMessageAsync(new LambdaMessage([&]() {
6235 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6236 "Failed tracking frame rate flexibility tokens");
6237 mFrameRateFlexibilityTokenCount--;
6238 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6239 if (mFrameRateFlexibilityTokenCount == 0) {
6240 // |mStateLock| not needed as we are on the main thread
6241 const auto display = getDefaultDisplayDeviceLocked();
6242 status_t result =
6243 setDesiredDisplayConfigSpecsInternal(display, {}, /*overridePolicy=*/true);
6244 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6245 }
6246 }));
6247}
6248
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006249} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006250
Mathias Agopian3f844832013-08-07 21:24:32 -07006251#if defined(__gl_h_)
6252#error "don't include gl/gl.h in this file"
6253#endif
6254
6255#if defined(__gl2_h_)
6256#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006257#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006258
6259// TODO(b/129481165): remove the #pragma below and fix conversion issues
6260#pragma clang diagnostic pop // ignored "-Wconversion"