blob: 1c5b32cc42f86afa7784f2534502deeddab91783 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri989ddbe2020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri989ddbe2020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Steven Thomasb02664d2017-07-26 18:48:28 -0700143namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700144
145#pragma clang diagnostic push
146#pragma clang diagnostic error "-Wswitch-enum"
147
148bool isWideColorMode(const ColorMode colorMode) {
149 switch (colorMode) {
150 case ColorMode::DISPLAY_P3:
151 case ColorMode::ADOBE_RGB:
152 case ColorMode::DCI_P3:
153 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700154 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700155 case ColorMode::BT2100_PQ:
156 case ColorMode::BT2100_HLG:
157 return true;
158 case ColorMode::NATIVE:
159 case ColorMode::STANDARD_BT601_625:
160 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
161 case ColorMode::STANDARD_BT601_525:
162 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
163 case ColorMode::STANDARD_BT709:
164 case ColorMode::SRGB:
165 return false;
166 }
167 return false;
168}
169
170#pragma clang diagnostic pop
171
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700172template <typename Mutex>
173struct ConditionalLockGuard {
174 ConditionalLockGuard(Mutex& mutex, bool lock) : mutex(mutex), lock(lock) {
175 if (lock) mutex.lock();
Steven Thomasb02664d2017-07-26 18:48:28 -0700176 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700177
178 ~ConditionalLockGuard() {
179 if (lock) mutex.unlock();
180 }
181
182 Mutex& mutex;
183 const bool lock;
Steven Thomasb02664d2017-07-26 18:48:28 -0700184};
Peiyong Linfca547f2018-07-09 13:03:33 -0700185
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700186using ConditionalLock = ConditionalLockGuard<Mutex>;
187
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800188// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
189constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
190
191float getDensityFromProperty(const char* property, bool required) {
192 char value[PROPERTY_VALUE_MAX];
193 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
194 if (!density && required) {
195 ALOGE("%s must be defined as a build property", property);
196 return FALLBACK_DENSITY;
197 }
198 return density / 160.f;
199}
200
Peiyong Lin9d846a52018-11-05 13:18:20 -0800201// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
202bool validateCompositionDataspace(Dataspace dataspace) {
203 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
204}
205
Steven Thomasd4071902020-03-24 16:02:53 -0700206class FrameRateFlexibilityToken : public BBinder {
207public:
208 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
209 virtual ~FrameRateFlexibilityToken() { mCallback(); }
210
211private:
212 std::function<void()> mCallback;
213};
214
Steven Thomasb02664d2017-07-26 18:48:28 -0700215} // namespace anonymous
216
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217// ---------------------------------------------------------------------------
218
Mathias Agopian99b49842011-06-27 16:05:52 -0700219const String16 sHardwareTest("android.permission.HARDWARE_TEST");
220const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
221const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
222const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800223const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700224
225// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700226int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700227bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800228uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800229bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800230bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800231int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100232uint32_t SurfaceFlinger::maxGraphicsWidth;
233uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600234bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800235ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700236bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700237bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700238Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
239ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
240Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
241ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800242bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700243
Kalle Raitaa099a242017-01-11 11:17:29 -0800244std::string getHwcServiceName() {
245 char value[PROPERTY_VALUE_MAX] = {};
246 property_get("debug.sf.hwc_service_name", value, "default");
247 ALOGI("Using HWComposer service: '%s'", value);
248 return std::string(value);
249}
250
251bool useTrebleTestingOverride() {
252 char value[PROPERTY_VALUE_MAX] = {};
253 property_get("debug.sf.treble_testing_override", value, "false");
254 ALOGI("Treble testing override: '%s'", value);
255 return std::string(value) == "true";
256}
257
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
259 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800260 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700261 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800262 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700263 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800264 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700265 return std::string("Enhanced");
266 default:
267 return std::string("Unknown ") +
268 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800269 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800270}
271
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700272SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800273
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700274SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
275 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700276 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700277 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700278 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700279 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700280 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800281 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
282 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800283
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700284SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800285 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800286
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900287 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800294
Steven Thomas050b2c82017-03-06 11:45:16 -0800295 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900296 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800297
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800299
Brian Lindahla13f2d52020-03-05 11:54:17 +0100300 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
301 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
302
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900303 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700304
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600306
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 mDefaultCompositionDataspace =
308 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700309 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
310 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 defaultCompositionDataspace = mDefaultCompositionDataspace;
312 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
313 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
314 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
315 wideColorGamutCompositionPixelFormat =
316 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700317
Yichi Chenda901bf2019-06-28 14:58:27 +0800318 mColorSpaceAgnosticDataspace =
319 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800322
Dominik Laskowski718f9602019-11-09 20:01:35 -0800323 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
324 switch (primary_display_orientation(Values::ORIENTATION_0)) {
325 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800326 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800327 case Values::ORIENTATION_90:
328 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800329 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800330 case Values::ORIENTATION_180:
331 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800332 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800333 case Values::ORIENTATION_270:
334 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
336 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800337 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800338
Sundong Ahn85131bd2019-02-18 15:51:53 +0900339 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800340
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800341 // debugging stuff...
342 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700343
Mathias Agopianb4b17302013-03-20 18:36:41 -0700344 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700345 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700346
Alec Mouri989ddbe2020-02-06 09:26:19 -0800347 property_get("ro.build.type", value, "user");
348 mIsUserBuild = strcmp(value, "user") == 0;
349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800350 property_get("debug.sf.showupdates", value, "0");
351 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700352
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700353 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000354
355 // DDMS debugging deprecated (b/120782499)
356 property_get("debug.sf.ddms", value, "0");
357 int debugDdms = atoi(value);
358 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700359
360 property_get("debug.sf.disable_backpressure", value, "0");
361 mPropagateBackpressure = !atoi(value);
362 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700363
Ady Abrahamadb9a992019-09-19 21:21:55 +0000364 property_get("debug.sf.enable_gl_backpressure", value, "0");
365 mPropagateBackpressureClientComposition = atoi(value);
366 ALOGI_IF(mPropagateBackpressureClientComposition,
367 "Enabling backpressure propagation for Client Composition");
368
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800369 property_get("debug.sf.enable_hwc_vds", value, "0");
370 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800371 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800372
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800373 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800374 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800375 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700376
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800377 property_get("ro.surface_flinger.supports_background_blur", value, "0");
378 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700379 mSupportsBlur = supportsBlurs;
380 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800381 property_get("ro.sf.blurs_are_expensive", value, "0");
382 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800383
Ady Abraham0a525092020-03-03 12:51:24 -0800384 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700385 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
386 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
387
Dan Stozaec460082018-12-17 15:35:09 -0800388 property_get("debug.sf.luma_sampling", value, "1");
389 mLumaSampling = atoi(value);
390
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800391 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800392 mDisableClientCompositionCache = atoi(value);
393
Romain Guy11d63f42017-07-20 12:47:14 -0700394 // We should be reading 'persist.sys.sf.color_saturation' here
395 // but since /data may be encrypted, we need to wait until after vold
396 // comes online to attempt to read the property. The property is
397 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800398
399 if (useTrebleTestingOverride()) {
400 // Without the override SurfaceFlinger cannot connect to HIDL
401 // services that are not listed in the manifests. Considered
402 // deriving the setting from the set service name, but it
403 // would be brittle if the name that's not 'default' is used
404 // for production purposes later on.
405 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
406 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800407
408 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409}
410
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411void SurfaceFlinger::onFirstRef()
412{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800413 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414}
415
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700416SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417
Dan Stozac7014012014-02-14 15:03:43 -0800418void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800419{
420 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700421 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422
Andy McFadden13a082e2012-08-24 10:16:42 -0700423 // restore initial conditions (default device unblank, etc)
424 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425
426 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700427 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428}
429
Robert Carr1db73f62016-12-21 12:58:51 -0800430static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700431 status_t err = client->initCheck();
432 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800433 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434 }
Robert Carr1db73f62016-12-21 12:58:51 -0800435 return nullptr;
436}
437
438sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
439 return initClient(new Client(this));
440}
441
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700442sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
443 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700444{
445 class DisplayToken : public BBinder {
446 sp<SurfaceFlinger> flinger;
447 virtual ~DisplayToken() {
448 // no more references, this display must be terminated
449 Mutex::Autolock _l(flinger->mStateLock);
450 flinger->mCurrentState.displays.removeItem(this);
451 flinger->setTransactionFlags(eDisplayTransactionNeeded);
452 }
453 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700454 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700455 : flinger(flinger) {
456 }
457 };
458
459 sp<BBinder> token = new DisplayToken(this);
460
461 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700462 // Display ID is assigned when virtual display is allocated by HWC.
463 DisplayDeviceState state;
464 state.isSecure = secure;
465 state.displayName = displayName;
466 mCurrentState.displays.add(token, state);
467 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468 return token;
469}
470
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700471void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700472 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700473
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700474 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700476 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700477 return;
478 }
479
Dominik Laskowski075d3172018-05-24 15:50:06 -0700480 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700481 if (state.physical) {
482 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700483 return;
484 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485 mInterceptor->saveDisplayDeletion(state.sequenceId);
486 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 setTransactionFlags(eDisplayTransactionNeeded);
488}
489
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800490std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
491 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800493 const auto internalDisplayId = getInternalDisplayIdLocked();
494 if (!internalDisplayId) {
495 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496 }
497
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800498 std::vector<PhysicalDisplayId> displayIds;
499 displayIds.reserve(mPhysicalDisplayTokens.size());
500 displayIds.push_back(internalDisplayId->value);
501
502 for (const auto& [id, token] : mPhysicalDisplayTokens) {
503 if (id != *internalDisplayId) {
504 displayIds.push_back(id.value);
505 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800508 return displayIds;
509}
510
511sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
512 Mutex::Autolock lock(mStateLock);
513 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700514}
515
Ady Abraham37965d42018-11-01 13:43:32 -0700516status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
517 if (!outGetColorManagement) {
518 return BAD_VALUE;
519 }
520 *outGetColorManagement = useColorManagement;
521 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700522}
523
Lloyd Pique441d5042018-10-18 16:49:51 -0700524HWComposer& SurfaceFlinger::getHwComposer() const {
525 return mCompositionEngine->getHwComposer();
526}
527
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700528renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
529 return mCompositionEngine->getRenderEngine();
530}
531
Lloyd Pique70d91362018-10-18 16:02:55 -0700532compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
533 return *mCompositionEngine.get();
534}
535
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800536void SurfaceFlinger::bootFinished()
537{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700538 if (mBootFinished == true) {
539 ALOGE("Extra call to bootFinished");
540 return;
541 }
542 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700543 if (mStartPropertySetThread->join() != NO_ERROR) {
544 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800545 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546 const nsecs_t now = systemTime();
547 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000548 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549
Mikael Pessa90092f42019-08-26 17:22:04 -0700550 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000551 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700552
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700553 // wait patiently for the window manager death
554 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700555 mWindowManager = defaultServiceManager()->getService(name);
556 if (mWindowManager != 0) {
557 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700558 }
Robert Carr720e5062018-07-30 17:45:14 -0700559 sp<IBinder> input(defaultServiceManager()->getService(
560 String16("inputflinger")));
561 if (input == nullptr) {
562 ALOGE("Failed to link to input service");
563 } else {
564 mInputFlinger = interface_cast<IInputFlinger>(input);
565 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700566
Steven Thomas050b2c82017-03-06 11:45:16 -0800567 if (mVrFlinger) {
568 mVrFlinger->OnBootFinished();
569 }
570
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700571 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700572 // formerly we would just kill the process, but we now ask it to exit so it
573 // can choose where to stop the animation.
574 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700575
576 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
577 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
578 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700579
Ana Krulecbd6654b2019-02-15 15:18:15 -0800580 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800581 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700582 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800583 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800584
Ady Abraham8a82ba62020-01-17 12:43:17 -0800585 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
586 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
587 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
588 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800589 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800590}
591
Dan Stoza436ccf32018-06-21 12:10:12 -0700592uint32_t SurfaceFlinger::getNewTexture() {
593 {
594 std::lock_guard lock(mTexturePoolMutex);
595 if (!mTexturePool.empty()) {
596 uint32_t name = mTexturePool.back();
597 mTexturePool.pop_back();
598 ATRACE_INT("TexturePoolSize", mTexturePool.size());
599 return name;
600 }
601
602 // The pool was too small, so increase it for the future
603 ++mTexturePoolSize;
604 }
605
606 // The pool was empty, so we need to get a new texture name directly using a
607 // blocking call to the main thread
608 uint32_t name = 0;
609 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
610 return name;
611}
612
Mathias Agopian3f844832013-08-07 21:24:32 -0700613void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700614 std::lock_guard lock(mTexturePoolMutex);
615 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
616 // to actually delete this or not based on mTexturePoolSize
617 mTexturePool.push_back(texture);
618 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700619}
620
Wei Wangf9b05ee2017-07-19 20:59:39 -0700621// Do not call property_set on main thread which will be blocked by init
622// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700623void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700624 ALOGI( "SurfaceFlinger's main thread ready to run. "
625 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700626 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800627
Steven Thomasb02664d2017-07-26 18:48:28 -0700628 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700629 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800630 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700631 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
632 renderengine::RenderEngineCreationArgs::Builder()
633 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
634 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
635 .setUseColorManagerment(useColorManagement)
636 .setEnableProtectedContext(enable_protected_contents(false))
637 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700638 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700639 .setContextPriority(useContextPriority
640 ? renderengine::RenderEngine::ContextPriority::HIGH
641 : renderengine::RenderEngine::ContextPriority::MEDIUM)
642 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800643 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700644
645 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
646 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700647 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800648 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800649 // Process any initial hotplug and resulting display changes.
650 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700651 const auto display = getDefaultDisplayDeviceLocked();
652 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700653 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700654 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800655
Steven Thomas050b2c82017-03-06 11:45:16 -0800656 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700657 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700658 // This callback is called from the vr flinger dispatch thread. We
659 // need to call signalTransaction(), which requires holding
660 // mStateLock when we're not on the main thread. Acquiring
661 // mStateLock from the vr flinger dispatch thread might trigger a
662 // deadlock in surface flinger (see b/66916578), so post a message
663 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700664 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700665 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
666 mVrFlingerRequestsDisplay = requestDisplay;
667 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700668 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700670 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
671 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700672 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700673 .value_or(0),
674 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 if (!mVrFlinger) {
676 ALOGE("Failed to start vrflinger");
677 }
678 }
679
Mathias Agopian92a979a2012-08-02 18:32:23 -0700680 // initialize our drawing state
681 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700682
Andy McFadden13a082e2012-08-24 10:16:42 -0700683 // set initial conditions (e.g. unblank default device)
684 initializeDisplays();
685
Steven Thomas137d4bc2019-07-25 16:55:14 -0700686 char primeShaderCache[PROPERTY_VALUE_MAX];
687 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
688 if (atoi(primeShaderCache)) {
689 getRenderEngine().primeCache();
690 }
Dan Stoza4e637772016-07-28 13:31:51 -0700691
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700693
694 const bool presentFenceReliable =
695 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
696 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700697
698 if (mStartPropertySetThread->Start() != NO_ERROR) {
699 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800700 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800701
Dan Stoza9e56aa02015-11-02 13:00:03 -0800702 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700703}
704
Romain Guy11d63f42017-07-20 12:47:14 -0700705void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700706 Mutex::Autolock _l(mStateLock);
707
Romain Guy11d63f42017-07-20 12:47:14 -0700708 char value[PROPERTY_VALUE_MAX];
709
710 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800711 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700712 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800713 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100714
715 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700716 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800717
718 property_get("persist.sys.sf.color_mode", value, "0");
719 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700720
721 property_get("persist.sys.sf.disable_blurs", value, "0");
722 bool disableBlurs = atoi(value);
723 mDisableBlurs = disableBlurs;
724 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700725}
726
Mathias Agopiana67e4182012-06-19 17:26:12 -0700727void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800728 // Start boot animation service by setting a property mailbox
729 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700730 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800731 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700732 if (mStartPropertySetThread->join() != NO_ERROR) {
733 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800734 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700735}
736
Mathias Agopian875d8e12013-06-07 15:35:48 -0700737size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700738 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700739}
740
Mathias Agopian875d8e12013-06-07 15:35:48 -0700741size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700742 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700743}
744
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800745// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800746
Jamie Gennis582270d2011-08-17 18:19:00 -0700747bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800748 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800749 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800750 return authenticateSurfaceTextureLocked(bufferProducer);
751}
752
753bool SurfaceFlinger::authenticateSurfaceTextureLocked(
754 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800755 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800756 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800757}
758
Brian Anderson6b376712017-04-04 10:51:39 -0700759status_t SurfaceFlinger::getSupportedFrameTimestamps(
760 std::vector<FrameEvent>* outSupported) const {
761 *outSupported = {
762 FrameEvent::REQUESTED_PRESENT,
763 FrameEvent::ACQUIRE,
764 FrameEvent::LATCH,
765 FrameEvent::FIRST_REFRESH_START,
766 FrameEvent::LAST_REFRESH_START,
767 FrameEvent::GPU_COMPOSITION_DONE,
768 FrameEvent::DEQUEUE_READY,
769 FrameEvent::RELEASE,
770 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700771 ConditionalLock _l(mStateLock,
772 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700773 if (!getHwComposer().hasCapability(
774 HWC2::Capability::PresentFenceIsNotReliable)) {
775 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
776 }
777 return NO_ERROR;
778}
779
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800780status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
781 if (!displayToken || !state) {
782 return BAD_VALUE;
783 }
784
785 Mutex::Autolock lock(mStateLock);
786
787 const auto display = getDisplayDeviceLocked(displayToken);
788 if (!display) {
789 return NAME_NOT_FOUND;
790 }
791
792 state->layerStack = display->getLayerStack();
793 state->orientation = display->getOrientation();
794
795 const Rect viewport = display->getViewport();
796 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
797
798 return NO_ERROR;
799}
800
801status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
802 if (!displayToken || !info) {
803 return BAD_VALUE;
804 }
805
806 Mutex::Autolock lock(mStateLock);
807
808 const auto display = getDisplayDeviceLocked(displayToken);
809 if (!display) {
810 return NAME_NOT_FOUND;
811 }
812
Dominik Laskowski55c85402020-01-21 16:25:47 -0800813 if (const auto connectionType = display->getConnectionType())
814 info->connectionType = *connectionType;
815 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800816 return INVALID_OPERATION;
817 }
818
819 if (mEmulatedDisplayDensity) {
820 info->density = mEmulatedDisplayDensity;
821 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800822 info->density = info->connectionType == DisplayConnectionType::Internal
823 ? mInternalDisplayDensity
824 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800825 }
826
827 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200828 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800829
830 return NO_ERROR;
831}
832
Dominik Laskowski22488f62019-03-28 09:53:04 -0700833status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800834 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700835 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 return BAD_VALUE;
837 }
838
Dominik Laskowski22488f62019-03-28 09:53:04 -0700839 Mutex::Autolock lock(mStateLock);
840
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800841 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700842 if (!displayId) {
843 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700844 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700845
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800846 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700847
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700849
Dominik Laskowski075d3172018-05-24 15:50:06 -0700850 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800851 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700852
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800853 auto width = hwConfig->getWidth();
854 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700855
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800856 auto xDpi = hwConfig->getDpiX();
857 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700858
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800859 if (isInternal &&
860 (internalDisplayOrientation == ui::ROTATION_90 ||
861 internalDisplayOrientation == ui::ROTATION_270)) {
862 std::swap(width, height);
863 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 }
865
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800866 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800867
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800868 if (mEmulatedDisplayDensity) {
869 config.xDpi = mEmulatedDisplayDensity;
870 config.yDpi = mEmulatedDisplayDensity;
871 } else {
872 config.xDpi = xDpi;
873 config.yDpi = yDpi;
874 }
875
876 const nsecs_t period = hwConfig->getVsyncPeriod();
877 config.refreshRate = 1e9f / period;
878
879 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
880 config.appVsyncOffset = offsets.late.app;
881 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800882 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800883
Andy McFadden91b2ca82014-06-13 14:04:23 -0700884 // This is how far in advance a buffer must be queued for
885 // presentation at a given time. If you want a buffer to appear
886 // on the screen at time N, you must submit the buffer before
887 // (N - presentationDeadline).
888 //
889 // Normally it's one full refresh period (to give SF a chance to
890 // latch the buffer), but this can be reduced by configuring a
891 // DispSync offset. Any additional delays introduced by the hardware
892 // composer or panel must be accounted for here.
893 //
894 // We add an additional 1ms to allow for processing time and
895 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800896 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700897
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800898 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700899 }
900
Dan Stoza7f7da322014-05-02 15:26:25 -0700901 return NO_ERROR;
902}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700903
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700904status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
905 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700906 return BAD_VALUE;
907 }
908
Ana Krulecc2870422019-01-29 19:00:58 -0800909 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700910 return NO_ERROR;
911}
912
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700913int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700914 int activeConfig;
915 bool isPrimary;
916
917 {
918 Mutex::Autolock lock(mStateLock);
919
920 if (const auto display = getDisplayDeviceLocked(displayToken)) {
921 activeConfig = display->getActiveConfig().value();
922 isPrimary = display->isPrimary();
923 } else {
924 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
925 return NAME_NOT_FOUND;
926 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800927 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700928
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700929 if (isPrimary) {
Steven Thomasc9098452019-09-30 17:15:05 -0700930 std::lock_guard<std::mutex> lock(mActiveConfigLock);
931 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800932 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700933 }
Steven Thomasc9098452019-09-30 17:15:05 -0700934 }
Ady Abraham2139f732019-11-13 18:56:40 -0800935
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700936 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700937}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700938
Ady Abraham03b02dd2019-03-21 15:40:11 -0700939void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800940 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800941 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700942 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800943
Ady Abrahamb838aed2019-02-12 15:30:16 -0800944 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800945 if (mDesiredActiveConfigChanged) {
946 // If a config change is pending, just cache the latest request in
947 // mDesiredActiveConfig
948 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
949 mDesiredActiveConfig = info;
950 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
951 } else {
952 // Check is we are already at the desired config
953 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700954 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800955 return;
956 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800957
Ady Abraham59db0a32020-03-02 18:04:20 -0800958 // Initiate a config change.
959 mDesiredActiveConfigChanged = true;
960 mDesiredActiveConfig = info;
961
Ady Abrahamb838aed2019-02-12 15:30:16 -0800962 // This will trigger HWC refresh without resetting the idle timer.
963 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700964 // Start receiving vsync samples now, so that we can detect a period
965 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700966 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700967 // As we called to set period, we will call to onRefreshRateChangeCompleted once
968 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700969 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800970
Ady Abrahamabc27602020-04-08 17:20:29 -0700971 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800972 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700974
975 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800976 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700977 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978}
979
980status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
981 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800982
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100983 if (!displayToken) {
984 return BAD_VALUE;
985 }
Ady Abraham838de062019-02-04 10:24:03 -0800986
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700987 status_t result = NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100988
989 postMessageSync(new LambdaMessage([&]() {
990 const auto display = getDisplayDeviceLocked(displayToken);
991 if (!display) {
992 ALOGE("Attempt to set allowed display configs for invalid display token %p",
993 displayToken.get());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100994 } else if (display->isVirtual()) {
995 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700996 result = INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100997 } else {
998 HwcConfigIndexType config(mode);
999 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
Steven Thomasd4071902020-03-24 16:02:53 -07001000 result = setDesiredDisplayConfigSpecsInternal(display,
1001 scheduler::RefreshRateConfigs::
Ady Abrahamabc27602020-04-08 17:20:29 -07001002 Policy{config,
1003 refreshRate.getFps(),
1004 refreshRate.getFps()},
Steven Thomasd4071902020-03-24 16:02:53 -07001005 /*overridePolicy=*/false);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001006 }
1007 }));
1008
1009 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001010}
1011
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001012void SurfaceFlinger::setActiveConfigInternal() {
1013 ATRACE_CALL();
1014
Dominik Laskowski22488f62019-03-28 09:53:04 -07001015 const auto display = getDefaultDisplayDeviceLocked();
1016 if (!display) {
1017 return;
1018 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001019
Alec Mouri8de697e2020-03-19 10:52:01 -07001020 auto& oldRefreshRate =
1021 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1022
Dominik Laskowski22488f62019-03-28 09:53:04 -07001023 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001024 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001025 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001026 display->setActiveConfig(mUpcomingActiveConfig.configId);
1027
Ady Abraham2e1dd892020-03-05 13:48:36 -08001028 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001029 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001030 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001031 mTimeStats->incrementRefreshRateSwitches();
1032 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001033 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001034 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001035 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001036
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001037 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001038 const nsecs_t vsyncPeriod =
1039 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001040 .getVsyncPeriod();
Ady Abraham447052e2019-02-13 16:07:27 -08001041 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001042 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001043 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001044}
1045
Ady Abraham53852a52019-05-28 18:07:44 -07001046void SurfaceFlinger::desiredActiveConfigChangeDone() {
1047 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1048 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1049 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001050
Ady Abraham2e1dd892020-03-05 13:48:36 -08001051 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001052 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001053 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1054 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001055 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001056}
1057
Ady Abraham27cbed72020-04-10 12:56:59 -07001058void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001059 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001060 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001061 // Store the local variable to release the lock.
Ady Abraham27cbed72020-04-10 12:56:59 -07001062 const auto desiredActiveConfig = [&]() -> std::optional<ActiveConfigInfo> {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001063 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham27cbed72020-04-10 12:56:59 -07001064 if (mDesiredActiveConfigChanged) {
1065 return mDesiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001066 }
Ady Abraham27cbed72020-04-10 12:56:59 -07001067 return std::nullopt;
1068 }();
1069
1070 if (!desiredActiveConfig) {
1071 // No desired active config pending to be applied
1072 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001073 }
1074
Ady Abraham2e1dd892020-03-05 13:48:36 -08001075 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001076 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001077 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1078 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001079 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001080 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001081 // display is not valid or we are already in the requested mode
1082 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001083 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001084 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001085 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001086
Ady Abraham838de062019-02-04 10:24:03 -08001087 // Desired active config was set, it is different than the config currently in use, however
1088 // allowed configs might have change by the time we process the refresh.
1089 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001090 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001091 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001092 return;
Ady Abraham838de062019-02-04 10:24:03 -08001093 }
Alec Mouri7f015182019-07-11 13:56:22 -07001094
Ady Abraham27cbed72020-04-10 12:56:59 -07001095 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001096 const auto displayId = display->getId();
1097 LOG_ALWAYS_FATAL_IF(!displayId);
1098
Ady Abrahamabc27602020-04-08 17:20:29 -07001099 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001100
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001101 // TODO(b/142753666) use constrains
1102 HWC2::VsyncPeriodChangeConstraints constraints;
1103 constraints.desiredTimeNanos = systemTime();
1104 constraints.seamlessRequired = false;
1105
1106 HWC2::VsyncPeriodChangeTimeline outTimeline;
1107 auto status =
1108 getHwComposer().setActiveConfigWithConstraints(*displayId,
1109 mUpcomingActiveConfig.configId.value(),
1110 constraints, &outTimeline);
1111 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001112 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1113 // to be sent. We just log the error in this case.
1114 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001115 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001116 }
1117
1118 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1119 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001120 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001121}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001122
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001123status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1124 Vector<ColorMode>* outColorModes) {
1125 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001126 return BAD_VALUE;
1127 }
1128
Peiyong Lina52f0292018-03-14 17:26:31 -07001129 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001130 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001131 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001132 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1133
1134 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1135 if (!displayId) {
1136 return NAME_NOT_FOUND;
1137 }
1138
Dominik Laskowski075d3172018-05-24 15:50:06 -07001139 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001140 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001141 }
Michael Wright28f24d02016-07-12 13:30:53 -07001142 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001143
1144 // If it's built-in display and the configuration claims it's not wide color capable,
1145 // filter out all wide color modes. The typical reason why this happens is that the
1146 // hardware is not good enough to support GPU composition of wide color, and thus the
1147 // OEMs choose to disable this capability.
1148 if (isInternalDisplay && !hasWideColorDisplay) {
1149 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1150 isWideColorMode);
1151 } else {
1152 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1153 }
Michael Wright28f24d02016-07-12 13:30:53 -07001154
1155 return NO_ERROR;
1156}
1157
Daniel Solomon42d04562019-01-20 21:03:19 -08001158status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1159 ui::DisplayPrimaries &primaries) {
1160 if (!displayToken) {
1161 return BAD_VALUE;
1162 }
1163
1164 // Currently we only support this API for a single internal display.
1165 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001166 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001167 }
1168
1169 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1170 return NO_ERROR;
1171}
1172
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001173ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001174 Mutex::Autolock lock(mStateLock);
1175
1176 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001177 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001178 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001179 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001180}
1181
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001182status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001183 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001184 Vector<ColorMode> modes;
1185 getDisplayColorModes(displayToken, &modes);
1186 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1187 if (mode < ColorMode::NATIVE || !exists) {
1188 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1189 decodeColorMode(mode).c_str(), mode, displayToken.get());
1190 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001191 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001192 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001193 if (!display) {
1194 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1195 decodeColorMode(mode).c_str(), mode, displayToken.get());
1196 } else if (display->isVirtual()) {
1197 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1198 decodeColorMode(mode).c_str(), mode);
1199 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001200 display->getCompositionDisplay()->setColorProfile(
1201 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1202 RenderIntent::COLORIMETRIC,
1203 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001204 }
1205 }));
1206
Michael Wright28f24d02016-07-12 13:30:53 -07001207 return NO_ERROR;
1208}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001209
Galia Peycheva5492cb52019-10-30 14:13:16 +01001210status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1211 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001212 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001213 return BAD_VALUE;
1214 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001215
1216 Mutex::Autolock lock(mStateLock);
1217
Galia Peycheva5492cb52019-10-30 14:13:16 +01001218 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1219 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001220 return NAME_NOT_FOUND;
1221 }
Dominik Laskowski1162e472020-04-02 19:02:47 -07001222 *outSupport = getHwComposer().hasDisplayCapability(*displayId,
Galia Peycheva5492cb52019-10-30 14:13:16 +01001223 HWC2::DisplayCapability::AutoLowLatencyMode);
1224 return NO_ERROR;
1225}
1226
1227void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001228 postMessageAsync(new LambdaMessage([=] {
1229 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1230 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1231 } else {
1232 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1233 }
1234 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001235}
1236
1237status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1238 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001239 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001240 return BAD_VALUE;
1241 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001242
1243 Mutex::Autolock lock(mStateLock);
1244
Galia Peycheva5492cb52019-10-30 14:13:16 +01001245 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1246 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001247 return NAME_NOT_FOUND;
1248 }
1249
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001250 std::vector<HWC2::ContentType> types;
1251 getHwComposer().getSupportedContentTypes(*displayId, &types);
1252
1253 *outSupport = std::any_of(types.begin(), types.end(),
1254 [](auto type) { return type == HWC2::ContentType::Game; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001255 return NO_ERROR;
1256}
1257
1258void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001259 postMessageAsync(new LambdaMessage([=] {
1260 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1261 const auto type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1262 getHwComposer().setContentType(*displayId, type);
1263 } else {
1264 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1265 }
1266 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001267}
1268
Svetoslavd85084b2014-03-20 10:28:31 -07001269status_t SurfaceFlinger::clearAnimationFrameStats() {
1270 Mutex::Autolock _l(mStateLock);
1271 mAnimFrameTracker.clearStats();
1272 return NO_ERROR;
1273}
1274
1275status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1276 Mutex::Autolock _l(mStateLock);
1277 mAnimFrameTracker.getStats(outStats);
1278 return NO_ERROR;
1279}
1280
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001281status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1282 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001283 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001284
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001285 const auto display = getDisplayDeviceLocked(displayToken);
1286 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001287 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1288 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001289 }
1290
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001291 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001292 // meaning the luminance information is already queried from
1293 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001294 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001295 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1296 capabilities.getDesiredMaxLuminance(),
1297 capabilities.getDesiredMaxAverageLuminance(),
1298 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001299
1300 return NO_ERROR;
1301}
1302
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001303std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1304 const DisplayDevice& display) const {
1305 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1306 // avoid repetitive HAL IPC and EDID parsing.
1307 const auto displayId = display.getId();
1308 LOG_FATAL_IF(!displayId);
1309
1310 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1311 LOG_FATAL_IF(!hwcDisplayId);
1312
1313 uint8_t port;
1314 DisplayIdentificationData data;
1315 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1316 ALOGV("%s: No identification data.", __FUNCTION__);
1317 return {};
1318 }
1319
1320 const auto info = parseDisplayIdentificationData(port, data);
1321 if (!info) {
1322 return {};
1323 }
1324 return info->deviceProductInfo;
1325}
1326
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001327status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1328 ui::PixelFormat* outFormat,
1329 ui::Dataspace* outDataspace,
1330 uint8_t* outComponentMask) const {
1331 if (!outFormat || !outDataspace || !outComponentMask) {
1332 return BAD_VALUE;
1333 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001334
1335 Mutex::Autolock lock(mStateLock);
1336
1337 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1338 if (!displayId) {
1339 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001340 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001341
1342 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001343 outDataspace, outComponentMask);
1344}
1345
Kevin DuBois74e53772018-11-19 10:52:38 -08001346status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1347 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001348 uint64_t maxFrames) {
1349 status_t result = NAME_NOT_FOUND;
Kevin DuBois74e53772018-11-19 10:52:38 -08001350
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001351 postMessageSync(new LambdaMessage([&] {
1352 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1353 result = getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1354 componentMask, maxFrames);
1355 } else {
1356 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1357 }
1358 }));
1359
1360 return result;
Kevin DuBois74e53772018-11-19 10:52:38 -08001361}
1362
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001363status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1364 uint64_t maxFrames, uint64_t timestamp,
1365 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001366 Mutex::Autolock lock(mStateLock);
1367
1368 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1369 if (!displayId) {
1370 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001371 }
1372
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001373 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001374}
1375
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001376status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1377 if (!outSupported) {
1378 return BAD_VALUE;
1379 }
1380 *outSupported = getRenderEngine().supportsProtectedContent();
1381 return NO_ERROR;
1382}
1383
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001384status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1385 bool* outIsWideColorDisplay) const {
1386 if (!displayToken || !outIsWideColorDisplay) {
1387 return BAD_VALUE;
1388 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001389
1390 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001391 const auto display = getDisplayDeviceLocked(displayToken);
1392 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001393 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001394 }
Peiyong Linff84a152019-05-17 18:36:19 -07001395
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001396 *outIsWideColorDisplay =
1397 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001398 return NO_ERROR;
1399}
1400
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001401status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001402 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001403 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001404
Dominik Laskowski6505f792019-09-18 11:10:05 -07001405 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1406 mEventQueue->setEventConnection(
1407 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001408 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001409 }));
1410
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001411 return NO_ERROR;
1412}
1413
1414status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001415 Mutex::Autolock lock(mStateLock);
1416 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001417}
1418
Lloyd Pique755e3192018-01-31 16:46:15 -08001419status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1420 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001421 // Try to acquire a lock for 1s, fail gracefully
1422 const status_t err = mStateLock.timedLock(s2ns(1));
1423 const bool locked = (err == NO_ERROR);
1424 if (!locked) {
1425 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1426 return TIMED_OUT;
1427 }
1428
1429 outLayers->clear();
1430 mCurrentState.traverseInZOrder([&](Layer* layer) {
1431 outLayers->push_back(layer->getLayerDebugInfo());
1432 });
1433
1434 mStateLock.unlock();
1435 return NO_ERROR;
1436}
1437
Peiyong Linc6780972018-10-28 15:24:08 -07001438status_t SurfaceFlinger::getCompositionPreference(
1439 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1440 Dataspace* outWideColorGamutDataspace,
1441 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001442 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001443 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001444 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001445 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001446 return NO_ERROR;
1447}
1448
Dan Stozaec460082018-12-17 15:35:09 -08001449status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1450 const sp<IBinder>& stopLayerHandle,
1451 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001452 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001453 return BAD_VALUE;
1454 }
1455 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001456 return NO_ERROR;
1457}
1458
Dan Stozaec460082018-12-17 15:35:09 -08001459status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001460 if (!listener) {
1461 return BAD_VALUE;
1462 }
Dan Stozaec460082018-12-17 15:35:09 -08001463 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001464 return NO_ERROR;
1465}
Dan Gittik57e63c52019-01-18 16:37:54 +00001466
1467status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1468 bool* outSupport) const {
1469 if (!displayToken || !outSupport) {
1470 return BAD_VALUE;
1471 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001472
1473 Mutex::Autolock lock(mStateLock);
1474
Dan Gittik57e63c52019-01-18 16:37:54 +00001475 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1476 if (!displayId) {
1477 return NAME_NOT_FOUND;
1478 }
1479 *outSupport =
Dominik Laskowski1162e472020-04-02 19:02:47 -07001480 getHwComposer().hasDisplayCapability(*displayId, HWC2::DisplayCapability::Brightness);
Dan Gittik57e63c52019-01-18 16:37:54 +00001481 return NO_ERROR;
1482}
1483
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001484status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001485 if (!displayToken) {
1486 return BAD_VALUE;
1487 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001488
1489 status_t result = NAME_NOT_FOUND;
1490
1491 postMessageSync(new LambdaMessage([&] {
1492 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1493 result = getHwComposer().setDisplayBrightness(*displayId, brightness);
1494 } else {
1495 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1496 }
1497 }));
1498
1499 return result;
Dan Gittik57e63c52019-01-18 16:37:54 +00001500}
1501
Ady Abraham8532d012019-05-08 14:50:56 -07001502status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1503 PowerHint powerHint = static_cast<PowerHint>(hintId);
1504
1505 if (powerHint == PowerHint::INTERACTION) {
1506 mScheduler->notifyTouchEvent();
1507 }
1508
1509 return NO_ERROR;
1510}
1511
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001512// ----------------------------------------------------------------------------
1513
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001514sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001515 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001516 const auto& handle =
1517 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001518
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001519 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001520}
1521
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001522// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001523
1524void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001525 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001526}
1527
1528void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001529 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001530 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001531 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001532}
1533
1534void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001535 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001536 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001537 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001538}
1539
1540void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001541 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001542 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001543}
1544
1545status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001546 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001547 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001548}
1549
1550status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001551 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001552 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001553 if (res == NO_ERROR) {
1554 msg->wait();
1555 }
1556 return res;
1557}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001558
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001559void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001560 do {
1561 waitForEvent();
1562 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001563}
1564
Dominik Laskowski83b88212018-12-11 13:34:06 -08001565nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001566 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001567 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1568 return 0;
1569 }
1570
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001571 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001572}
1573
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001574void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001575 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001576 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001577 ATRACE_NAME("SF onVsync");
1578
Steven Thomas3cfac282017-02-06 12:29:30 -08001579 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001580 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001581 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001582 return;
1583 }
1584
Dominik Laskowski075d3172018-05-24 15:50:06 -07001585 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001586 return;
1587 }
1588
Dominik Laskowski075d3172018-05-24 15:50:06 -07001589 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001590 // For now, we don't do anything with external display vsyncs.
1591 return;
1592 }
1593
Alec Mourif8e689c2019-05-20 18:32:22 -07001594 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001595 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001596 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001597 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001598 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001599}
1600
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001601void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001602 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1603 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001604}
1605
Ady Abraham2139f732019-11-13 18:56:40 -08001606bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001607 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001608}
1609
Ady Abraham2139f732019-11-13 18:56:40 -08001610void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1611 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001612 const auto display = getDefaultDisplayDeviceLocked();
1613 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001614 return;
1615 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001616 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001617
Ana Krulec7d1d6832018-12-27 11:10:09 -08001618 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001619 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001620 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001621 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001622 return;
1623 }
1624
Ady Abrahamabc27602020-04-08 17:20:29 -07001625 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001626}
1627
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001628void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001629 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001630 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001631 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001632
Lloyd Piqueba04e622017-12-14 17:11:26 -08001633 // Ignore events that do not have the right sequenceId.
1634 if (sequenceId != getBE().mComposerSequenceId) {
1635 return;
1636 }
1637
Steven Thomasb02664d2017-07-26 18:48:28 -07001638 // Only lock if we're not on the main thread. This function is normally
1639 // called on a hwbinder thread, but for the primary display it's called on
1640 // the main thread with the state lock already held, so don't attempt to
1641 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001642 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001643
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001644 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001645
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001646 if (std::this_thread::get_id() == mMainThreadId) {
1647 // Process all pending hot plug events immediately if we are on the main thread.
1648 processDisplayHotplugEventsLocked();
1649 }
1650
Lloyd Piqueba04e622017-12-14 17:11:26 -08001651 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001652}
1653
Ady Abraham7159f572019-10-11 11:10:18 -07001654void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001655 int32_t sequenceId, hwc2_display_t /*display*/,
1656 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1657 Mutex::Autolock lock(mStateLock);
1658 if (sequenceId != getBE().mComposerSequenceId) {
1659 return;
1660 }
1661 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001662}
1663
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001664void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1665 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1666 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1667}
1668
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001669void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001670 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001671 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001672 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001673 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001674 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001675}
1676
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001677void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001678 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001679
1680 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1681 // display power state.
1682 postMessageAsync(new LambdaMessage(
1683 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1684}
1685
1686void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1687 ATRACE_CALL();
1688
Ady Abraham27c70212019-06-11 10:52:26 -07001689 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1690
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001691 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001692 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1693 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001694 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001695 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001696 }
Mathias Agopian86303202012-07-24 22:46:10 -07001697}
1698
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001699// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001700void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001701 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001702 // Clear the drawing state so that the logic inside of
1703 // handleTransactionLocked will fire. It will determine the delta between
1704 // mCurrentState and mDrawingState and re-apply all changes when we make the
1705 // transition.
1706 mDrawingState.displays.clear();
1707 mDisplays.clear();
1708}
1709
Steven Thomas050b2c82017-03-06 11:45:16 -08001710void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001711 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001712 if (!mVrFlinger)
1713 return;
1714 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001715 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001716 return;
1717 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001718
Lloyd Pique441d5042018-10-18 16:49:51 -07001719 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001720 ALOGE("Vr flinger is only supported for remote hardware composer"
1721 " service connections. Ignoring request to transition to vr"
1722 " flinger.");
1723 mVrFlingerRequestsDisplay = false;
1724 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001725 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001726
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001727 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001728
Steven Thomas0123ac62018-07-12 11:32:34 -07001729 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001730 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001731
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001732 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001733
1734 // Clear out all the output layers from the composition engine for all
1735 // displays before destroying the hardware composer interface. This ensures
1736 // any HWC layers are destroyed through that interface before it becomes
1737 // invalid.
1738 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001739 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001740 }
1741
Steven Thomas0123ac62018-07-12 11:32:34 -07001742 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1743 // called below. Clear the reference now so we don't accidentally use it
1744 // later.
1745 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001746
Steven Thomasb02664d2017-07-26 18:48:28 -07001747 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001748 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001749 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001750
Steven Thomasb02664d2017-07-26 18:48:28 -07001751 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001752 // Delete the current instance before creating the new one
1753 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1754 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1755 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001756 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001757
Lloyd Pique441d5042018-10-18 16:49:51 -07001758 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001759 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001760
1761 if (vrFlingerRequestsDisplay) {
1762 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001763 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001764
1765 mVisibleRegionsDirty = true;
1766 invalidateHwcGeometry();
1767
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001768 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001769 display = getDefaultDisplayDeviceLocked();
1770 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001771 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001772
Steven Thomasb02664d2017-07-26 18:48:28 -07001773 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001774 const nsecs_t vsyncPeriod = getVsyncPeriod();
1775 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001776
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001777 // The present fences returned from vr_hwc are not an accurate
1778 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001779 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001780
Steven Thomasb02664d2017-07-26 18:48:28 -07001781 // Use phase of 0 since phase is not known.
1782 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001783 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001784 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001785
Ana Krulecc2870422019-01-29 19:00:58 -08001786 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001787
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001788 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001789 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001790}
1791
Alec Mouri6d414b52020-03-17 11:18:05 -07001792sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001793 // We are storing the last 2 present fences. If sf's phase offset is to be
1794 // woken up before the actual vsync but targeting the next vsync, we need to check
1795 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001796 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1797 : mPreviousPresentFences[1];
1798}
1799
1800bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1801 ATRACE_CALL();
1802 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001803
Ady Abraham11579302019-09-19 12:35:58 -07001804 if (fence == Fence::NO_FENCE) {
1805 return false;
1806 }
1807
1808 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1809 fence->wait(graceTimeMs);
1810 }
1811
1812 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001813}
1814
Alec Mouri6d414b52020-03-17 11:18:05 -07001815nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1816 const sp<Fence>& fence = previousFrameFence();
1817
1818 if (fence == Fence::NO_FENCE) {
1819 return Fence::SIGNAL_TIME_INVALID;
1820 }
1821
1822 return fence->getSignalTime();
1823}
1824
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001825void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001826 DisplayStatInfo stats;
1827 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001828 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001829 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001830 mExpectedPresentTime.store(
1831 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001832}
1833
Dominik Laskowski22488f62019-03-28 09:53:04 -07001834void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001835 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001836 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001837 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001838 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001839 // calculate the expected present time once and use the cached
1840 // value throughout this frame to make sure all layers are
1841 // seeing this same value.
Alec Mouri6d414b52020-03-17 11:18:05 -07001842 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001843 populateExpectedPresentTime();
1844
Ady Abraham11579302019-09-19 12:35:58 -07001845 // When Backpressure propagation is enabled we want to give a small grace period
1846 // for the present fence to fire instead of just giving up on this frame to handle cases
1847 // where present fence is just about to get signaled.
1848 const int graceTimeForPresentFenceMs =
1849 (mPropagateBackpressure &&
1850 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1851 ? 1
1852 : 0;
Alec Mouri6d414b52020-03-17 11:18:05 -07001853
1854 // Pending frames may trigger backpressure propagation.
1855 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1856 previousFramePending(
1857 graceTimeForPresentFenceMs)};
1858
1859 // Frame missed counts for metrics tracking.
1860 // A frame is missed if the prior frame is still pending. If no longer pending,
1861 // then we still count the frame as missed if the predicted present time
1862 // was further in the past than when the fence actually fired.
1863
1864 // Add some slop to correct for drift. This should generally be
1865 // smaller than a typical frame duration, but should not be so small
1866 // that it reports reasonable drift as a missed frame.
1867 DisplayStatInfo stats;
1868 mScheduler->getDisplayStatInfo(&stats);
1869 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1870 const nsecs_t previousPresentTime = previousFramePresentTime();
1871 const TracedOrdinal<bool> frameMissed =
1872 {"PrevFrameMissed",
1873 framePending ||
1874 (previousPresentTime >= 0 &&
1875 (lastExpectedPresentTime < previousPresentTime - frameMissedSlop))};
1876 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001877 mHadDeviceComposition && frameMissed};
Alec Mouri6d414b52020-03-17 11:18:05 -07001878 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001879 mHadClientComposition && frameMissed};
1880
Alec Mouricc0fc602019-02-26 21:45:19 -08001881 if (frameMissed) {
1882 mFrameMissedCount++;
1883 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001884 if (mMissedFrameJankCount == 0) {
1885 mMissedFrameJankStart = systemTime();
1886 }
1887 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001888 }
1889
Alec Mouri40189b02019-03-05 15:07:54 -08001890 if (hwcFrameMissed) {
1891 mHwcFrameMissedCount++;
1892 }
1893
1894 if (gpuFrameMissed) {
1895 mGpuFrameMissedCount++;
1896 }
1897
Ady Abraham27cbed72020-04-10 12:56:59 -07001898 // If we are in the middle of a config change and the fence hasn't
1899 // fired yet just wait for the next invalidate
1900 if (mSetActiveConfigPending) {
1901 if (framePending) {
1902 mEventQueue->invalidate();
1903 break;
1904 }
1905
1906 // We received the present fence from the HWC, so we assume it successfully updated
1907 // the config, hence we update SF.
1908 mSetActiveConfigPending = false;
1909 setActiveConfigInternal();
1910 }
1911
Alec Mouri6d414b52020-03-17 11:18:05 -07001912 if (framePending && mPropagateBackpressure) {
Ady Abrahamadb9a992019-09-19 21:21:55 +00001913 if ((hwcFrameMissed && !gpuFrameMissed) ||
1914 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001915 signalLayerUpdate();
1916 break;
1917 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001918 }
Dan Stoza50182882016-07-08 12:02:20 -07001919
Alec Mouri989ddbe2020-02-06 09:26:19 -08001920 // Our jank window is always at least 100ms since we missed a
1921 // frame...
1922 static constexpr nsecs_t kMinJankyDuration =
1923 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1924 // ...but if it's larger than 1s then we missed the trace cutoff.
1925 static constexpr nsecs_t kMaxJankyDuration =
1926 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1927 // If we're in a user build then don't push any atoms
1928 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1929 const auto displayDevice = getDefaultDisplayDeviceLocked();
1930 // Only report jank when the display is on, as displays in DOZE
1931 // power mode may operate at a different frame rate than is
1932 // reported in their config, which causes noticeable (but less
1933 // severe) jank.
1934 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1935 const nsecs_t currentTime = systemTime();
1936 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1937 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1938 ATRACE_NAME("Jank detected");
1939 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1940 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1941 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1942 jankyDurationMillis, mMissedFrameJankCount);
1943 }
1944
1945 // We either reported a jank event or we missed the trace
1946 // window, so clear counters here.
1947 if (jankDuration > kMinJankyDuration) {
1948 mMissedFrameJankCount = 0;
1949 mMissedFrameJankStart = 0;
1950 }
1951 }
1952 }
1953
Steven Thomas050b2c82017-03-06 11:45:16 -08001954 // Now that we're going to make it to the handleMessageTransaction()
1955 // call below it's safe to call updateVrFlinger(), which will
1956 // potentially trigger a display handoff.
1957 updateVrFlinger();
1958
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001959 if (mTracingEnabledChanged) {
1960 mTracingEnabled = mTracing.isEnabled();
1961 mTracingEnabledChanged = false;
1962 }
1963
Vishnu Nair60db8c02020-04-02 11:55:16 -07001964 bool refreshNeeded;
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001965 {
1966 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1967
Vishnu Nair60db8c02020-04-02 11:55:16 -07001968 refreshNeeded = handleMessageTransaction();
1969 refreshNeeded |= handleMessageInvalidate();
1970 if (mTracingEnabled) {
1971 mAddCompositionStateToTrace =
1972 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1973 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1974 mTracing.notifyLocked("visibleRegionsDirty");
1975 }
1976 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07001977 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001978
Ana Krulecc84d09b2019-11-02 23:10:29 +01001979 // Layers need to get updated (in the previous line) before we can use them for
1980 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001981 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1982 // and may eventually call to ~Layer() if it holds the last reference
1983 {
1984 Mutex::Autolock _l(mStateLock);
1985 mScheduler->chooseRefreshRateForContent();
1986 }
1987
Ady Abraham27cbed72020-04-10 12:56:59 -07001988 performSetActiveConfig();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001989
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001990 updateCursorAsync();
1991 updateInputFlinger();
1992
Dan Stoza58784442014-12-02 16:58:17 -08001993 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001994 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001995 // Signal a refresh if a transaction modified the window state,
1996 // a new buffer was latched, or if HWC has requested a full
1997 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001998 if (mFrameStartTime <= 0) {
1999 // We should only use the time of the first invalidate
2000 // message that signals a refresh as the beginning of the
2001 // frame. Otherwise the real frame time will be
2002 // underestimated.
2003 mFrameStartTime = frameStart;
2004 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08002005 signalRefresh();
2006 }
2007 break;
2008 }
2009 case MessageQueue::REFRESH: {
2010 handleMessageRefresh();
2011 break;
2012 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002013 }
2014}
2015
Dan Stoza6b9454d2014-11-07 16:00:59 -08002016bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08002017 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002018 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002019
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002020 bool flushedATransaction = flushTransactionQueues();
2021
2022 bool runHandleTransaction = transactionFlags &&
2023 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
2024
2025 if (runHandleTransaction) {
2026 handleTransaction(eTransactionMask);
2027 } else {
2028 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002029 }
2030
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002031 if (transactionFlushNeeded()) {
2032 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002033 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002034
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002035 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002036}
2037
Mathias Agopian4fec8732012-06-29 14:12:52 -07002038void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002039 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002040
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002041 mRefreshPending = false;
2042
Lloyd Piqueab039b52019-02-13 14:22:42 -08002043 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002044 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002045 for (const auto& [_, display] : mDisplays) {
2046 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2047 }
2048 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002049 if (auto layerFE = layer->getCompositionEngineLayerFE())
2050 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002051 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002052 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2053 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002054 if (auto layerFE = layer->getCompositionEngineLayerFE())
2055 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002056 }
2057
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002058 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002059 refreshArgs.outputColorSetting = useColorManagement
2060 ? mDisplayColorSetting
2061 : compositionengine::OutputColorSetting::kUnmanaged;
2062 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2063 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002064
2065 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2066 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002067 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002068
2069 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2070 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2071 mDrawingState.colorMatrixChanged = false;
2072 }
2073
2074 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2075
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002076 if (mDebugRegion != 0) {
2077 refreshArgs.devOptFlashDirtyRegionsDelay =
2078 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2079 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002080
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002081 mGeometryInvalid = false;
2082
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002083 // Store the present time just before calling to the composition engine so we could notify
2084 // the scheduler.
2085 const auto presentTime = systemTime();
2086
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002087 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002088 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2089 // Reset the frame start time now that we've recorded this frame.
2090 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002091
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002092 mScheduler->onDisplayRefreshed(presentTime);
2093
David Sodmanfa9b2af2017-12-24 13:28:59 -08002094 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002095 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002096
Alec Mouri8f7a0102020-04-15 12:11:10 -07002097 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2098
Lloyd Pique66d68602019-02-13 14:23:31 -08002099 mHadClientComposition =
2100 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2101 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002102 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2103 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002104 });
2105 mHadDeviceComposition =
2106 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2107 auto& displayDevice = tokenDisplayPair.second;
2108 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2109 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002110 mReusedClientComposition =
2111 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2112 auto& displayDevice = tokenDisplayPair.second;
2113 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2114 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002115
Alec Mouri8f7a0102020-04-15 12:11:10 -07002116 // Only report a strategy change if we move in and out of composition with hw overlays
2117 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2118 mTimeStats->incrementCompositionStrategyChanges();
2119 }
2120
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002121 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002122
David Sodman7e4ae112018-02-09 15:02:28 -08002123 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002124 if (mVisibleRegionsDirty) {
2125 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002126 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002127 mTracing.notify("visibleRegionsDirty");
2128 }
2129 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002130
2131 if (mCompositionEngine->needsAnotherUpdate()) {
2132 signalLayerUpdate();
2133 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002134}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002135
David Sodmanfa9b2af2017-12-24 13:28:59 -08002136
2137bool SurfaceFlinger::handleMessageInvalidate() {
2138 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002139 bool refreshNeeded = handlePageFlip();
2140
Vishnu Nair4351ad52019-02-11 14:13:02 -08002141 if (mVisibleRegionsDirty) {
2142 computeLayerBounds();
2143 }
2144
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002145 for (auto& layer : mLayersPendingRefresh) {
2146 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002147 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002148 invalidateLayerStack(layer, visibleReg);
2149 }
2150 mLayersPendingRefresh.clear();
2151 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002152}
2153
Ana Krulece588e312018-09-18 12:32:24 -07002154void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2155 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002156 // Update queue of past composite+present times and determine the
2157 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002158 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002159 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002160 while (!getBE().mCompositePresentTimes.empty()) {
2161 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002162 // Cached values should have been updated before calling this method,
2163 // which helps avoid duplicate syscalls.
2164 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2165 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2166 break;
2167 }
2168 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002169 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002170 }
2171
2172 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002173 while (getBE().mCompositePresentTimes.size() > 16) {
2174 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002175 }
2176
Ana Krulece588e312018-09-18 12:32:24 -07002177 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002178}
2179
Ana Krulece588e312018-09-18 12:32:24 -07002180void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2181 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002182 // Integer division and modulo round toward 0 not -inf, so we need to
2183 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002184 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2185 ? (stats.vsyncPeriod -
2186 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2187 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002188
Ady Abraham9e16a482019-12-03 17:19:41 -08002189 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002190 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002191 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002192 }
2193
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002194 // Snap the latency to a value that removes scheduling jitter from the
2195 // composition and present times, which often have >1ms of jitter.
2196 // Reducing jitter is important if an app attempts to extrapolate
2197 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002198 // Snapping also allows an app to precisely calculate
2199 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002200 nsecs_t bias = stats.vsyncPeriod / 2;
2201 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2202 nsecs_t snappedCompositeToPresentLatency =
2203 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002204
David Sodman99974d22017-11-28 12:04:33 -08002205 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002206 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2207 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002208 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002209}
2210
David Sodman2b406362017-12-15 13:33:47 -08002211void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002212{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002213 ATRACE_CALL();
2214 ALOGV("postComposition");
2215
Brian Andersonf6386862016-10-31 16:34:13 -07002216 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002217 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002218 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002219 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002220 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002221 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002222
David Sodman73beded2017-11-15 11:56:06 -08002223 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002224 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002225 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002226 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002227 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2228 ->getRenderSurface()
2229 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002230 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002231 } else {
2232 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2233 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002234
David Sodman73beded2017-11-15 11:56:06 -08002235 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002236 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2237 mPreviousPresentFences[0] = displayDevice
2238 ? getHwComposer().getPresentFence(*displayDevice->getId())
2239 : Fence::NO_FENCE;
2240 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002241 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002242
Ana Krulece588e312018-09-18 12:32:24 -07002243 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002244 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002245
Lloyd Piqueab039b52019-02-13 14:22:42 -08002246 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2247 // be sampled a little later than when we started doing work for this frame,
2248 // but that should be okay since updateCompositorTiming has snapping logic.
2249 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2250 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002251 CompositorTiming compositorTiming;
2252 {
David Sodman99974d22017-11-28 12:04:33 -08002253 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2254 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002255 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002256
Edgar Arriaga844fa672020-01-16 14:21:42 -08002257 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002258 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2259 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002260 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002261 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002262 }
Robert Carr2047fae2016-11-28 14:09:09 -08002263 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002264
Valerie Hau4b678442020-04-14 10:50:42 -07002265 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2266 mTransactionCompletedThread.sendCallbacks();
2267
Ady Abraham92fa2f42020-02-11 15:33:56 -08002268 if (displayDevice && displayDevice->isPrimary() &&
2269 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002270 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002271 }
2272
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002273 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002274 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2275 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002276 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002277 }
2278 }
2279
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002280 if (mAnimCompositionPending) {
2281 mAnimCompositionPending = false;
2282
Brian Anderson4e606e32017-03-16 15:34:57 -07002283 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002284 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002285 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002286 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002287 // The HWC doesn't support present fences, so use the refresh
2288 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002289 const nsecs_t presentTime =
2290 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002291 mAnimFrameTracker.setActualPresentTime(presentTime);
2292 }
2293 mAnimFrameTracker.advanceFrame();
2294 }
Dan Stozab90cf072015-03-05 11:05:59 -08002295
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002296 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002297 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002298 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002299 }
2300
Vishnu Nair9b079a22020-01-21 14:36:08 -08002301 if (mReusedClientComposition) {
2302 mTimeStats->incrementClientCompositionReusedFrames();
2303 }
2304
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002305 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002306
Alec Mouri717bcb62020-02-10 17:07:19 -08002307 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2308 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2309 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2310
Lloyd Pique32cbe282018-10-19 13:09:22 -07002311 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2312 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002313 return;
2314 }
2315
2316 nsecs_t currentTime = systemTime();
2317 if (mHasPoweredOff) {
2318 mHasPoweredOff = false;
2319 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002320 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002321 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002322 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2323 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002324 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002325 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002326 }
David Sodman4a36e932017-11-07 14:29:47 -08002327 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002328 }
David Sodman4a36e932017-11-07 14:29:47 -08002329 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002330
2331 {
2332 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002333 if (mTexturePool.size() < mTexturePoolSize) {
2334 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002335 const size_t offset = mTexturePool.size();
2336 mTexturePool.resize(mTexturePoolSize);
2337 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2338 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002339 } else if (mTexturePool.size() > mTexturePoolSize) {
2340 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2341 const size_t offset = mTexturePoolSize;
2342 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2343 mTexturePool.resize(mTexturePoolSize);
2344 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002345 }
2346 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002347
Kevin DuBois413287f2019-02-25 08:46:47 -08002348 if (mLumaSampling && mRegionSamplingThread) {
2349 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002350 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002351
2352 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2353 // side-effect of getTotalSize(), so we check that again here
2354 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002355 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002356 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2357 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002358}
2359
Vishnu Nair4351ad52019-02-11 14:13:02 -08002360void SurfaceFlinger::computeLayerBounds() {
2361 for (const auto& pair : mDisplays) {
2362 const auto& displayDevice = pair.second;
2363 const auto display = displayDevice->getCompositionDisplay();
2364 for (const auto& layer : mDrawingState.layersSortedByZ) {
2365 // only consider the layers on the given layer stack
2366 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002367 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002368 }
2369
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002370 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2371 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002372 }
2373 }
2374}
2375
David Sodmanfa9b2af2017-12-24 13:28:59 -08002376void SurfaceFlinger::postFrame()
2377{
2378 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002379 const auto display = getDefaultDisplayDeviceLocked();
2380 if (display && getHwComposer().isConnected(*display->getId())) {
2381 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002382 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2383 logFrameStats();
2384 }
2385 }
2386}
2387
Mathias Agopian87baae12012-07-31 12:38:26 -07002388void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002389{
Mathias Agopian841cde52012-03-01 15:44:37 -08002390 ATRACE_CALL();
2391
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002392 // here we keep a copy of the drawing state (that is the state that's
2393 // going to be overwritten by handleTransactionLocked()) outside of
2394 // mStateLock so that the side-effects of the State assignment
2395 // don't happen with mStateLock held (which can cause deadlocks).
2396 State drawingState(mDrawingState);
2397
Mathias Agopianca4d3602011-05-19 15:38:14 -07002398 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002399 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002400
Mathias Agopianca4d3602011-05-19 15:38:14 -07002401 // Here we're guaranteed that some transaction flags are set
2402 // so we can call handleTransactionLocked() unconditionally.
2403 // We call getTransactionFlags(), which will also clear the flags,
2404 // with mStateLock held to guarantee that mCurrentState won't change
2405 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002406
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002407 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002408 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002409 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002410
Mathias Agopianca4d3602011-05-19 15:38:14 -07002411 mDebugInTransaction = 0;
2412 invalidateHwcGeometry();
2413 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002414}
2415
Lloyd Piqueba04e622017-12-14 17:11:26 -08002416void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2417 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002418 const std::optional<DisplayIdentificationInfo> info =
2419 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002420
Dominik Laskowski075d3172018-05-24 15:50:06 -07002421 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002422 continue;
2423 }
2424
Dominik Laskowski55c85402020-01-21 16:25:47 -08002425 const DisplayId displayId = info->id;
2426 const auto it = mPhysicalDisplayTokens.find(displayId);
2427
Lloyd Piqueba04e622017-12-14 17:11:26 -08002428 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002429 if (it == mPhysicalDisplayTokens.end()) {
2430 ALOGV("Creating display %s", to_string(displayId).c_str());
2431
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002432 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002433 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002434 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002435
Dominik Laskowski075d3172018-05-24 15:50:06 -07002436 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002437 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2438 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002439 state.isSecure = true; // All physical displays are currently considered secure.
2440 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002441
2442 sp<IBinder> token = new BBinder();
2443 mCurrentState.displays.add(token, state);
2444 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2445
Dominik Laskowski075d3172018-05-24 15:50:06 -07002446 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002447 } else {
2448 ALOGV("Recreating display %s", to_string(displayId).c_str());
2449
2450 const auto token = it->second;
2451 auto& state = mCurrentState.displays.editValueFor(token);
2452 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002453 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002454 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002455 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002456
Dominik Laskowski55c85402020-01-21 16:25:47 -08002457 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 if (index >= 0) {
2459 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2460 mInterceptor->saveDisplayDeletion(state.sequenceId);
2461 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002462 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002463 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002464 }
2465
2466 processDisplayChangesLocked();
2467 }
2468
2469 mPendingHotplugEvents.clear();
2470}
2471
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002472void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002473 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2474 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002475}
2476
Lloyd Pique99d3da52018-01-22 17:48:03 -08002477sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002478 const wp<IBinder>& displayToken,
2479 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002480 const DisplayDeviceState& state,
2481 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002482 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002483 auto displayId = compositionDisplay->getDisplayId();
2484 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002485 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002486 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002487 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002488 creationArgs.hasWideColorGamut = false;
2489 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002490
Dominik Laskowski55c85402020-01-21 16:25:47 -08002491 if (const auto& physical = state.physical) {
2492 creationArgs.connectionType = physical->type;
2493 }
2494
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002495 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 creationArgs.isPrimary = isInternalDisplay;
2497
2498 if (useColorManagement && displayId) {
2499 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002500 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002501 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002502 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002503 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002504
Dominik Laskowski7e045462018-05-30 13:02:02 -07002505 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002506 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002507 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002508 }
tangrobin6753a022018-08-10 10:58:54 +08002509 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002510
Dominik Laskowski075d3172018-05-24 15:50:06 -07002511 if (displayId) {
2512 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002513 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002514 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002515 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002516
Lloyd Pique90c115d2018-09-18 21:39:42 -07002517 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002518 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002519 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002520
Lloyd Pique99d3da52018-01-22 17:48:03 -08002521 // Make sure that composition can never be stalled by a virtual display
2522 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002523 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002524 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002525 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2526 }
2527
Dominik Laskowski718f9602019-11-09 20:01:35 -08002528 creationArgs.physicalOrientation =
2529 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002530
Lloyd Pique99d3da52018-01-22 17:48:03 -08002531 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002532 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002533
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002534 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002535
2536 if (maxFrameBufferAcquiredBuffers >= 3) {
2537 nativeWindowSurface->preallocateBuffers();
2538 }
2539
2540 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002541 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002542 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002543 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002544 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002545 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002546 display->getCompositionDisplay()->setColorProfile(
2547 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2548 RenderIntent::COLORIMETRIC,
2549 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002550 if (!state.isVirtual()) {
2551 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002552 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2553 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002554 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002556 display->setLayerStack(state.layerStack);
2557 display->setProjection(state.orientation, state.viewport, state.frame);
2558 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002560 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002561}
2562
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002563void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2564 const DisplayDeviceState& state) {
2565 int width = 0;
2566 int height = 0;
2567 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2568 if (state.physical) {
2569 const auto& activeConfig =
2570 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2571 width = activeConfig->getWidth();
2572 height = activeConfig->getHeight();
2573 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2574 } else if (state.surface != nullptr) {
2575 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2576 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2577 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2578 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2579 int intPixelFormat;
2580 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2581 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2582 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2583 } else {
2584 // Virtual displays without a surface are dormant:
2585 // they have external state (layer stack, projection,
2586 // etc.) but no internal state (i.e. a DisplayDevice).
2587 return;
2588 }
2589
2590 compositionengine::DisplayCreationArgsBuilder builder;
2591 if (const auto& physical = state.physical) {
2592 builder.setPhysical({physical->id, physical->type});
2593 }
2594 builder.setPixels(ui::Size(width, height));
2595 builder.setPixelFormat(pixelFormat);
2596 builder.setIsSecure(state.isSecure);
2597 builder.setLayerStackId(state.layerStack);
2598 builder.setPowerAdvisor(&mPowerAdvisor);
2599 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2600 builder.setName(state.displayName);
2601 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2602
2603 sp<compositionengine::DisplaySurface> displaySurface;
2604 sp<IGraphicBufferProducer> producer;
2605 sp<IGraphicBufferProducer> bqProducer;
2606 sp<IGraphicBufferConsumer> bqConsumer;
2607 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2608
2609 std::optional<DisplayId> displayId = compositionDisplay->getId();
2610
2611 if (state.isVirtual()) {
2612 sp<VirtualDisplaySurface> vds =
2613 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2614 bqConsumer, state.displayName);
2615
2616 displaySurface = vds;
2617 producer = vds;
2618 } else {
2619 ALOGE_IF(state.surface != nullptr,
2620 "adding a supported display, but rendering "
2621 "surface is provided (%p), ignoring it",
2622 state.surface.get());
2623
2624 LOG_ALWAYS_FATAL_IF(!displayId);
2625 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2626 maxGraphicsWidth, maxGraphicsHeight);
2627 producer = bqProducer;
2628 }
2629
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002630 LOG_FATAL_IF(!displaySurface);
2631 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2632 displaySurface, producer);
2633 mDisplays.emplace(displayToken, display);
2634 if (!state.isVirtual()) {
2635 LOG_FATAL_IF(!displayId);
2636 dispatchDisplayHotplugEvent(displayId->value, true);
2637 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002638
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002639 if (display->isPrimary()) {
2640 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002641 }
2642}
2643
2644void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2645 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2646 // Save display ID before disconnecting.
2647 const auto displayId = display->getId();
2648 display->disconnect();
2649
2650 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002651 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002652 dispatchDisplayHotplugEvent(displayId->value, false);
2653 }
2654 }
2655
2656 mDisplays.erase(displayToken);
2657}
2658
2659void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2660 const DisplayDeviceState& currentState,
2661 const DisplayDeviceState& drawingState) {
2662 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2663 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002664 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002665 // changing the surface is like destroying and recreating the DisplayDevice
2666 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2667 display->disconnect();
2668 }
2669 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002670 if (const auto& physical = currentState.physical) {
2671 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2672 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002673 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002674 if (currentState.physical) {
2675 initializeDisplays();
2676 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002677 return;
2678 }
2679
2680 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2681 if (currentState.layerStack != drawingState.layerStack) {
2682 display->setLayerStack(currentState.layerStack);
2683 }
2684 if ((currentState.orientation != drawingState.orientation) ||
2685 (currentState.viewport != drawingState.viewport) ||
2686 (currentState.frame != drawingState.frame)) {
2687 display->setProjection(currentState.orientation, currentState.viewport,
2688 currentState.frame);
2689 }
2690 if (currentState.width != drawingState.width ||
2691 currentState.height != drawingState.height) {
2692 display->setDisplaySize(currentState.width, currentState.height);
2693 if (display->isPrimary()) {
2694 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2695 }
2696 }
2697 }
2698}
2699
Lloyd Pique347200f2017-12-14 17:00:15 -08002700void SurfaceFlinger::processDisplayChangesLocked() {
2701 // here we take advantage of Vector's copy-on-write semantics to
2702 // improve performance by skipping the transaction entirely when
2703 // know that the lists are identical
2704 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2705 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2706 if (!curr.isIdenticalTo(draw)) {
2707 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002708
2709 // find the displays that were removed
2710 // (ie: in drawing state but not in current state)
2711 // also handle displays that changed
2712 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002713 for (size_t i = 0; i < draw.size(); i++) {
2714 const wp<IBinder>& displayToken = draw.keyAt(i);
2715 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 if (j < 0) {
2717 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002718 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002719 } else {
2720 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002721 const DisplayDeviceState& currentState = curr[j];
2722 const DisplayDeviceState& drawingState = draw[i];
2723 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002724 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 }
2726
2727 // find displays that were added
2728 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002729 for (size_t i = 0; i < curr.size(); i++) {
2730 const wp<IBinder>& displayToken = curr.keyAt(i);
2731 if (draw.indexOfKey(displayToken) < 0) {
2732 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002733 }
2734 }
2735 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002736
2737 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002738}
2739
Mathias Agopian87baae12012-07-31 12:38:26 -07002740void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002741{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002742 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2743
Dan Stoza7dde5992015-05-22 09:51:44 -07002744 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002745 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002746 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002747 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002748
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002749 /*
2750 * Traversal of the children
2751 * (perform the transaction for each of them if needed)
2752 */
2753
Marissa Wall06255332019-03-27 13:48:27 -07002754 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002755 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002757 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758
2759 const uint32_t flags = layer->doTransaction(0);
2760 if (flags & Layer::eVisibleRegion)
2761 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002762
2763 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002764 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002765 }
Robert Carr2047fae2016-11-28 14:09:09 -08002766 });
Marissa Wall06255332019-03-27 13:48:27 -07002767 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 }
2769
2770 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002771 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772 */
2773
Mathias Agopiane57f2922012-08-09 16:29:12 -07002774 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002776 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002777 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002779 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002780 // The transform hint might have changed for some layers
2781 // (either because a display has changed, or because a layer
2782 // as changed).
2783 //
2784 // Walk through all the layers in currentLayers,
2785 // and update their transform hint.
2786 //
2787 // If a layer is visible only on a single display, then that
2788 // display is used to calculate the hint, otherwise we use the
2789 // default display.
2790 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002791 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002792 // the hint is set before we acquire a buffer from the surface texture.
2793 //
2794 // NOTE: layer transactions have taken place already, so we use their
2795 // drawing state. However, SurfaceFlinger's own transaction has not
2796 // happened yet, so we must use the current state layer list
2797 // (soon to become the drawing state list).
2798 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002799 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002800 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002801 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002802 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002803 // NOTE: we rely on the fact that layers are sorted by
2804 // layerStack first (so we don't have to traverse the list
2805 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002806 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002807 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002808 currentlayerStack = layerStack;
2809 // figure out if this layerstack is mirrored
2810 // (more than one display) if so, pick the default display,
2811 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002812 hintDisplay = nullptr;
2813 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002814 if (display->getCompositionDisplay()
2815 ->belongsInOutput(layer->getLayerStack(),
2816 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002817 if (hintDisplay) {
2818 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002819 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002820 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002821 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002822 }
2823 }
2824 }
2825 }
Chet Haase91d25932013-04-11 15:24:55 -07002826
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002827 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002828 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2829 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002830
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002831 // could be null when this layer is using a layerStack
2832 // that is not visible on any display. Also can occur at
2833 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002834 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002835 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002836
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002837 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002838 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002839 if (hintDisplay) {
2840 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002841 }
Robert Carr2047fae2016-11-28 14:09:09 -08002842
2843 first = false;
2844 });
Mathias Agopian84300952012-11-21 16:02:13 -08002845 }
2846
2847
Mathias Agopian3559b072012-08-15 13:46:03 -07002848 /*
2849 * Perform our own transaction if needed
2850 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002851
2852 if (mLayersAdded) {
2853 mLayersAdded = false;
2854 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002855 mVisibleRegionsDirty = true;
2856 }
2857
2858 // some layers might have been removed, so
2859 // we need to update the regions they're exposing.
2860 if (mLayersRemoved) {
2861 mLayersRemoved = false;
2862 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002863 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002864 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002865 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002866 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002867 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002868 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002869 }
Robert Carr2047fae2016-11-28 14:09:09 -08002870 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 }
2872
Vishnu Nairec0ab382019-02-13 15:32:56 -08002873 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002875}
2876
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002877void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002878 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002879 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002880 return;
2881 }
2882
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002883 if (mVisibleRegionsDirty || mInputInfoChanged) {
2884 mInputInfoChanged = false;
2885 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002886 } else if (mInputWindowCommands.syncInputWindows) {
2887 // If the caller requested to sync input windows, but there are no
2888 // changes to input windows, notify immediately.
2889 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002890 }
2891
Arthur Hung6cbb9752019-09-05 16:38:18 +08002892 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002893}
2894
2895void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002896 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002897
Robert Carra1257842020-01-31 13:48:28 -08002898 // We use a simple caching algorithm here. mInputDirty begins as true,
2899 // after we call setInputWindows we set it to false, so
2900 // in the future we wont call it again.. We set input dirty to true again
2901 // when any layer that hasInput() has a transaction performed on it
2902 // or when any parent or relative parent of such a layer has a transaction
2903 // performed on it. Not all of these transactions will really result in
2904 // input changes but all input changes will spring from these transactions
2905 // so the cache is safe but not optimal. It seems like it might be annoyingly
2906 // costly to cache and comapre the actual InputWindowHandle vector though.
Robert Carr0854b992020-03-11 12:09:42 -07002907 if (!mInputDirty && !mInputWindowCommands.syncInputWindows) {
Robert Carra1257842020-01-31 13:48:28 -08002908 return;
2909 }
2910
Robert Carr720e5062018-07-30 17:45:14 -07002911 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2912 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002913 // When calculating the screen bounds we ignore the transparent region since it may
2914 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002915 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002916 }
2917 });
chaviw291d88a2019-02-14 10:33:58 -08002918
2919 mInputFlinger->setInputWindows(inputHandles,
2920 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2921 : nullptr);
Robert Carra1257842020-01-31 13:48:28 -08002922
2923 mInputDirty = false;
Robert Carr720e5062018-07-30 17:45:14 -07002924}
2925
Vishnu Nairec0ab382019-02-13 15:32:56 -08002926void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002927 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002928 mPendingInputWindowCommands.clear();
2929}
2930
Riley Andrews03414a12014-07-01 14:22:59 -07002931void SurfaceFlinger::updateCursorAsync()
2932{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002933 compositionengine::CompositionRefreshArgs refreshArgs;
2934 for (const auto& [_, display] : mDisplays) {
2935 if (display->getId()) {
2936 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002937 }
2938 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002939
2940 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002941}
2942
Ady Abraham2139f732019-11-13 18:56:40 -08002943void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002944 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2945 // If this is called from the main thread mStateLock must be locked before
2946 // Currently the only way to call this function from the main thread is from
2947 // Sheduler::chooseRefreshRateForContent
2948
2949 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002950 changeRefreshRateLocked(refreshRate, event);
2951}
2952
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002953void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2954 if (mScheduler) {
2955 // In practice it's not allowed to hotplug in/out the primary display once it's been
2956 // connected during startup, but some tests do it, so just warn and return.
2957 ALOGW("Can't re-init scheduler");
2958 return;
2959 }
2960
Ady Abraham2139f732019-11-13 18:56:40 -08002961 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002962 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002963 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002964 primaryDisplayId),
2965 currentConfig);
2966 mRefreshRateStats =
2967 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2968 currentConfig, HWC_POWER_MODE_OFF);
2969 mRefreshRateStats->setConfigMode(currentConfig);
2970
Ady Abraham9e16a482019-12-03 17:19:41 -08002971 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2972
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002973 // start the EventThread
2974 mScheduler =
2975 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002976 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002977 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002978 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002979 impl::EventThread::InterceptVSyncsCallback());
2980 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002981 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002982 [this](nsecs_t timestamp) {
2983 mInterceptor->saveVSyncEvent(timestamp);
2984 });
2985
2986 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2987 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002988 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002989
2990 mRegionSamplingThread =
2991 new RegionSamplingThread(*this, *mScheduler,
2992 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002993 // Dispatch a config change request for the primary display on scheduler
2994 // initialization, so that the EventThreads always contain a reference to a
2995 // prior configuration.
2996 //
2997 // This is a bit hacky, but this avoids a back-pointer into the main SF
2998 // classes from EventThread, and there should be no run-time binder cost
2999 // anyway since there are no connected apps at this point.
3000 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07003001 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Alec Mouri60aee1c2019-10-28 16:18:59 -07003002 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
3003 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003004}
3005
Mathias Agopian4fec8732012-06-29 14:12:52 -07003006void SurfaceFlinger::commitTransaction()
3007{
Vishnu Nair60db8c02020-04-02 11:55:16 -07003008 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003009 mTransactionPending = false;
3010 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003011 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003012}
3013
Lloyd Pique58e24a32019-08-01 15:50:14 -07003014void SurfaceFlinger::commitTransactionLocked() {
3015 if (!mLayersPendingRemoval.isEmpty()) {
3016 // Notify removed layers now that they can't be drawn from
3017 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003018 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003019
3020 // Ensure any buffers set to display on any children are released.
3021 if (l->isRemovedFromCurrentState()) {
3022 l->latchAndReleaseBuffer();
3023 }
3024
3025 // If the layer has been removed and has no parent, then it will not be reachable
3026 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3027 // ensure we can copy its current to drawing state.
3028 if (!l->getParent()) {
3029 mOffscreenLayers.emplace(l.get());
3030 }
3031 }
3032 mLayersPendingRemoval.clear();
3033 }
3034
3035 // If this transaction is part of a window animation then the next frame
3036 // we composite should be considered an animation as well.
3037 mAnimCompositionPending = mAnimTransactionPending;
3038
3039 mDrawingState = mCurrentState;
3040 // clear the "changed" flags in current state
3041 mCurrentState.colorMatrixChanged = false;
3042
Edgar Arriaga844fa672020-01-16 14:21:42 -08003043 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003044 layer->commitChildList();
3045
3046 // If the layer can be reached when traversing mDrawingState, then the layer is no
3047 // longer offscreen. Remove the layer from the offscreenLayer set.
3048 if (mOffscreenLayers.count(layer)) {
3049 mOffscreenLayers.erase(layer);
3050 }
3051 });
3052
3053 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003054 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003055}
3056
chaviw74d90ad2019-04-26 14:45:26 -07003057void SurfaceFlinger::commitOffscreenLayers() {
3058 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003059 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003060 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3061 if (!trFlags) return;
3062
3063 layer->doTransaction(0);
3064 layer->commitChildList();
3065 });
3066 }
3067}
3068
Chia-I Wuab0c3192017-08-01 11:29:00 -07003069void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003070 for (const auto& [token, displayDevice] : mDisplays) {
3071 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003072 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003073 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003074 }
3075 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003076}
3077
Dan Stoza6b9454d2014-11-07 16:00:59 -08003078bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003079{
Ady Abraham09bd3922019-04-08 10:44:56 -07003080 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003081 ALOGV("handlePageFlip");
3082
Brian Andersond6927fb2016-07-23 23:37:30 -07003083 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084
Mathias Agopian4fec8732012-06-29 14:12:52 -07003085 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003086 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003087 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003088
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003089 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3090
Eric Penner51c59cd2014-07-28 19:51:58 -07003091 // Store the set of layers that need updates. This set must not change as
3092 // buffers are being latched, as this could result in a deadlock.
3093 // Example: Two producers share the same command stream and:
3094 // 1.) Layer 0 is latched
3095 // 2.) Layer 0 gets a new frame
3096 // 2.) Layer 1 gets a new frame
3097 // 3.) Layer 1 is latched.
3098 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3099 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003100 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003101 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003102 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003103 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003104 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003105 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003106 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003107 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003108 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003109 } else {
3110 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003111 }
Robert Carr2047fae2016-11-28 14:09:09 -08003112 });
3113
chaviw49a108c2019-08-12 11:23:06 -07003114 // The client can continue submitting buffers for offscreen layers, but they will not
3115 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3116 // layers to ensure dequeueBuffer doesn't block indefinitely.
3117 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003118 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003119 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3120 }
3121
Lloyd Piquef2c79392018-12-20 16:23:33 -08003122 if (!mLayersWithQueuedFrames.empty()) {
3123 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3124 // writes to Layer current state. See also b/119481871
3125 Mutex::Autolock lock(mStateLock);
3126
3127 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003128 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003129 mLayersPendingRefresh.push_back(layer);
3130 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003131 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003132 if (layer->isBufferLatched()) {
3133 newDataLatched = true;
3134 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003135 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003136 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003137
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003138 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003139
3140 // If we will need to wake up at some time in the future to deal with a
3141 // queued frame that shouldn't be displayed during this vsync period, wake
3142 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003143 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003144 signalLayerUpdate();
3145 }
3146
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003147 // enter boot animation on first buffer latch
3148 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3149 ALOGI("Enter boot animation");
3150 mBootStage = BootStage::BOOTANIMATION;
3151 }
3152
Edgar Arriaga844fa672020-01-16 14:21:42 -08003153 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003154
Dan Stoza6b9454d2014-11-07 16:00:59 -08003155 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003156 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157}
3158
Mathias Agopianad456f92011-01-13 17:53:01 -08003159void SurfaceFlinger::invalidateHwcGeometry()
3160{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003161 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003162}
3163
Robert Carrc0df3122019-04-11 13:18:21 -07003164status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3165 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3166 const sp<IBinder>& parentHandle,
3167 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003168 // add this layer to the current state list
3169 {
3170 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003171 sp<Layer> parent;
3172 if (parentHandle != nullptr) {
3173 parent = fromHandle(parentHandle);
3174 if (parent == nullptr) {
3175 return NAME_NOT_FOUND;
3176 }
3177 } else {
3178 parent = parentLayer;
3179 }
3180
Ady Abraham0a525092020-03-03 12:51:24 -08003181 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003182 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003183 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003184 return NO_MEMORY;
3185 }
Robert Carrc0df3122019-04-11 13:18:21 -07003186
3187 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3188
Robert Carrb89ea9d2018-12-10 13:01:14 -08003189 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003190 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003191 } else if (parent == nullptr) {
3192 lbc->onRemovedFromCurrentState();
3193 } else if (parent->isRemovedFromCurrentState()) {
3194 parent->addChild(lbc);
3195 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003196 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003197 parent->addChild(lbc);
3198 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003199
Yiwei Zhang243b3782018-05-15 17:40:04 -07003200 if (gbc != nullptr) {
3201 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3202 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3203 mMaxGraphicBufferProducerListSize,
3204 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3205 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003206 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003207 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003208 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003209 }
3210
Mathias Agopian96f08192010-06-02 23:28:45 -07003211 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003212 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003213
Dan Stoza7d89d062015-04-30 13:29:25 -07003214 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003215}
3216
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003217uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003218 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003219}
3220
Mathias Agopian3f844832013-08-07 21:24:32 -07003221uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003222 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003223}
3224
Mathias Agopian3f844832013-08-07 21:24:32 -07003225uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003226 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003227}
3228
3229uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003230 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003231 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003232 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003234 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235 }
3236 return old;
3237}
3238
Marissa Wall713b63f2018-10-17 15:42:43 -07003239bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003240 // to prevent onHandleDestroyed from being called while the lock is held,
3241 // we must keep a copy of the transactions (specifically the composer
3242 // states) around outside the scope of the lock
3243 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003244 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003245 {
3246 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003247
Valerie Haufce31b82019-04-30 16:41:14 -07003248 auto it = mTransactionQueues.begin();
3249 while (it != mTransactionQueues.end()) {
3250 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003251
Valerie Haufce31b82019-04-30 16:41:14 -07003252 while (!transactionQueue.empty()) {
3253 const auto& transaction = transactionQueue.front();
3254 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003255 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003256 transaction.states)) {
3257 setTransactionFlags(eTransactionFlushNeeded);
3258 break;
3259 }
3260 transactions.push_back(transaction);
3261 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3262 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003263 transaction.buffer, transaction.postTime,
3264 transaction.privileged, transaction.hasListenerCallbacks,
3265 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003266 transactionQueue.pop();
3267 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003268 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003269
Valerie Haufce31b82019-04-30 16:41:14 -07003270 if (transactionQueue.empty()) {
3271 it = mTransactionQueues.erase(it);
3272 mTransactionCV.broadcast();
3273 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003274 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003275 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003276 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003277 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003278 return flushedATransaction;
3279}
3280
3281bool SurfaceFlinger::transactionFlushNeeded() {
3282 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003283}
3284
chaviwca27f252018-02-06 16:46:39 -08003285
Marissa Wall17b4e452018-12-26 16:32:34 -08003286bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003287 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003288 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003289 if (!useCachedExpectedPresentTime)
3290 populateExpectedPresentTime();
3291
3292 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003293 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3294 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3295 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3296 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3297 return false;
3298 }
3299
Marissa Wall713b63f2018-10-17 15:42:43 -07003300 for (const ComposerState& state : states) {
3301 const layer_state_t& s = state.state;
3302 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3303 continue;
3304 }
3305 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003306 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003307 }
3308 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003309 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003310}
3311
Valerie Hau9dab9732019-08-20 09:29:25 -07003312void SurfaceFlinger::setTransactionState(
3313 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3314 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3315 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3316 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003317 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003318
Valerie Haubc6ddb12019-03-08 11:10:15 -08003319 const int64_t postTime = systemTime();
3320
Robert Carr14167e02019-02-13 13:50:55 -08003321 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3322
Mathias Agopian698c0872011-06-28 19:09:31 -07003323 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003324
Marissa Wall713b63f2018-10-17 15:42:43 -07003325 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003326 auto itr = mTransactionQueues.find(applyToken);
3327 // if this is an animation frame, wait until prior animation frame has
3328 // been applied by SF
3329 if (flags & eAnimation) {
3330 while (itr != mTransactionQueues.end()) {
3331 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3332 if (CC_UNLIKELY(err != NO_ERROR)) {
3333 ALOGW_IF(err == TIMED_OUT,
3334 "setTransactionState timed out "
3335 "waiting for animation frame to apply");
3336 break;
3337 }
3338 itr = mTransactionQueues.find(applyToken);
3339 }
3340 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003341
3342 // Expected present time is computed and cached on invalidate, so it may be stale.
3343 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3344 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003345 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003346 uncacheBuffer, postTime, privileged,
3347 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003348 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003349 return;
3350 }
3351
Valerie Haubc6ddb12019-03-08 11:10:15 -08003352 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003353 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3354 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003355}
3356
Valerie Hau9dab9732019-08-20 09:29:25 -07003357void SurfaceFlinger::applyTransactionState(
3358 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3359 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3360 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3361 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3362 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003363 uint32_t transactionFlags = 0;
3364
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003365 if (flags & eAnimation) {
3366 // For window updates that are part of an animation we must wait for
3367 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003368 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003369 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003370 if (CC_UNLIKELY(err != NO_ERROR)) {
3371 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003372 // caller after a few seconds.
3373 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3374 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003375 mAnimTransactionPending = false;
3376 break;
3377 }
3378 }
3379 }
3380
chaviwca27f252018-02-06 16:46:39 -08003381 for (const DisplayState& display : displays) {
3382 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003383 }
3384
Valerie Hau9dab9732019-08-20 09:29:25 -07003385 // start and end registration for listeners w/ no surface so they can get their callback. Note
3386 // that listeners with SurfaceControls will start registration during setClientStateLocked
3387 // below.
3388 for (const auto& listener : listenerCallbacks) {
3389 mTransactionCompletedThread.startRegistration(listener);
3390 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003391 }
3392
Valerie Hau9dab9732019-08-20 09:29:25 -07003393 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003394 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003395 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003396 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3397 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003398 }
3399
Valerie Hau9dab9732019-08-20 09:29:25 -07003400 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003401 mTransactionCompletedThread.endRegistration(listenerCallback);
3402 }
3403
Marissa Walle2ffb422018-10-12 11:33:52 -07003404 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003405 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003406 mTransactionCompletedThread.sendCallbacks();
3407 }
3408 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003409
chaviw273171b2018-12-26 11:46:30 -08003410 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3411
Marissa Wall947d34e2019-03-29 14:03:53 -07003412 if (uncacheBuffer.isValid()) {
3413 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003414 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003415 }
3416
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003417 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3418 // anyway. This can be used as a flush mechanism for previous async transactions.
3419 // Empty animation transaction can be used to simulate back-pressure, so also force a
3420 // transaction for empty animation transactions.
3421 if (transactionFlags == 0 &&
3422 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003423 transactionFlags = eTransactionNeeded;
3424 }
3425
Marissa Wall06255332019-03-27 13:48:27 -07003426 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3427 // so we don't have to wake up again next frame to preform an uneeded traversal.
3428 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3429 transactionFlags = transactionFlags & (~eTraversalNeeded);
3430 mTraversalNeededMainThread = true;
3431 }
3432
Mathias Agopian386aa982011-11-07 21:58:03 -08003433 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003434 if (mInterceptor->isEnabled()) {
3435 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003436 }
Irvel468051e2016-06-13 16:44:44 -07003437
Mathias Agopian386aa982011-11-07 21:58:03 -08003438 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003439 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3440 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003441 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003442
3443 // if this is a synchronous transaction, wait for it to take effect
3444 // before returning.
3445 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003446 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003447 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003448 if (flags & eAnimation) {
3449 mAnimTransactionPending = true;
3450 }
chaviw4fe36852019-04-15 16:25:49 -07003451 if (mPendingInputWindowCommands.syncInputWindows) {
3452 mPendingSyncInputWindows = true;
3453 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003454
3455 // applyTransactionState can be called by either the main SF thread or by
3456 // another process through setTransactionState. While a given process may wish
3457 // to wait on synchronous transactions, the main SF thread should never
3458 // be blocked. Therefore, we only wait if isMainThread is false.
3459 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003460 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3461 if (CC_UNLIKELY(err != NO_ERROR)) {
3462 // just in case something goes wrong in SF, return to the
3463 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003464 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3465 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003466 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003467 break;
3468 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003469 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003470 }
3471}
3472
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003473uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3474 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3475 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003476
Mathias Agopiane57f2922012-08-09 16:29:12 -07003477 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003478 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3479
3480 const uint32_t what = s.what;
3481 if (what & DisplayState::eSurfaceChanged) {
3482 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3483 state.surface = s.surface;
3484 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003485 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003486 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003487 if (what & DisplayState::eLayerStackChanged) {
3488 if (state.layerStack != s.layerStack) {
3489 state.layerStack = s.layerStack;
3490 flags |= eDisplayTransactionNeeded;
3491 }
3492 }
3493 if (what & DisplayState::eDisplayProjectionChanged) {
3494 if (state.orientation != s.orientation) {
3495 state.orientation = s.orientation;
3496 flags |= eDisplayTransactionNeeded;
3497 }
3498 if (state.frame != s.frame) {
3499 state.frame = s.frame;
3500 flags |= eDisplayTransactionNeeded;
3501 }
3502 if (state.viewport != s.viewport) {
3503 state.viewport = s.viewport;
3504 flags |= eDisplayTransactionNeeded;
3505 }
3506 }
3507 if (what & DisplayState::eDisplaySizeChanged) {
3508 if (state.width != s.width) {
3509 state.width = s.width;
3510 flags |= eDisplayTransactionNeeded;
3511 }
3512 if (state.height != s.height) {
3513 state.height = s.height;
3514 flags |= eDisplayTransactionNeeded;
3515 }
3516 }
3517
Mathias Agopiane57f2922012-08-09 16:29:12 -07003518 return flags;
3519}
3520
Steven Thomasd4071902020-03-24 16:02:53 -07003521bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003522 IPCThreadState* ipc = IPCThreadState::self();
3523 const int pid = ipc->getCallingPid();
3524 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003525 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003526 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3527 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003528 return false;
3529 }
3530 return true;
3531}
3532
Marissa Wall3dad52d2019-03-22 14:03:19 -07003533uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003534 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3535 bool privileged,
3536 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003537 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003538
Valerie Hau9dab9732019-08-20 09:29:25 -07003539 for (auto& listener : s.listeners) {
3540 // note that startRegistration will not re-register if the listener has
3541 // already be registered for a prior surface control
3542 mTransactionCompletedThread.startRegistration(listener);
3543 listenerCallbacks.insert(listener);
3544 }
3545
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003546 sp<Layer> layer = nullptr;
3547 if (s.surface) {
3548 layer = fromHandle(s.surface);
3549 } else {
3550 // The client may provide us a null handle. Treat it as if the layer was removed.
3551 ALOGW("Attempt to set client state with a null layer handle");
3552 }
chaviw8b3871a2017-11-01 17:41:01 -07003553 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003554 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003555 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003556 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003557 }
chaviw8b3871a2017-11-01 17:41:01 -07003558 return 0;
3559 }
3560
chaviw8b3871a2017-11-01 17:41:01 -07003561 uint32_t flags = 0;
3562
Garfield Tan8a3083e2018-12-03 13:21:07 -08003563 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003564
3565 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3566 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003567 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003568 layer->pushPendingState();
3569 }
3570
Valerie Hau871d6352020-01-29 08:44:02 -08003571 // Only set by BLAST adapter layers
3572 if (what & layer_state_t::eProducerDisconnect) {
3573 layer->onDisconnect();
3574 }
3575
chaviw8b3871a2017-11-01 17:41:01 -07003576 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003577 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003578 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003579 }
chaviw8b3871a2017-11-01 17:41:01 -07003580 }
3581 if (what & layer_state_t::eLayerChanged) {
3582 // NOTE: index needs to be calculated before we update the state
3583 const auto& p = layer->getParent();
3584 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003585 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003586 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003587 mCurrentState.layersSortedByZ.removeAt(idx);
3588 mCurrentState.layersSortedByZ.add(layer);
3589 // we need traversal (state changed)
3590 // AND transaction (list changed)
3591 flags |= eTransactionNeeded|eTraversalNeeded;
3592 }
chaviw8b3871a2017-11-01 17:41:01 -07003593 } else {
3594 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003595 flags |= eTransactionNeeded|eTraversalNeeded;
3596 }
3597 }
chaviw8b3871a2017-11-01 17:41:01 -07003598 }
3599 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003600 // NOTE: index needs to be calculated before we update the state
3601 const auto& p = layer->getParent();
3602 if (p == nullptr) {
3603 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3604 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3605 mCurrentState.layersSortedByZ.removeAt(idx);
3606 mCurrentState.layersSortedByZ.add(layer);
3607 // we need traversal (state changed)
3608 // AND transaction (list changed)
3609 flags |= eTransactionNeeded|eTraversalNeeded;
3610 }
3611 } else {
3612 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3613 flags |= eTransactionNeeded|eTraversalNeeded;
3614 }
chaviw8b3871a2017-11-01 17:41:01 -07003615 }
3616 }
3617 if (what & layer_state_t::eSizeChanged) {
3618 if (layer->setSize(s.w, s.h)) {
3619 flags |= eTraversalNeeded;
3620 }
3621 }
3622 if (what & layer_state_t::eAlphaChanged) {
3623 if (layer->setAlpha(s.alpha))
3624 flags |= eTraversalNeeded;
3625 }
3626 if (what & layer_state_t::eColorChanged) {
3627 if (layer->setColor(s.color))
3628 flags |= eTraversalNeeded;
3629 }
Peiyong Lind3788632018-09-18 16:01:31 -07003630 if (what & layer_state_t::eColorTransformChanged) {
3631 if (layer->setColorTransform(s.colorTransform)) {
3632 flags |= eTraversalNeeded;
3633 }
3634 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003635 if (what & layer_state_t::eBackgroundColorChanged) {
3636 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3637 flags |= eTraversalNeeded;
3638 }
3639 }
chaviw8b3871a2017-11-01 17:41:01 -07003640 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003641 // TODO: b/109894387
3642 //
3643 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3644 // rotation. To see the problem observe that if we have a square parent, and a child
3645 // of the same size, then we rotate the child 45 degrees around it's center, the child
3646 // must now be cropped to a non rectangular 8 sided region.
3647 //
3648 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3649 // private API, and the WindowManager only uses rotation in one case, which is on a top
3650 // level layer in which cropping is not an issue.
3651 //
3652 // However given that abuse of rotation matrices could lead to surfaces extending outside
3653 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3654 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3655 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003656 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003657 flags |= eTraversalNeeded;
3658 }
3659 if (what & layer_state_t::eTransparentRegionChanged) {
3660 if (layer->setTransparentRegionHint(s.transparentRegion))
3661 flags |= eTraversalNeeded;
3662 }
3663 if (what & layer_state_t::eFlagsChanged) {
3664 if (layer->setFlags(s.flags, s.mask))
3665 flags |= eTraversalNeeded;
3666 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003667 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003668 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003669 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003670 if (what & layer_state_t::eCornerRadiusChanged) {
3671 if (layer->setCornerRadius(s.cornerRadius))
3672 flags |= eTraversalNeeded;
3673 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003674 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003675 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3676 }
chaviw8b3871a2017-11-01 17:41:01 -07003677 if (what & layer_state_t::eLayerStackChanged) {
3678 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3679 // We only allow setting layer stacks for top level layers,
3680 // everything else inherits layer stack from its parent.
3681 if (layer->hasParent()) {
3682 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003683 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003684 } else if (idx < 0) {
3685 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003686 "that also does not appear in the top level layer list. Something"
3687 " has gone wrong.",
3688 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003689 } else if (layer->setLayerStack(s.layerStack)) {
3690 mCurrentState.layersSortedByZ.removeAt(idx);
3691 mCurrentState.layersSortedByZ.add(layer);
3692 // we need traversal (state changed)
3693 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003694 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003695 }
3696 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003697 if (what & layer_state_t::eDeferTransaction_legacy) {
3698 if (s.barrierHandle_legacy != nullptr) {
3699 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3700 } else if (s.barrierGbp_legacy != nullptr) {
3701 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003702 if (authenticateSurfaceTextureLocked(gbp)) {
3703 const auto& otherLayer =
3704 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003705 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003706 } else {
3707 ALOGE("Attempt to defer transaction to to an"
3708 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003709 }
3710 }
chaviw8b3871a2017-11-01 17:41:01 -07003711 // We don't trigger a traversal here because if no other state is
3712 // changed, we don't want this to cause any more work
3713 }
chaviw8b3871a2017-11-01 17:41:01 -07003714 if (what & layer_state_t::eReparentChildren) {
3715 if (layer->reparentChildren(s.reparentHandle)) {
3716 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003717 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003718 }
chaviw8b3871a2017-11-01 17:41:01 -07003719 if (what & layer_state_t::eDetachChildren) {
3720 layer->detachChildren();
3721 }
3722 if (what & layer_state_t::eOverrideScalingModeChanged) {
3723 layer->setOverrideScalingMode(s.overrideScalingMode);
3724 // We don't trigger a traversal here because if no other state is
3725 // changed, we don't want this to cause any more work
3726 }
Marissa Wall61c58622018-07-18 10:12:20 -07003727 if (what & layer_state_t::eTransformChanged) {
3728 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3729 }
3730 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3731 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3732 flags |= eTraversalNeeded;
3733 }
3734 if (what & layer_state_t::eCropChanged) {
3735 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3736 }
Marissa Wall861616d2018-10-22 12:52:23 -07003737 if (what & layer_state_t::eFrameChanged) {
3738 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3739 }
Marissa Wall61c58622018-07-18 10:12:20 -07003740 if (what & layer_state_t::eAcquireFenceChanged) {
3741 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3742 }
3743 if (what & layer_state_t::eDataspaceChanged) {
3744 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3745 }
3746 if (what & layer_state_t::eHdrMetadataChanged) {
3747 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3748 }
3749 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3750 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3751 }
3752 if (what & layer_state_t::eApiChanged) {
3753 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3754 }
3755 if (what & layer_state_t::eSidebandStreamChanged) {
3756 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3757 }
Robert Carr720e5062018-07-30 17:45:14 -07003758 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003759 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003760 layer->setInputInfo(s.inputInfo);
3761 flags |= eTraversalNeeded;
3762 } else {
3763 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3764 }
Robert Carr720e5062018-07-30 17:45:14 -07003765 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003766 if (what & layer_state_t::eMetadataChanged) {
3767 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3768 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003769 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3770 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3771 flags |= eTraversalNeeded;
3772 }
3773 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003774 if (what & layer_state_t::eShadowRadiusChanged) {
3775 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3776 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003777 if (what & layer_state_t::eFrameRateSelectionPriority) {
3778 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3779 flags |= eTraversalNeeded;
3780 }
3781 }
Steven Thomas3172e202020-01-06 19:25:30 -08003782 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003783 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3784 "SurfaceFlinger::setClientStateLocked") &&
3785 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3786 Layer::FrameRate::convertCompatibility(
3787 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003788 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003789 }
Steven Thomas3172e202020-01-06 19:25:30 -08003790 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003791 // This has to happen after we reparent children because when we reparent to null we remove
3792 // child layers from current state and remove its relative z. If the children are reparented in
3793 // the same transaction, then we have to make sure we reparent the children first so we do not
3794 // lose its relative z order.
3795 if (what & layer_state_t::eReparent) {
3796 bool hadParent = layer->hasParent();
3797 if (layer->reparent(s.parentHandleForChild)) {
3798 if (!hadParent) {
3799 mCurrentState.layersSortedByZ.remove(layer);
3800 }
3801 flags |= eTransactionNeeded | eTraversalNeeded;
3802 }
3803 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003804 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003805 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3806 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003807 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3808 }
3809 }
Marissa Wall78b72202019-03-15 14:58:34 -07003810 bool bufferChanged = what & layer_state_t::eBufferChanged;
3811 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3812 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003813 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003814 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003815 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3816 if (success) {
3817 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3818 success = ClientCache::getInstance()
3819 .registerErasedRecipient(s.cachedBuffer,
3820 wp<ClientCache::ErasedRecipient>(this));
3821 if (!success) {
3822 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3823 }
3824 }
Marissa Wall78b72202019-03-15 14:58:34 -07003825 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003826 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003827 } else if (bufferChanged) {
3828 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003829 }
Marissa Wall78b72202019-03-15 14:58:34 -07003830 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003831 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3832 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003833 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003834 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003835 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003836 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3837 // Do not put anything that updates layer state or modifies flags after
3838 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003839 return flags;
3840}
3841
chaviw273171b2018-12-26 11:46:30 -08003842uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3843 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003844 if (inputWindowCommands.syncInputWindows) {
3845 flags |= eTraversalNeeded;
3846 }
3847
Vishnu Nairec0ab382019-02-13 15:32:56 -08003848 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003849 return flags;
3850}
3851
chaviwfe94a222019-08-21 13:52:59 -07003852status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3853 sp<IBinder>* outHandle) {
3854 if (!mirrorFromHandle) {
3855 return NAME_NOT_FOUND;
3856 }
3857
3858 sp<Layer> mirrorLayer;
3859 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003860 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003861
3862 {
3863 Mutex::Autolock _l(mStateLock);
3864 mirrorFrom = fromHandle(mirrorFromHandle);
3865 if (!mirrorFrom) {
3866 return NAME_NOT_FOUND;
3867 }
3868
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003869 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3870 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003871 if (result != NO_ERROR) {
3872 return result;
3873 }
3874
3875 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3876 }
3877
3878 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3879}
3880
Marissa Wall2d814fb2019-04-09 18:52:57 +00003881status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3882 uint32_t h, PixelFormat format, uint32_t flags,
3883 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003884 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003885 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3886 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003887 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003888 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003889 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003890 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003891 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003892
Robert Carrc0df3122019-04-11 13:18:21 -07003893 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3894 "Expected only one of parentLayer or parentHandle to be non-null. "
3895 "Programmer error?");
3896
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003897 status_t result = NO_ERROR;
3898
3899 sp<Layer> layer;
3900
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003901 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003902
Evan Roskya1f1e152019-01-24 16:17:46 -08003903 bool primaryDisplayOnly = false;
3904
3905 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3906 // TODO b/64227542
3907 if (metadata.has(METADATA_WINDOW_TYPE)) {
3908 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3909 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003910 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003911 primaryDisplayOnly = true;
3912 }
3913 }
3914
Mathias Agopian3165cc22012-08-08 19:42:09 -07003915 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003916 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003917 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3918 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003919
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003920 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003921 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003922 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003923 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003924 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003925 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003926 // check if buffer size is set for color layer.
3927 if (w > 0 || h > 0) {
3928 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3929 int(w), int(h));
3930 return BAD_VALUE;
3931 }
3932
Vishnu Nairfa247b12020-02-11 08:58:26 -08003933 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3934 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003935 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003936 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003937 // check if buffer size is set for container layer.
3938 if (w > 0 || h > 0) {
3939 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3940 int(w), int(h));
3941 return BAD_VALUE;
3942 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003943 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3944 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003945 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003946 default:
3947 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003948 break;
3949 }
3950
Dan Stoza7d89d062015-04-30 13:29:25 -07003951 if (result != NO_ERROR) {
3952 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003953 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003954
Evan Roskya1f1e152019-01-24 16:17:46 -08003955 if (primaryDisplayOnly) {
3956 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003957 }
3958
Robert Carrb89ea9d2018-12-10 13:01:14 -08003959 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003960 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3961 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003962 if (result != NO_ERROR) {
3963 return result;
3964 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003965 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003966
3967 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003968 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003969}
3970
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003971std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3972 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003973
3974 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003975 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003976
Dan Stoza436ccf32018-06-21 12:10:12 -07003977 // Grab the state lock since we're accessing mCurrentState
3978 Mutex::Autolock lock(mStateLock);
3979
Cody Northropbc755282017-03-31 12:00:08 -06003980 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003981 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003982 while (matchFound) {
3983 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003984 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003985 if (layer->getName() == uniqueName) {
3986 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003987 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003988 }
3989 });
3990 }
3991
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003992 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003993 return uniqueName;
3994}
3995
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003996status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003997 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003998 LayerMetadata metadata, PixelFormat& format,
3999 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004000 sp<IGraphicBufferProducer>* gbp,
4001 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004002 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004003 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004004 case PIXEL_FORMAT_TRANSPARENT:
4005 case PIXEL_FORMAT_TRANSLUCENT:
4006 format = PIXEL_FORMAT_RGBA_8888;
4007 break;
4008 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004009 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004010 break;
4011 }
4012
chaviwb4c6e582019-08-16 14:35:07 -07004013 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004014 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004015 args.textureName = getNewTexture();
4016 {
4017 // Grab the SF state lock during this since it's the only safe way to access
4018 // RenderEngine when creating a BufferLayerConsumer
4019 // TODO: Check if this lock is still needed here
4020 Mutex::Autolock lock(mStateLock);
4021 layer = getFactory().createBufferQueueLayer(args);
4022 }
4023
Marissa Wallfd668622018-05-10 10:21:13 -07004024 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004025 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004026 *handle = layer->getHandle();
4027 *gbp = layer->getProducer();
4028 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004029 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004030
Marissa Wallfd668622018-05-10 10:21:13 -07004031 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004032 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004033}
4034
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004035status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004036 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004037 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004038 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004039 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004040 args.displayDevice = getDefaultDisplayDevice();
4041 args.textureName = getNewTexture();
4042 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004043 if (outTransformHint) {
4044 *outTransformHint = layer->getTransformHint();
4045 }
Marissa Wall61c58622018-07-18 10:12:20 -07004046 *handle = layer->getHandle();
4047 *outLayer = layer;
4048
4049 return NO_ERROR;
4050}
4051
Vishnu Nairfa247b12020-02-11 08:58:26 -08004052status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4053 uint32_t h, uint32_t flags, LayerMetadata metadata,
4054 sp<IBinder>* handle, sp<Layer>* outLayer) {
4055 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004056 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004057 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004058 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004059}
4060
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004061status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004062 uint32_t w, uint32_t h, uint32_t flags,
4063 LayerMetadata metadata, sp<IBinder>* handle,
4064 sp<Layer>* outLayer) {
4065 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004066 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004067 *handle = (*outLayer)->getHandle();
4068 return NO_ERROR;
4069}
4070
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004071void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004072 mLayersPendingRemoval.add(layer);
4073 mLayersRemoved = true;
4074 setTransactionFlags(eTransactionNeeded);
4075}
4076
Robert Carr695d5282018-12-18 15:27:58 -08004077void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004078{
Robert Carr2e102c92018-10-23 12:11:15 -07004079 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004080 // If a layer has a parent, we allow it to out-live it's handle
4081 // with the idea that the parent holds a reference and will eventually
4082 // be cleaned up. However no one cleans up the top-level so we do so
4083 // here.
4084 if (layer->getParent() == nullptr) {
4085 mCurrentState.layersSortedByZ.remove(layer);
4086 }
4087 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004088
4089 auto it = mLayersByLocalBinderToken.begin();
4090 while (it != mLayersByLocalBinderToken.end()) {
4091 if (it->second == layer) {
4092 it = mLayersByLocalBinderToken.erase(it);
4093 } else {
4094 it++;
4095 }
4096 }
4097
Robert Carr695d5282018-12-18 15:27:58 -08004098 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004099}
4100
Mathias Agopianb60314a2012-04-10 22:09:54 -07004101// ---------------------------------------------------------------------------
4102
Andy McFadden13a082e2012-08-24 10:16:42 -07004103void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004104 const auto display = getDefaultDisplayDeviceLocked();
4105 if (!display) return;
4106
4107 const sp<IBinder> token = display->getDisplayToken().promote();
4108 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004109
Jesse Hall01e29052013-02-19 16:13:35 -08004110 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004111 Vector<ComposerState> state;
4112 Vector<DisplayState> displays;
4113 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004114 d.what = DisplayState::eDisplayProjectionChanged |
4115 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004116 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004117 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004118 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004119 d.frame.makeInvalid();
4120 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004121 d.width = 0;
4122 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004123 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004124 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4125 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004126
Dominik Laskowskie9774092018-12-11 10:04:24 -08004127 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004128
Dominik Laskowski83b88212018-12-11 13:34:06 -08004129 const nsecs_t vsyncPeriod = getVsyncPeriod();
4130 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004131
Brian Andersond0010582017-03-07 13:20:31 -08004132 // Use phase of 0 since phase is not known.
4133 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004134 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004135 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004136}
4137
4138void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004139 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004140 postMessageAsync(
4141 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004142}
4143
Ady Abraham27c70212019-06-11 10:52:26 -07004144void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4145 if (mHWCVsyncState != enabled) {
4146 getHwComposer().setVsyncEnabled(displayId, enabled);
4147 mHWCVsyncState = enabled;
4148 }
4149}
4150
Dominik Laskowskie9774092018-12-11 10:04:24 -08004151void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004152 if (display->isVirtual()) {
4153 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004154 return;
4155 }
4156
Dominik Laskowski075d3172018-05-24 15:50:06 -07004157 const auto displayId = display->getId();
4158 LOG_ALWAYS_FATAL_IF(!displayId);
4159
Dominik Laskowski34157762018-10-31 13:07:19 -07004160 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004161
4162 int currentMode = display->getPowerMode();
4163 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004164 return;
4165 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004166
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004167 display->setPowerMode(mode);
4168
Lloyd Pique4dccc412018-01-22 17:21:36 -08004169 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004170 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004171 }
4172
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004173 if (currentMode == HWC_POWER_MODE_OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004174 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4175 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4176 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004177 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004178 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004179 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004180 mScheduler->onScreenAcquired(mAppConnectionHandle);
4181 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004182 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004183
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004184 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004185 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004186 repaintEverything();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004187 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004188 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004189 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4190 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004191 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004192 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004193 mScheduler->disableHardwareVsync(true);
4194 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004195 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004196
Ady Abraham27c70212019-06-11 10:52:26 -07004197 // Make sure HWVsync is disabled before turning off the display
4198 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4199
Dominik Laskowski075d3172018-05-24 15:50:06 -07004200 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004201 mVisibleRegionsDirty = true;
4202 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004203 } else if (mode == HWC_POWER_MODE_DOZE ||
4204 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004205 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004206 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004207 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004208 mScheduler->onScreenAcquired(mAppConnectionHandle);
4209 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004210 }
4211 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4212 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004213 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004214 mScheduler->disableHardwareVsync(true);
4215 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004216 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004217 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004218 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004219 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004220 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004221 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004222
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004223 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004224 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004225 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004226 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004227 }
4228
Dominik Laskowski34157762018-10-31 13:07:19 -07004229 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004230}
4231
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004232void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004233 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004234 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004235 if (!display) {
4236 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4237 displayToken.get());
4238 } else if (display->isVirtual()) {
4239 ALOGW("Attempt to set power mode %d for virtual display", mode);
4240 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004241 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004242 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004243 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004244}
4245
4246// ---------------------------------------------------------------------------
4247
Dominik Laskowskic2867142019-01-21 11:33:38 -08004248status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4249 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004250 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004251
Mathias Agopianbd115332013-04-18 16:41:04 -07004252 IPCThreadState* ipc = IPCThreadState::self();
4253 const int pid = ipc->getCallingPid();
4254 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004255
Mathias Agopianbd115332013-04-18 16:41:04 -07004256 if ((uid != AID_SHELL) &&
4257 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004258 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4259 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004260 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004261 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004262 // (this would indicate SF is stuck, but we want to be able to
4263 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004264 status_t err = mStateLock.timedLock(s2ns(1));
4265 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004266 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004267 StringAppendF(&result,
4268 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4269 "(no locks held)\n",
4270 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004271 }
4272
Dominik Laskowskic2867142019-01-21 11:33:38 -08004273 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004274 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004275 {"--dispsync"s,
4276 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004277 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004278 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4279 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4280 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4281 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4282 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4283 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004284 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004285 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4286 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004287
Dominik Laskowskic2867142019-01-21 11:33:38 -08004288 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004289
Dominik Laskowski46470112019-08-02 13:13:11 -07004290 const auto it = dumpers.find(flag);
4291 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004292 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004293 } else if (!asProto) {
4294 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004295 }
4296
Mathias Agopian9795c422009-08-26 16:36:26 -07004297 if (locked) {
4298 mStateLock.unlock();
4299 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004300
Dominik Laskowski46470112019-08-02 13:13:11 -07004301 if (it == dumpers.end()) {
4302 const LayersProto layersProto = dumpProtoFromMainThread();
4303 if (asProto) {
4304 result.append(layersProto.SerializeAsString());
4305 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004306 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004307 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4308 result.append(LayerProtoParser::layerTreeToString(layerTree));
4309 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004310 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004311 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004312 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004313 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004314 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004315 return NO_ERROR;
4316}
4317
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004318status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4319 if (asProto && mTracing.isEnabled()) {
4320 mTracing.writeToFileAsync();
4321 }
4322
4323 return doDump(fd, DumpArgs(), asProto);
4324}
4325
Dominik Laskowskic2867142019-01-21 11:33:38 -08004326void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004327 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004328 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004329}
4330
Dominik Laskowskic2867142019-01-21 11:33:38 -08004331void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004332 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004333
Dominik Laskowskic2867142019-01-21 11:33:38 -08004334 if (args.size() > 1) {
4335 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004336 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004337 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004338 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004339 }
Robert Carr2047fae2016-11-28 14:09:09 -08004340 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004341 } else {
4342 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004343 }
4344}
4345
Dominik Laskowskic2867142019-01-21 11:33:38 -08004346void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004347 const bool clearAll = args.size() < 2;
4348 const auto name = clearAll ? String8() : String8(args[1]);
4349
Edgar Arriaga844fa672020-01-16 14:21:42 -08004350 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004351 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004352 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004353 }
Robert Carr2047fae2016-11-28 14:09:09 -08004354 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004355
Svetoslavd85084b2014-03-20 10:28:31 -07004356 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004357}
4358
Dominik Laskowskic2867142019-01-21 11:33:38 -08004359void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4360 mTimeStats->parseArgs(asProto, args, result);
4361}
4362
Jamie Gennis6547ff42013-07-16 20:12:42 -07004363// This should only be called from the main thread. Otherwise it would need
4364// the lock and should use mCurrentState rather than mDrawingState.
4365void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004366 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004367 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004368 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004369
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004370 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004371}
4372
Yiwei Zhang5434a782018-12-05 18:06:32 -08004373void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004374 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004375
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004376 if (isLayerTripleBufferingDisabled())
4377 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004378
Yiwei Zhang5434a782018-12-05 18:06:32 -08004379 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4380 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4381 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4382 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4383 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4384 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004385 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004386}
4387
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004388void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004389 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004390
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004391 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004392 result.append("\n");
4393
Ady Abraham9e16a482019-12-03 17:19:41 -08004394 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004395 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004396 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004397 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004398
Steven Thomasd4071902020-03-24 16:02:53 -07004399 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004400 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004401 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004402 ", min: %.2f Hz, max: %.2f Hz",
Steven Thomasd4071902020-03-24 16:02:53 -07004403 policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004404 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4405 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004406 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4407 if (currentPolicy != policy) {
4408 StringAppendF(&result,
4409 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
4410 ", min: %.2f Hz, max: %.2f Hz\n\n",
4411 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
4412 currentPolicy.maxRefreshRate);
4413 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004414
Ana Krulecc2870422019-01-29 19:00:58 -08004415 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004416 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004417}
4418
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4420 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004421 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4422 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004423 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004424 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004425 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004426 }
David Sodman4a36e932017-11-07 14:29:47 -08004427 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004428 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004429 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004430 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4431 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004432}
4433
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004434void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4435 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004436 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4437 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004438 for (const auto& segment : history) {
4439 if (!segment.usedThirdBuffer) {
4440 stats.twoBufferTime += segment.totalTime;
4441 }
4442 if (segment.occupancyAverage < 1.0f) {
4443 stats.doubleBufferedTime += segment.totalTime;
4444 } else if (segment.occupancyAverage < 2.0f) {
4445 stats.tripleBufferedTime += segment.totalTime;
4446 }
4447 ++stats.numSegments;
4448 stats.totalTime += segment.totalTime;
4449 }
4450}
4451
Yiwei Zhang5434a782018-12-05 18:06:32 -08004452void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4453 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004454
4455 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4456 const size_t count = currentLayers.size();
4457 for (size_t i=0 ; i<count ; i++) {
4458 currentLayers[i]->dumpFrameEvents(result);
4459 }
4460}
4461
Yiwei Zhang5434a782018-12-05 18:06:32 -08004462void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004463 result.append("Buffering stats:\n");
4464 result.append(" [Layer name] <Active time> <Two buffer> "
4465 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004466 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004467 typedef std::tuple<std::string, float, float, float> BufferTuple;
4468 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004469 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004470 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004471 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004472 if (stats.numSegments == 0) {
4473 continue;
4474 }
4475 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4476 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4477 stats.totalTime;
4478 float doubleBufferRatio = static_cast<float>(
4479 stats.doubleBufferedTime) / stats.totalTime;
4480 float tripleBufferRatio = static_cast<float>(
4481 stats.tripleBufferedTime) / stats.totalTime;
4482 sorted.insert({activeTime, {name, twoBufferRatio,
4483 doubleBufferRatio, tripleBufferRatio}});
4484 }
4485 for (const auto& sortedPair : sorted) {
4486 float activeTime = sortedPair.first;
4487 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004488 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4489 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004490 }
4491 result.append("\n");
4492}
4493
Yiwei Zhang5434a782018-12-05 18:06:32 -08004494void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004495 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004496 const auto displayId = display->getId();
4497 if (!displayId) {
4498 continue;
4499 }
4500 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004501 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004502 continue;
4503 }
4504
Yiwei Zhang5434a782018-12-05 18:06:32 -08004505 StringAppendF(&result,
4506 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4507 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004508 uint8_t port;
4509 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004510 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004511 result.append("no identification data\n");
4512 continue;
4513 }
4514
4515 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004516 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004517 continue;
4518 }
4519
4520 const auto edid = parseEdid(data);
4521 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004522 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004523 continue;
4524 }
4525
Yiwei Zhang5434a782018-12-05 18:06:32 -08004526 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004527 result.append(edid->displayName.data(), edid->displayName.length());
4528 result.append("\"\n");
4529 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004530}
4531
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004532void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4533 std::string& result) const {
4534 hwc2_display_t hwcDisplayId;
4535 uint8_t port;
4536 DisplayIdentificationData data;
4537
4538 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4539 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4540 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4541 }
4542}
4543
Yiwei Zhang5434a782018-12-05 18:06:32 -08004544void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004545 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004546 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4547 StringAppendF(&result, "DisplayColorSetting: %s\n",
4548 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004549
4550 // TODO: print out if wide-color mode is active or not
4551
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004552 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004553 const auto displayId = display->getId();
4554 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004555 continue;
4556 }
4557
Yiwei Zhang5434a782018-12-05 18:06:32 -08004558 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004559 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004560 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004561 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004562 }
4563
Lloyd Pique32cbe282018-10-19 13:09:22 -07004564 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004565 StringAppendF(&result, " Current color mode: %s (%d)\n",
4566 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004567 }
4568 result.append("\n");
4569}
4570
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004571LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4572 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
4573 const auto display = getDefaultDisplayDeviceLocked();
4574
chaviw1d044282017-09-27 12:19:28 -07004575 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004576 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004577 layer->writeToProto(layersProto, traceFlags, display);
chaviw08f3cb22020-01-13 13:17:21 -08004578 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004579
chaviw1d044282017-09-27 12:19:28 -07004580 return layersProto;
4581}
4582
Alec Mouri6b9e9912020-01-21 10:50:24 -08004583void SurfaceFlinger::dumpHwc(std::string& result) const {
4584 getHwComposer().dump(result);
4585}
4586
Vishnu Nair0f085c62019-08-30 08:49:12 -07004587void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4588 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4589 // it.
4590 LayerProto* rootProto = layersProto.add_layers();
4591 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4592 rootProto->set_id(offscreenRootLayerId);
4593 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004594 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004595
4596 for (Layer* offscreenLayer : mOffscreenLayers) {
4597 // Add layer as child of the fake root
4598 rootProto->add_children(offscreenLayer->sequence);
4599
4600 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004601 LayerProto* layerProto =
4602 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004603 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004604 }
4605}
4606
Vishnu Nair8406fd72019-07-30 11:29:31 -07004607LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4608 LayersProto layersProto;
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004609 postMessageSync(new LambdaMessage([&] { layersProto = dumpDrawingStateProto(traceFlags); }));
Vishnu Nair8406fd72019-07-30 11:29:31 -07004610 return layersProto;
4611}
4612
Vishnu Nair0f085c62019-08-30 08:49:12 -07004613void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4614 result.append("Offscreen Layers:\n");
4615 postMessageSync(new LambdaMessage([&]() {
4616 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004617 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004618 layer->dumpCallingUidPid(result);
4619 });
4620 }
4621 }));
4622}
4623
Dominik Laskowskic2867142019-01-21 11:33:38 -08004624void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4625 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004626 Colorizer colorizer(colorize);
4627
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004628 // figure out if we're stuck somewhere
4629 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004630 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004631 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4632
4633 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004634 * Dump library configuration.
4635 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004636
4637 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004638 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004639 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004640 appendSfConfigString(result);
4641 appendUiConfigString(result);
4642 appendGuiConfigString(result);
4643 result.append("\n");
4644
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004645 result.append("\nDisplay identification data:\n");
4646 dumpDisplayIdentificationData(result);
4647
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004648 result.append("\nWide-Color information:\n");
4649 dumpWideColorInfo(result);
4650
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004651 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004652 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004653 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004654 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004655 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004656
Andy McFadden41d67d72014-04-25 16:58:34 -07004657 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004658 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004659 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004660 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004661 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004662
Dan Stozab90cf072015-03-05 11:05:59 -08004663 dumpStaticScreenStats(result);
4664 result.append("\n");
4665
Alec Mouri40189b02019-03-05 15:07:54 -08004666 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4667 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4668 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004669
Dan Stozae77c7662016-05-13 11:37:28 -07004670 dumpBufferingStats(result);
4671
Andy McFadden4803b742012-09-24 19:07:20 -07004672 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004673 * Dump the visible layer list
4674 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004675 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004676 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004677 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4678 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004679 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004680
Chia-I Wu2f884132018-09-13 15:17:58 -07004681 {
Lloyd Pique207def92019-02-28 16:09:52 -08004682 StringAppendF(&result, "Composition layers\n");
4683 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004684 auto* compositionState = layer->getCompositionState();
4685 if (!compositionState) return;
4686
4687 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4688 layer->getDebugName() ? layer->getDebugName()
4689 : "<unknown>");
4690 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004691 });
4692 }
4693
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004694 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004695 * Dump Display state
4696 */
4697
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004698 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004699 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004700 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004701 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004702 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004703 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004704 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004705
4706 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004707 * Dump CompositionEngine state
4708 */
4709
4710 mCompositionEngine->dump(result);
4711
4712 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004713 * Dump SurfaceFlinger global state
4714 */
4715
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004716 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004717 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004718 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004719
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004720 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004721
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004722 DebugEGLImageTracker::getInstance()->dump(result);
4723
Dominik Laskowski075d3172018-05-24 15:50:06 -07004724 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004725 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4726 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004727 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4728 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004729 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004730 StringAppendF(&result,
4731 " transaction-flags : %08x\n"
4732 " gpu_to_cpu_unsupported : %d\n",
4733 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004734
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004735 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004736 displayId && getHwComposer().isConnected(*displayId)) {
4737 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738 StringAppendF(&result,
4739 " refresh-rate : %f fps\n"
4740 " x-dpi : %f\n"
4741 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004742 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4743 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004744 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004745
Yiwei Zhang5434a782018-12-05 18:06:32 -08004746 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004747
Dan Stozae22aec72016-08-01 13:20:59 -07004748 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004749 * Tracing state
4750 */
4751 mTracing.dump(result);
4752 result.append("\n");
4753
4754 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004755 * HWC layer minidump
4756 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004757 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004758 const auto displayId = display->getId();
4759 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004760 continue;
4761 }
4762
Yiwei Zhang5434a782018-12-05 18:06:32 -08004763 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004764 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004765 const sp<DisplayDevice> displayDevice = display;
4766 mCurrentState.traverseInZOrder(
4767 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004768 result.append("\n");
4769 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004770
4771 /*
4772 * Dump HWComposer state
4773 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004774 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004775 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004776 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004777 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004778 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004779 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004780
4781 /*
4782 * Dump gralloc state
4783 */
4784 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4785 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004786
4787 /*
4788 * Dump VrFlinger state if in use.
4789 */
4790 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4791 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004792 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004793 result.append("\n");
4794 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004795
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004796 result.append(mTimeStats->miniDump());
4797 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004798}
4799
Chia-I Wu28f320b2018-05-03 11:02:56 -07004800void SurfaceFlinger::updateColorMatrixLocked() {
4801 mat4 colorMatrix;
4802 if (mGlobalSaturationFactor != 1.0f) {
4803 // Rec.709 luma coefficients
4804 float3 luminance{0.213f, 0.715f, 0.072f};
4805 luminance *= 1.0f - mGlobalSaturationFactor;
4806 mat4 saturationMatrix = mat4(
4807 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4808 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4809 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4810 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4811 );
4812 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4813 } else {
4814 colorMatrix = mClientColorMatrix * mDaltonizer();
4815 }
4816
4817 if (mCurrentState.colorMatrix != colorMatrix) {
4818 mCurrentState.colorMatrix = colorMatrix;
4819 mCurrentState.colorMatrixChanged = true;
4820 setTransactionFlags(eTransactionNeeded);
4821 }
4822}
4823
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004824status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004825#pragma clang diagnostic push
4826#pragma clang diagnostic error "-Wswitch-enum"
4827 switch (static_cast<ISurfaceComposerTag>(code)) {
4828 // These methods should at minimum make sure that the client requested
4829 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004830 case BOOT_FINISHED:
4831 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004832 case CREATE_DISPLAY:
4833 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004834 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004835 case GET_ANIMATION_FRAME_STATS:
4836 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004837 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004838 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004839 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004840 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4841 case SET_AUTO_LOW_LATENCY_MODE:
4842 case GET_GAME_CONTENT_TYPE_SUPPORT:
4843 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004844 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004845 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004846 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004847 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004848 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004849 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004850 case SET_GLOBAL_SHADOW_SETTINGS:
4851 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4852 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4853 // necessary permission dynamically. Don't use the permission cache for this check.
4854 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4855 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004856 IPCThreadState* ipc = IPCThreadState::self();
4857 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4858 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004859 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004860 }
Robert Carr1db73f62016-12-21 12:58:51 -08004861 return OK;
4862 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004863 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004864 IPCThreadState* ipc = IPCThreadState::self();
4865 const int pid = ipc->getCallingPid();
4866 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004867 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4868 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004869 return PERMISSION_DENIED;
4870 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004871 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004872 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004873 // Used by apps to hook Choreographer to SurfaceFlinger.
4874 case CREATE_DISPLAY_EVENT_CONNECTION:
4875 // The following calls are currently used by clients that do not
4876 // request necessary permissions. However, they do not expose any secret
4877 // information, so it is OK to pass them.
4878 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004879 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004880 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004881 case GET_PHYSICAL_DISPLAY_IDS:
4882 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004883 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004884 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004885 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004886 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004887 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004888 case GET_DISPLAY_STATS:
4889 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4890 // Calling setTransactionState is safe, because you need to have been
4891 // granted a reference to Client* and Handle* to do anything with it.
4892 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004893 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004894 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004895 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004896 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004897 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004898 // setFrameRate() is deliberately available for apps to call without any
4899 // special permissions.
4900 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004901 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4902 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004903 return OK;
4904 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004905 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004906 case CAPTURE_SCREEN:
4907 case ADD_REGION_SAMPLING_LISTENER:
4908 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004909 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004910 IPCThreadState* ipc = IPCThreadState::self();
4911 const int pid = ipc->getCallingPid();
4912 const int uid = ipc->getCallingUid();
4913 if ((uid != AID_GRAPHICS) &&
4914 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4915 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4916 return PERMISSION_DENIED;
4917 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004918 return OK;
4919 }
chaviw93df2ea2019-04-30 16:45:12 -07004920 case CAPTURE_SCREEN_BY_ID: {
4921 IPCThreadState* ipc = IPCThreadState::self();
4922 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004923 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004924 return OK;
4925 }
4926 return PERMISSION_DENIED;
4927 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004928 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929
4930 // These codes are used for the IBinder protocol to either interrogate the recipient
4931 // side of the transaction for its canonical interface descriptor or to dump its state.
4932 // We let them pass by default.
4933 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4934 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4935 code == IBinder::SYSPROPS_TRANSACTION) {
4936 return OK;
4937 }
Ady Abraham07e54702020-04-16 15:05:37 -07004938 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004939 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004940 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004941 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4942 return OK;
4943 }
4944 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4945 return PERMISSION_DENIED;
4946#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004947}
4948
Ana Krulec13be8ad2018-08-21 02:43:56 +00004949status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4950 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004951 status_t credentialCheck = CheckTransactCodeCredentials(code);
4952 if (credentialCheck != OK) {
4953 return credentialCheck;
4954 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004955
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004956 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4957 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004958 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004959 IPCThreadState* ipc = IPCThreadState::self();
4960 const int uid = ipc->getCallingUid();
4961 if (CC_UNLIKELY(uid != AID_SYSTEM
4962 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004963 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004964 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004965 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004966 return PERMISSION_DENIED;
4967 }
4968 int n;
4969 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004970 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004971 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004972 return NO_ERROR;
4973 case 1002: // SHOW_UPDATES
4974 n = data.readInt32();
4975 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004976 invalidateHwcGeometry();
4977 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004978 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004979 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004980 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004981 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004982 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004983 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004984 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004985 setTransactionFlags(
4986 eTransactionNeeded|
4987 eDisplayTransactionNeeded|
4988 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004989 return NO_ERROR;
4990 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004991 case 1006:{ // send empty update
4992 signalRefresh();
4993 return NO_ERROR;
4994 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004995 case 1008: // toggle use of hw composer
4996 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004997 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004998 invalidateHwcGeometry();
4999 repaintEverything();
5000 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005001 case 1009: // toggle use of transform hint
5002 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005003 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005004 invalidateHwcGeometry();
5005 repaintEverything();
5006 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005007 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005008 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005009 reply->writeInt32(0);
5010 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005011 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005012 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005013 return NO_ERROR;
5014 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005015 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005016 if (!display) {
5017 return NAME_NOT_FOUND;
5018 }
5019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005020 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005021 return NO_ERROR;
5022 }
5023 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005024 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005025 // daltonize
5026 n = data.readInt32();
5027 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005028 case 1:
5029 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5030 break;
5031 case 2:
5032 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5033 break;
5034 case 3:
5035 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5036 break;
5037 default:
5038 mDaltonizer.setType(ColorBlindnessType::None);
5039 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005040 }
5041 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005042 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005043 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005044 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005045 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005046
5047 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005048 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005049 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005050 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005051 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005052 // apply a color matrix
5053 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005054 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005055 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005056 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005057 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005058 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005059 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005060 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005061 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005062 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005063 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005064
5065 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5066 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005067 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005068 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5069 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5070 }
5071
Chia-I Wu28f320b2018-05-03 11:02:56 -07005072 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005073 return NO_ERROR;
5074 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005075 case 1016: { // Unused.
5076 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005077 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005078 case 1017: {
5079 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005080 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005081 return NO_ERROR;
5082 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005083 case 1018: { // Modify Choreographer's phase offset
5084 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005085 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005086 return NO_ERROR;
5087 }
5088 case 1019: { // Modify SurfaceFlinger's phase offset
5089 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005090 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005091 return NO_ERROR;
5092 }
Irvel468051e2016-06-13 16:44:44 -07005093 case 1020: { // Layer updates interceptor
5094 n = data.readInt32();
5095 if (n) {
5096 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005097 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005098 }
5099 else{
5100 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005101 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005102 }
5103 return NO_ERROR;
5104 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005105 case 1021: { // Disable HWC virtual displays
5106 n = data.readInt32();
5107 mUseHwcVirtualDisplays = !n;
5108 return NO_ERROR;
5109 }
Romain Guy0147a172017-06-01 13:53:56 -07005110 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005111 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005112 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005113
Chia-I Wu28f320b2018-05-03 11:02:56 -07005114 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005115 return NO_ERROR;
5116 }
Romain Guy54f154a2017-10-24 21:40:32 +01005117 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005118 int32_t colorMode;
5119
Chia-I Wu0d711262018-05-21 15:19:35 -07005120 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005121 if (data.readInt32(&colorMode) == NO_ERROR) {
5122 mForceColorMode = static_cast<ColorMode>(colorMode);
5123 }
Romain Guy54f154a2017-10-24 21:40:32 +01005124 invalidateHwcGeometry();
5125 repaintEverything();
5126 return NO_ERROR;
5127 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005128 // Deprecate, use 1030 to check whether the device is color managed.
5129 case 1024: {
5130 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005131 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005132 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005133 n = data.readInt32();
5134 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005135 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005136 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005137 reply->writeInt32(NO_ERROR);
5138 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005139 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005140 mTracingEnabledChanged = mTracing.disable();
5141 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005142 reply->writeInt32(mTracing.writeToFile());
5143 } else {
5144 reply->writeInt32(NO_ERROR);
5145 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005146 }
5147 return NO_ERROR;
5148 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005149 case 1026: { // Get layer tracing status
5150 reply->writeBool(mTracing.isEnabled());
5151 return NO_ERROR;
5152 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005153 // Is a DisplayColorSetting supported?
5154 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005155 const auto display = getDefaultDisplayDevice();
5156 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005157 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005158 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005159
5160 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5161 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005162 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005163 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005164 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005165 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005166 reply->writeBool(true);
5167 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005168 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005169 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005170 break;
5171 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005172 reply->writeBool(
5173 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005174 break;
5175 }
5176 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005177 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005178 // Is VrFlinger active?
5179 case 1028: {
5180 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005181 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005182 return NO_ERROR;
5183 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005184 // Set buffer size for SF tracing (value in KB)
5185 case 1029: {
5186 n = data.readInt32();
5187 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5188 ALOGW("Invalid buffer size: %d KB", n);
5189 reply->writeInt32(BAD_VALUE);
5190 return BAD_VALUE;
5191 }
5192
5193 ALOGD("Updating trace buffer to %d KB", n);
5194 mTracing.setBufferSize(n * 1024);
5195 reply->writeInt32(NO_ERROR);
5196 return NO_ERROR;
5197 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005198 // Is device color managed?
5199 case 1030: {
5200 reply->writeBool(useColorManagement);
5201 return NO_ERROR;
5202 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005203 // Override default composition data space
5204 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5205 // && adb shell stop zygote && adb shell start zygote
5206 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5207 // adb shell stop zygote && adb shell start zygote
5208 case 1031: {
5209 Mutex::Autolock _l(mStateLock);
5210 n = data.readInt32();
5211 if (n) {
5212 n = data.readInt32();
5213 if (n) {
5214 Dataspace dataspace = static_cast<Dataspace>(n);
5215 if (!validateCompositionDataspace(dataspace)) {
5216 return BAD_VALUE;
5217 }
5218 mDefaultCompositionDataspace = dataspace;
5219 }
5220 n = data.readInt32();
5221 if (n) {
5222 Dataspace dataspace = static_cast<Dataspace>(n);
5223 if (!validateCompositionDataspace(dataspace)) {
5224 return BAD_VALUE;
5225 }
5226 mWideColorGamutCompositionDataspace = dataspace;
5227 }
5228 } else {
5229 // restore composition data space.
5230 mDefaultCompositionDataspace = defaultCompositionDataspace;
5231 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5232 }
5233 return NO_ERROR;
5234 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005235 // Set trace flags
5236 case 1033: {
5237 n = data.readUint32();
5238 ALOGD("Updating trace flags to 0x%x", n);
5239 mTracing.setTraceFlags(n);
5240 reply->writeInt32(NO_ERROR);
5241 return NO_ERROR;
5242 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005243 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005244 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005245 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005246 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005247 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005248 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005249 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005250 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005251 } else {
5252 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005253 }
5254 return NO_ERROR;
5255 }
Ady Abraham34392f72019-04-10 11:29:27 -07005256 case 1035: {
5257 n = data.readInt32();
5258 mDebugDisplayConfigSetByBackdoor = false;
5259 if (n >= 0) {
5260 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005261 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005262 if (result != NO_ERROR) {
5263 return result;
5264 }
5265 mDebugDisplayConfigSetByBackdoor = true;
5266 }
5267 return NO_ERROR;
5268 }
Ady Abraham07e54702020-04-16 15:05:37 -07005269 case 1036: {
5270 if (data.readInt32() > 0) {
5271 status_t result =
5272 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5273 if (result != NO_ERROR) {
5274 return result;
5275 }
5276 } else {
5277 mDebugFrameRateFlexibilityToken = nullptr;
5278 }
5279 return NO_ERROR;
5280 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005281 }
5282 }
5283 return err;
5284}
5285
Steven Thomas6d8110b2017-08-31 18:24:21 -07005286void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005287 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005288 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005289}
5290
Ana Krulec7d1d6832018-12-27 11:10:09 -08005291void SurfaceFlinger::repaintEverythingForHWC() {
5292 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005293 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005294 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005295}
5296
Ady Abrahama09852a2020-02-20 14:23:42 -08005297void SurfaceFlinger::kernelTimerChanged(bool expired) {
5298 static bool updateOverlay =
5299 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5300 if (!updateOverlay || !mRefreshRateOverlay) return;
5301
5302 // Update the overlay on the main thread to avoid race conditions with
5303 // mRefreshRateConfigs->getCurrentRefreshRate()
5304 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5305 if (mRefreshRateOverlay) {
5306 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5307 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005308 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005309 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5310 if (mDesiredActiveConfigChanged) {
5311 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5312 mDesiredActiveConfig.configId);
5313 }
5314
5315 return mRefreshRateConfigs->getCurrentRefreshRate();
5316 }();
5317 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5318
5319 if (current != min) {
5320 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5321 mEventQueue->invalidate();
5322 }
5323 }
5324 }));
5325}
5326
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005327// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5328class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005329public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005330 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5331 ~WindowDisconnector() {
5332 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005333 }
5334
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005335private:
5336 ANativeWindow* mWindow;
5337 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005338};
5339
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005340status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005341 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005342 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5343 const Rect& sourceCrop, uint32_t reqWidth,
5344 uint32_t reqHeight, bool useIdentityTransform,
5345 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005346 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005347
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005348 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005349
Dominik Laskowski718f9602019-11-09 20:01:35 -08005350 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5351 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5352 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5353 renderAreaRotation = ui::Transform::ROT_0;
5354 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005355
Chia-I Wu20261cb2018-08-23 12:55:44 -07005356 sp<DisplayDevice> display;
5357 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005358 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005359
Chia-I Wu20261cb2018-08-23 12:55:44 -07005360 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005361 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005362
Chia-I Wucb023152018-08-28 12:57:23 -07005363 // set the requested width/height to the logical display viewport size
5364 // by default
5365 if (reqWidth == 0 || reqHeight == 0) {
5366 reqWidth = uint32_t(display->getViewport().width());
5367 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005368 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005369 }
5370
Peiyong Lin0e003c92018-09-17 11:09:51 -07005371 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005372 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005373 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5374 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005375 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005376 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005377}
5378
chaviw93df2ea2019-04-30 16:45:12 -07005379static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5380 switch (colorMode) {
5381 case ColorMode::DISPLAY_P3:
5382 case ColorMode::BT2100_PQ:
5383 case ColorMode::BT2100_HLG:
5384 case ColorMode::DISPLAY_BT2020:
5385 return Dataspace::DISPLAY_P3;
5386 default:
5387 return Dataspace::V0_SRGB;
5388 }
5389}
5390
Martin Liu4a322352020-03-24 21:30:38 +08005391status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5392 static constexpr int kFifoPriority = 2;
5393 static constexpr int kOtherPriority = 0;
5394
5395 struct sched_param param = {0};
5396 int sched_policy;
5397 if (enabled) {
5398 sched_policy = SCHED_FIFO;
5399 param.sched_priority = kFifoPriority;
5400 } else {
5401 sched_policy = SCHED_OTHER;
5402 param.sched_priority = kOtherPriority;
5403 }
5404
5405 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5406 return -errno;
5407 }
5408 return NO_ERROR;
5409}
5410
chaviw93df2ea2019-04-30 16:45:12 -07005411const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5412 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5413 if (displayToken) {
5414 return getDisplayDeviceLocked(displayToken);
5415 }
5416 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5417 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005418 return getDisplayByLayerStack(displayOrLayerStack);
5419}
5420
5421const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005422 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005423 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005424 return display;
5425 }
5426 }
5427 return nullptr;
5428}
5429
5430status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5431 sp<GraphicBuffer>* outBuffer) {
5432 sp<DisplayDevice> display;
5433 uint32_t width;
5434 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005435 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005436 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005437 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005438 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5439 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005440 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005441 }
5442
5443 width = uint32_t(display->getViewport().width());
5444 height = uint32_t(display->getViewport().height());
5445
Dominik Laskowski718f9602019-11-09 20:01:35 -08005446 const auto orientation = display->getOrientation();
5447 captureOrientation = ui::Transform::toRotationFlags(orientation);
5448
5449 switch (captureOrientation) {
5450 case ui::Transform::ROT_90:
5451 captureOrientation = ui::Transform::ROT_270;
5452 break;
5453
5454 case ui::Transform::ROT_270:
5455 captureOrientation = ui::Transform::ROT_90;
5456 break;
5457
5458 case ui::Transform::ROT_INVALID:
5459 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5460 captureOrientation = ui::Transform::ROT_0;
5461 break;
5462
5463 default:
5464 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005465 }
chaviw93df2ea2019-04-30 16:45:12 -07005466 *outDataspace =
5467 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5468 }
5469
5470 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5471 false /* captureSecureLayers */);
5472
5473 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5474 std::placeholders::_1);
5475 bool ignored = false;
5476 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5477 false /* useIdentityTransform */,
5478 ignored /* outCapturedSecureLayers */);
5479}
5480
Robert Carr866455f2019-04-02 16:28:26 -07005481status_t SurfaceFlinger::captureLayers(
5482 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5483 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5484 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5485 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005486 ATRACE_CALL();
5487
5488 class LayerRenderArea : public RenderArea {
5489 public:
Robert Carr578038f2018-03-09 12:25:24 -08005490 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005491 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005492 bool childrenOnly, const Rect& displayViewport)
5493 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005494 mLayer(layer),
5495 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005496 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005497 mFlinger(flinger),
5498 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005499 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005500 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005501 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005502 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005503 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005504 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005505 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005506 }
chaviwa76b2712017-09-20 12:02:26 -07005507 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005508 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005509 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005510 Rect getSourceCrop() const override {
5511 if (mCrop.isEmpty()) {
5512 return getBounds();
5513 } else {
5514 return mCrop;
5515 }
5516 }
Robert Carr578038f2018-03-09 12:25:24 -08005517 class ReparentForDrawing {
5518 public:
5519 const sp<Layer>& oldParent;
5520 const sp<Layer>& newParent;
5521
Vishnu Nair4351ad52019-02-11 14:13:02 -08005522 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5523 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005524 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005525 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005526 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5527 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005528 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005529 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005530 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005531 };
5532
5533 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005534 const Rect sourceCrop = getSourceCrop();
5535 // no need to check rotation because there is none
5536 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5537 sourceCrop.height() != getReqHeight();
5538
Robert Carr578038f2018-03-09 12:25:24 -08005539 if (!mChildrenOnly) {
5540 mTransform = mLayer->getTransform().inverse();
5541 drawLayers();
5542 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005543 uint32_t w = static_cast<uint32_t>(getWidth());
5544 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005545 // In the "childrenOnly" case we reparent the children to a screenshot
5546 // layer which has no properties set and which does not draw.
5547 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005548 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5549 "Screenshot Parent"s, w, h, 0,
5550 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005551
Vishnu Nair4351ad52019-02-11 14:13:02 -08005552 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005553 drawLayers();
5554 }
5555 }
chaviwa76b2712017-09-20 12:02:26 -07005556
chaviwa76b2712017-09-20 12:02:26 -07005557 private:
chaviw7206d492017-11-10 16:16:12 -08005558 const sp<Layer> mLayer;
5559 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005560
Peiyong Linefefaac2018-08-17 12:27:51 -07005561 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005562 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005563
5564 SurfaceFlinger* mFlinger;
5565 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005566 };
5567
Robert Carrc0df3122019-04-11 13:18:21 -07005568 int reqWidth = 0;
5569 int reqHeight = 0;
5570 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005571 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005572 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005573 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005574 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005575 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005576
Robert Carrc0df3122019-04-11 13:18:21 -07005577 parent = fromHandle(layerHandleBinder);
5578 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5579 ALOGE("captureLayers called with an invalid or removed parent");
5580 return NAME_NOT_FOUND;
5581 }
5582
5583 const int uid = IPCThreadState::self()->getCallingUid();
5584 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5585 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5586 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5587 return PERMISSION_DENIED;
5588 }
5589
Vishnu Nairefc42e22019-12-03 17:36:12 -08005590 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005591 if (sourceCrop.width() <= 0) {
5592 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005593 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005594 }
5595
5596 if (sourceCrop.height() <= 0) {
5597 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005598 crop.bottom = parentSourceBounds.getHeight();
5599 }
5600
5601 if (crop.isEmpty() || frameScale <= 0.0f) {
5602 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5603 // crop was not specified, or an invalid frame scale was provided.
5604 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005605 }
5606 reqWidth = crop.width() * frameScale;
5607 reqHeight = crop.height() * frameScale;
5608
5609 for (const auto& handle : excludeHandles) {
5610 sp<Layer> excludeLayer = fromHandle(handle);
5611 if (excludeLayer != nullptr) {
5612 excludeLayers.emplace(excludeLayer);
5613 } else {
5614 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5615 return NAME_NOT_FOUND;
5616 }
5617 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005618
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005619 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005620 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005621 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005622 }
5623
5624 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005625 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005626
Chia-I Wu20261cb2018-08-23 12:55:44 -07005627 // really small crop or frameScale
5628 if (reqWidth <= 0) {
5629 reqWidth = 1;
5630 }
5631 if (reqHeight <= 0) {
5632 reqHeight = 1;
5633 }
5634
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005635 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5636 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005637 auto traverseLayers = [parent, childrenOnly,
5638 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005639 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5640 if (!layer->isVisible()) {
5641 return;
Robert Carr578038f2018-03-09 12:25:24 -08005642 } else if (childrenOnly && layer == parent.get()) {
5643 return;
chaviwa76b2712017-09-20 12:02:26 -07005644 }
Robert Carr866455f2019-04-02 16:28:26 -07005645
5646 sp<Layer> p = layer;
5647 while (p != nullptr) {
5648 if (excludeLayers.count(p) != 0) {
5649 return;
5650 }
5651 p = p->getParent();
5652 }
5653
chaviwa76b2712017-09-20 12:02:26 -07005654 visitor(layer);
5655 });
5656 };
Robert Carr108b2c72019-04-02 16:32:58 -07005657
5658 bool outCapturedSecureLayers = false;
5659 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5660 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005661}
5662
5663status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5664 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005665 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005666 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005667 bool useIdentityTransform,
5668 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005669 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005670
Peiyong Lin0e003c92018-09-17 11:09:51 -07005671 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005672 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5673 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005674 *outBuffer =
5675 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5676 static_cast<android_pixel_format>(reqPixelFormat), 1,
5677 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005678
Robert Carr108b2c72019-04-02 16:32:58 -07005679 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5680 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005681}
5682
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005683status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5684 TraverseLayersFunction traverseLayers,
5685 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005686 bool useIdentityTransform,
5687 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005688 // This mutex protects syncFd and captureResult for communication of the return values from the
5689 // main thread back to this Binder thread
5690 std::mutex captureMutex;
5691 std::condition_variable captureCondition;
5692 std::unique_lock<std::mutex> captureLock(captureMutex);
5693 int syncFd = -1;
5694 std::optional<status_t> captureResult;
5695
Robert Carr03480e22018-01-04 16:02:06 -08005696 const int uid = IPCThreadState::self()->getCallingUid();
5697 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5698
Dominik Laskowski8c001672018-05-30 16:52:06 -07005699 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005700 // If there is a refresh pending, bug out early and tell the binder thread to try again
5701 // after the refresh.
5702 if (mRefreshPending) {
5703 ATRACE_NAME("Skipping screenshot for now");
5704 std::unique_lock<std::mutex> captureLock(captureMutex);
5705 captureResult = std::make_optional<status_t>(EAGAIN);
5706 captureCondition.notify_one();
5707 return;
5708 }
5709
5710 status_t result = NO_ERROR;
5711 int fd = -1;
5712 {
5713 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005714 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005715 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005716 useIdentityTransform, forSystem, &fd,
5717 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005718 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005719 }
5720
5721 {
5722 std::unique_lock<std::mutex> captureLock(captureMutex);
5723 syncFd = fd;
5724 captureResult = std::make_optional<status_t>(result);
5725 captureCondition.notify_one();
5726 }
5727 });
5728
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005729 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005730 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005731 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005732 while (*captureResult == EAGAIN) {
5733 captureResult.reset();
5734 result = postMessageAsync(message);
5735 if (result != NO_ERROR) {
5736 return result;
5737 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005738 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005739 }
5740 result = *captureResult;
5741 }
5742
5743 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005744 sync_wait(syncFd, -1);
5745 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005746 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005747
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005748 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005749}
5750
chaviwa76b2712017-09-20 12:02:26 -07005751void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005752 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005753 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5754 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005755 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005756
chaviwa76b2712017-09-20 12:02:26 -07005757 const auto reqWidth = renderArea.getReqWidth();
5758 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005759 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005760 const auto transform = renderArea.getTransform();
5761 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005762 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005763
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005764 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005765 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005766
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005767 // assume that bounds are never offset, and that they are the same as the
5768 // buffer bounds.
5769 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005770 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005771 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005772
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005773 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5774 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005775
chaviw50da5042018-04-09 13:49:37 -07005776 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005777
Vishnu Nair9b079a22020-01-21 14:36:08 -08005778 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005779 fillLayer.source.buffer.buffer = nullptr;
5780 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005781 fillLayer.geometry.boundaries =
5782 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005783 fillLayer.alpha = half(alpha);
5784 clientCompositionLayers.push_back(fillLayer);
5785
Yichi Chen40773d92020-04-01 10:10:18 +08005786 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005787 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005788 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005789 const bool supportProtectedContent = false;
5790 Region clip(renderArea.getBounds());
5791 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5792 clip,
5793 useIdentityTransform,
Alec Mouri5a6d8572020-03-23 23:56:15 -07005794 layer->needsFilteringForScreenshots(renderArea.getDisplayDevice(), transform) ||
5795 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005796 renderArea.isSecure(),
5797 supportProtectedContent,
5798 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005799 displayViewport,
5800 clientCompositionDisplay.outputDataspace,
5801 true, /* realContentIsVisible */
5802 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005803 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005804 std::vector<compositionengine::LayerFE::LayerSettings> results =
5805 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005806 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005807 for (auto& settings : results) {
5808 settings.geometry.positionTransform =
5809 transform.asMatrix4() * settings.geometry.positionTransform;
5810 }
Yichi Chen40773d92020-04-01 10:10:18 +08005811 clientCompositionLayers.insert(clientCompositionLayers.end(),
5812 std::make_move_iterator(results.begin()),
5813 std::make_move_iterator(results.end()));
5814 renderedLayers.push_back(layer);
5815 }
chaviwa76b2712017-09-20 12:02:26 -07005816 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005817
Yichi Chen40773d92020-04-01 10:10:18 +08005818 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5819 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005820 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005821 clientCompositionLayerPointers.begin(),
5822 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005823
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005824 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005825 // Use an empty fence for the buffer fence, since we just created the buffer so
5826 // there is no need for synchronization with the GPU.
5827 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005828 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005829 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005830 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005831 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005832
5833 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005834
5835 if (*outSyncFd >= 0) {
5836 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5837 for (auto* layer : renderedLayers) {
5838 layer->onLayerDisplayed(releaseFence);
5839 }
5840 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005841}
5842
chaviwa76b2712017-09-20 12:02:26 -07005843status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5844 TraverseLayersFunction traverseLayers,
5845 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005846 bool useIdentityTransform, bool forSystem,
5847 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005848 ATRACE_CALL();
5849
chaviwa76b2712017-09-20 12:02:26 -07005850 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005851 outCapturedSecureLayers =
5852 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005853 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005854
Robert Carr03480e22018-01-04 16:02:06 -08005855 // We allow the system server to take screenshots of secure layers for
5856 // use in situations like the Screen-rotation animation and place
5857 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005858 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005859 ALOGW("FB is protected: PERMISSION_DENIED");
5860 return PERMISSION_DENIED;
5861 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005862 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005863 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005864}
5865
chaviw95ef3c42019-02-14 10:55:09 -08005866void SurfaceFlinger::setInputWindowsFinished() {
5867 Mutex::Autolock _l(mStateLock);
5868
5869 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005870
chaviw95ef3c42019-02-14 10:55:09 -08005871 mTransactionCV.broadcast();
5872}
chaviw5f21a5e2019-02-14 10:00:34 -08005873
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005874// ---------------------------------------------------------------------------
5875
Edgar Arriaga844fa672020-01-16 14:21:42 -08005876void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5877 layersSortedByZ.traverse(visitor);
5878}
5879
Dan Stoza412903f2017-04-27 13:42:17 -07005880void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5881 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005882}
5883
Dan Stoza412903f2017-04-27 13:42:17 -07005884void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5885 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005886}
5887
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005888void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005889 const LayerVector::Visitor& visitor) {
5890 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005891 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005892 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005893 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005894 continue;
5895 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005896 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005897 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005898 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005899 return;
5900 }
chaviwa76b2712017-09-20 12:02:26 -07005901 if (!layer->isVisible()) {
5902 return;
5903 }
5904 visitor(layer);
5905 });
5906 }
5907}
5908
Steven Thomasd4071902020-03-24 16:02:53 -07005909status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5910 const sp<DisplayDevice>& display,
5911 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005912 Mutex::Autolock lock(mStateLock);
5913
Steven Thomasd4071902020-03-24 16:02:53 -07005914 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5915 "Can only set override policy on the primary display");
5916 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5917
Dominik Laskowski22488f62019-03-28 09:53:04 -07005918 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005919 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5920 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5921 // it should go thru setDesiredActiveConfig, similar to primary display.
5922 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5923 const auto displayId = display->getId();
5924 LOG_ALWAYS_FATAL_IF(!displayId);
5925
5926 HWC2::VsyncPeriodChangeConstraints constraints;
5927 constraints.desiredTimeNanos = systemTime();
5928 constraints.seamlessRequired = false;
5929
5930 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005931 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5932 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005933 constraints, &timeline) < 0) {
5934 return BAD_VALUE;
5935 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005936 if (timeline.refreshRequired) {
5937 repaintEverythingForHWC();
5938 }
5939
Steven Thomasd4071902020-03-24 16:02:53 -07005940 display->setActiveConfig(policy->defaultConfig);
5941 const nsecs_t vsyncPeriod = getHwComposer()
5942 .getConfigs(*displayId)[policy->defaultConfig.value()]
5943 ->getVsyncPeriod();
5944 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5945 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005946 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005947 }
5948
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005949 if (mDebugDisplayConfigSetByBackdoor) {
5950 // ignore this request as config is overridden by backdoor
5951 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005952 }
5953
Steven Thomasd4071902020-03-24 16:02:53 -07005954 status_t setPolicyResult = overridePolicy
5955 ? mRefreshRateConfigs->setOverridePolicy(policy)
5956 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5957 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005958 return BAD_VALUE;
5959 }
Steven Thomasd4071902020-03-24 16:02:53 -07005960 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005961 return NO_ERROR;
5962 }
Steven Thomasd4071902020-03-24 16:02:53 -07005963 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005964
5965 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
Steven Thomasd4071902020-03-24 16:02:53 -07005966 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
5967 currentPolicy.maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005968
5969 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5970 // that listeners that care about a change in allowed configs can get the notification.
5971 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005972 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005973 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5974 .getVsyncPeriod();
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005975 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005976 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005977
Ana Krulec3f6a2062020-01-23 15:48:01 -08005978 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005979 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005980 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5981 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005982 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005983 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005984 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005985
Ady Abrahamabc27602020-04-08 17:20:29 -07005986 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5987 ALOGV("switching to Scheduler preferred config %d",
5988 preferredRefreshRate.getConfigId().value());
5989 setDesiredActiveConfig(
5990 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005991 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005992 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5993 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005994 }
5995
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005996 return NO_ERROR;
5997}
5998
Ana Krulec0782b882019-10-15 17:34:54 -07005999status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006000 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07006001 float maxRefreshRate) {
6002 ATRACE_CALL();
6003
6004 if (!displayToken) {
6005 return BAD_VALUE;
6006 }
6007
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006008 status_t result = NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006009
Ana Krulec234bb162019-11-10 22:55:55 +01006010 postMessageSync(new LambdaMessage([&]() {
6011 const auto display = getDisplayDeviceLocked(displayToken);
6012 if (!display) {
6013 ALOGE("Attempt to set desired display configs for invalid display token %p",
6014 displayToken.get());
6015 } else if (display->isVirtual()) {
6016 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006017 result = INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006018 } else {
Steven Thomasd4071902020-03-24 16:02:53 -07006019 result = setDesiredDisplayConfigSpecsInternal(display,
6020 scheduler::RefreshRateConfigs::
6021 Policy{HwcConfigIndexType(
6022 defaultConfig),
6023 minRefreshRate,
6024 maxRefreshRate},
6025 /*overridePolicy=*/false);
Ana Krulec234bb162019-11-10 22:55:55 +01006026 }
6027 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006028
6029 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01006030}
6031
6032status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006033 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01006034 float* outMinRefreshRate,
6035 float* outMaxRefreshRate) {
6036 ATRACE_CALL();
6037
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006038 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01006039 return BAD_VALUE;
6040 }
6041
6042 Mutex::Autolock lock(mStateLock);
6043 const auto display = getDisplayDeviceLocked(displayToken);
6044 if (!display) {
6045 return NAME_NOT_FOUND;
6046 }
6047
6048 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006049 scheduler::RefreshRateConfigs::Policy policy =
6050 mRefreshRateConfigs->getDisplayManagerPolicy();
6051 *outDefaultConfig = policy.defaultConfig.value();
6052 *outMinRefreshRate = policy.minRefreshRate;
6053 *outMaxRefreshRate = policy.maxRefreshRate;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006054 return NO_ERROR;
6055 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006056 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006057 } else {
6058 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006059 LOG_FATAL_IF(!displayId);
6060
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006061 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6062 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6063 *outMinRefreshRate = 1e9f / vsyncPeriod;
6064 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6065 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006066 }
Ana Krulec0782b882019-10-15 17:34:54 -07006067}
6068
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006069void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006070 mFlinger->setInputWindowsFinished();
6071}
6072
Robert Carrc0df3122019-04-11 13:18:21 -07006073sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006074 BBinder* b = nullptr;
6075 if (handle) {
6076 b = handle->localBinder();
6077 }
Robert Carrc0df3122019-04-11 13:18:21 -07006078 if (b == nullptr) {
6079 return nullptr;
6080 }
6081 auto it = mLayersByLocalBinderToken.find(b);
6082 if (it != mLayersByLocalBinderToken.end()) {
6083 return it->second.promote();
6084 }
6085 return nullptr;
6086}
6087
Dominik Laskowski75848362019-11-11 17:57:20 -08006088void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006089 mNumLayers++;
6090 mScheduler->registerLayer(layer);
6091}
6092
6093void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6094 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006095 removeFromOffscreenLayers(layer);
6096}
6097
6098// WARNING: ONLY CALL THIS FROM LAYER DTOR
6099// Here we add children in the current state to offscreen layers and remove the
6100// layer itself from the offscreen layer list. Since
6101// this is the dtor, it is safe to access the current state. This keeps us
6102// from dangling children layers such that they are not reachable from the
6103// Drawing state nor the offscreen layer list
6104// See b/141111965
6105void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6106 for (auto& child : layer->getCurrentChildren()) {
6107 mOffscreenLayers.emplace(child.get());
6108 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006109 mOffscreenLayers.erase(layer);
6110}
6111
Alec Mouri4545a8a2019-08-08 20:05:32 -07006112void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6113 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6114}
6115
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006116status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6117 float lightPosY, float lightPosZ,
6118 float lightRadius) {
6119 Mutex::Autolock _l(mStateLock);
6120 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6121 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6122 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6123 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6124 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6125
6126 // these values are overridden when calculating the shadow settings for a layer.
6127 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6128 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006129 return NO_ERROR;
6130}
6131
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006132const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6133 const {
6134 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6135 // on the work to remove the table in that bug rather than adding more to
6136 // it.
6137 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6138 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6139 // supported, and exposed via the
6140 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6141 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6142 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6143 };
6144 return genericLayerMetadataKeyMap;
6145}
6146
Steven Thomas62a4cf82020-01-31 12:04:03 -08006147status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6148 int8_t compatibility) {
6149 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6150 return BAD_VALUE;
6151 }
6152
Ady Abraham60e42ea2020-03-09 19:17:31 -07006153 postMessageAsync(new LambdaMessage([=]() NO_THREAD_SAFETY_ANALYSIS {
6154 Mutex::Autolock lock(mStateLock);
6155 if (authenticateSurfaceTextureLocked(surface)) {
6156 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6157 if (layer->setFrameRate(
6158 Layer::FrameRate(frameRate,
6159 Layer::FrameRate::convertCompatibility(compatibility)))) {
6160 setTransactionFlags(eTraversalNeeded);
6161 }
6162 } else {
6163 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6164 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006165 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006166 return NO_ERROR;
6167 }));
6168
Steven Thomas62a4cf82020-01-31 12:04:03 -08006169 return NO_ERROR;
6170}
6171
Steven Thomasd4071902020-03-24 16:02:53 -07006172status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6173 if (!outToken) {
6174 return BAD_VALUE;
6175 }
6176 status_t result = NO_ERROR;
6177 postMessageSync(new LambdaMessage([&]() {
6178 if (mFrameRateFlexibilityTokenCount == 0) {
6179 // |mStateLock| not needed as we are on the main thread
6180 const auto display = getDefaultDisplayDeviceLocked();
6181
6182 // This is a little racy, but not in a way that hurts anything. As we grab the
6183 // defaultConfig from the display manager policy, we could be setting a new display
6184 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6185 // matter for the override policy though, since we set allowGroupSwitching to true, so
6186 // it's not a problem.
6187 scheduler::RefreshRateConfigs::Policy overridePolicy;
6188 overridePolicy.defaultConfig =
6189 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6190 overridePolicy.allowGroupSwitching = true;
6191 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy,
6192 /*overridePolicy=*/true);
6193 }
6194
6195 if (result == NO_ERROR) {
6196 mFrameRateFlexibilityTokenCount++;
6197 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6198 // below, is something to consider carefully. The lifetime of the
6199 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6200 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6201 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6202 // in this case, for two reasons:
6203 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6204 // the program exits is via a crash. So we won't have a situation where the
6205 // SurfaceFlinger object is dead but the process is still up.
6206 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6207 // if condition 1 were changed, the problem would only show up when running CTS tests,
6208 // not on end user devices, so we could spot it and fix it without serious impact.
6209 *outToken = new FrameRateFlexibilityToken(
6210 [this]() { onFrameRateFlexibilityTokenReleased(); });
6211 ALOGD("Frame rate flexibility token acquired. count=%d",
6212 mFrameRateFlexibilityTokenCount);
6213 }
6214 }));
6215 return result;
6216}
6217
6218void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
6219 postMessageAsync(new LambdaMessage([&]() {
6220 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6221 "Failed tracking frame rate flexibility tokens");
6222 mFrameRateFlexibilityTokenCount--;
6223 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6224 if (mFrameRateFlexibilityTokenCount == 0) {
6225 // |mStateLock| not needed as we are on the main thread
6226 const auto display = getDefaultDisplayDeviceLocked();
6227 status_t result =
6228 setDesiredDisplayConfigSpecsInternal(display, {}, /*overridePolicy=*/true);
6229 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6230 }
6231 }));
6232}
6233
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006234} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006235
Mathias Agopian3f844832013-08-07 21:24:32 -07006236#if defined(__gl_h_)
6237#error "don't include gl/gl.h in this file"
6238#endif
6239
6240#if defined(__gl2_h_)
6241#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006242#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006243
6244// TODO(b/129481165): remove the #pragma below and fix conversion issues
6245#pragma clang diagnostic pop // ignored "-Wconversion"