blob: 27fe0187b6d7d8d3b535795e4d5f1b2723a2b601 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri5f487d42020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri5f487d42020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri5f487d42020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
Dominik Laskowski5690bde2020-04-23 19:04:22 -0700111#include "Promise.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800112#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700113#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700114#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700115#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700116#include "Scheduler/EventControlThread.h"
117#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700118#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700119#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700120#include "Scheduler/Scheduler.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800121#include "StartPropertySetThread.h"
122#include "SurfaceFlingerProperties.h"
123#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800124#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700125#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800126#include "android-base/stringprintf.h"
127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700129
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700130using namespace std::string_literals;
131
Jaesoo Lee43518572017-01-23 19:03:16 +0900132using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900133using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900134using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800135
Ady Abraham8532d012019-05-08 14:50:56 -0700136using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800137using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700138using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700139using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800140using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700141using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700142using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900143
Peiyong Line9d809e2020-04-14 13:10:48 -0700144namespace hal = android::hardware::graphics::composer::hal;
145
Steven Thomasb02664d2017-07-26 18:48:28 -0700146namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700147
148#pragma clang diagnostic push
149#pragma clang diagnostic error "-Wswitch-enum"
150
151bool isWideColorMode(const ColorMode colorMode) {
152 switch (colorMode) {
153 case ColorMode::DISPLAY_P3:
154 case ColorMode::ADOBE_RGB:
155 case ColorMode::DCI_P3:
156 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700157 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700158 case ColorMode::BT2100_PQ:
159 case ColorMode::BT2100_HLG:
160 return true;
161 case ColorMode::NATIVE:
162 case ColorMode::STANDARD_BT601_625:
163 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
164 case ColorMode::STANDARD_BT601_525:
165 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
166 case ColorMode::STANDARD_BT709:
167 case ColorMode::SRGB:
168 return false;
169 }
170 return false;
171}
172
173#pragma clang diagnostic pop
174
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700175template <typename Mutex>
176struct ConditionalLockGuard {
177 ConditionalLockGuard(Mutex& mutex, bool lock) : mutex(mutex), lock(lock) {
178 if (lock) mutex.lock();
Steven Thomasb02664d2017-07-26 18:48:28 -0700179 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700180
181 ~ConditionalLockGuard() {
182 if (lock) mutex.unlock();
183 }
184
185 Mutex& mutex;
186 const bool lock;
Steven Thomasb02664d2017-07-26 18:48:28 -0700187};
Peiyong Linfca547f2018-07-09 13:03:33 -0700188
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700189using ConditionalLock = ConditionalLockGuard<Mutex>;
190
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800191// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
192constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
193
194float getDensityFromProperty(const char* property, bool required) {
195 char value[PROPERTY_VALUE_MAX];
196 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
197 if (!density && required) {
198 ALOGE("%s must be defined as a build property", property);
199 return FALLBACK_DENSITY;
200 }
201 return density / 160.f;
202}
203
Peiyong Lin9d846a52018-11-05 13:18:20 -0800204// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
205bool validateCompositionDataspace(Dataspace dataspace) {
206 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
207}
208
Steven Thomasd4071902020-03-24 16:02:53 -0700209class FrameRateFlexibilityToken : public BBinder {
210public:
211 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
212 virtual ~FrameRateFlexibilityToken() { mCallback(); }
213
214private:
215 std::function<void()> mCallback;
216};
217
Steven Thomasb02664d2017-07-26 18:48:28 -0700218} // namespace anonymous
219
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220// ---------------------------------------------------------------------------
221
Mathias Agopian99b49842011-06-27 16:05:52 -0700222const String16 sHardwareTest("android.permission.HARDWARE_TEST");
223const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
224const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
225const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800226const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700227
228// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700229int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700230bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800231uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800232bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800233bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800234int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100235uint32_t SurfaceFlinger::maxGraphicsWidth;
236uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600237bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800238ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700239bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700240bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700241Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
242ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
243Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
244ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800245bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700246
Kalle Raitaa099a242017-01-11 11:17:29 -0800247std::string getHwcServiceName() {
248 char value[PROPERTY_VALUE_MAX] = {};
249 property_get("debug.sf.hwc_service_name", value, "default");
250 ALOGI("Using HWComposer service: '%s'", value);
251 return std::string(value);
252}
253
254bool useTrebleTestingOverride() {
255 char value[PROPERTY_VALUE_MAX] = {};
256 property_get("debug.sf.treble_testing_override", value, "false");
257 ALOGI("Treble testing override: '%s'", value);
258 return std::string(value) == "true";
259}
260
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800261std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
262 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800263 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700264 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800265 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700266 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800267 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700268 return std::string("Enhanced");
269 default:
270 return std::string("Unknown ") +
271 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800272 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800273}
274
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700275SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800276
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700277SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
278 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700279 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700280 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700281 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700282 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700283 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800284 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
285 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800286
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700287SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800288 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700293
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900294 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700295
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900296 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800297
Steven Thomas050b2c82017-03-06 11:45:16 -0800298 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800302
Brian Lindahla13f2d52020-03-05 11:54:17 +0100303 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
304 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 mDefaultCompositionDataspace =
311 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700312 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
313 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 defaultCompositionDataspace = mDefaultCompositionDataspace;
315 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
316 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
317 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
318 wideColorGamutCompositionPixelFormat =
319 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700320
Yichi Chenda901bf2019-06-28 14:58:27 +0800321 mColorSpaceAgnosticDataspace =
322 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
323
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900324 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800325
Dominik Laskowski718f9602019-11-09 20:01:35 -0800326 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
327 switch (primary_display_orientation(Values::ORIENTATION_0)) {
328 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800329 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800330 case Values::ORIENTATION_90:
331 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800332 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800333 case Values::ORIENTATION_180:
334 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800336 case Values::ORIENTATION_270:
337 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800338 break;
339 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800340 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800341
Sundong Ahn85131bd2019-02-18 15:51:53 +0900342 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344 // debugging stuff...
345 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700346
Mathias Agopianb4b17302013-03-20 18:36:41 -0700347 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700348 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700349
Alec Mouri5f487d42020-02-06 09:26:19 -0800350 property_get("ro.build.type", value, "user");
351 mIsUserBuild = strcmp(value, "user") == 0;
352
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353 property_get("debug.sf.showupdates", value, "0");
354 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700355
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700356 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000357
358 // DDMS debugging deprecated (b/120782499)
359 property_get("debug.sf.ddms", value, "0");
360 int debugDdms = atoi(value);
361 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700362
363 property_get("debug.sf.disable_backpressure", value, "0");
364 mPropagateBackpressure = !atoi(value);
365 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700366
Ady Abrahamadb9a992019-09-19 21:21:55 +0000367 property_get("debug.sf.enable_gl_backpressure", value, "0");
368 mPropagateBackpressureClientComposition = atoi(value);
369 ALOGI_IF(mPropagateBackpressureClientComposition,
370 "Enabling backpressure propagation for Client Composition");
371
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800372 property_get("debug.sf.enable_hwc_vds", value, "0");
373 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800374 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800375
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800376 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800377 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800378 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700379
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800380 property_get("ro.surface_flinger.supports_background_blur", value, "0");
381 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700382 mSupportsBlur = supportsBlurs;
383 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800384 property_get("ro.sf.blurs_are_expensive", value, "0");
385 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800386
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800387 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700388 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
389 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800390 mGraphicBufferProducerListSizeLogThreshold =
391 std::max(static_cast<int>(0.95 *
392 static_cast<double>(mMaxGraphicBufferProducerListSize)),
393 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700394
Dan Stozaec460082018-12-17 15:35:09 -0800395 property_get("debug.sf.luma_sampling", value, "1");
396 mLumaSampling = atoi(value);
397
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800398 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800399 mDisableClientCompositionCache = atoi(value);
400
Romain Guy11d63f42017-07-20 12:47:14 -0700401 // We should be reading 'persist.sys.sf.color_saturation' here
402 // but since /data may be encrypted, we need to wait until after vold
403 // comes online to attempt to read the property. The property is
404 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800405
406 if (useTrebleTestingOverride()) {
407 // Without the override SurfaceFlinger cannot connect to HIDL
408 // services that are not listed in the manifests. Considered
409 // deriving the setting from the set service name, but it
410 // would be brittle if the name that's not 'default' is used
411 // for production purposes later on.
412 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
413 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800414
415 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800416}
417
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700418SurfaceFlinger::~SurfaceFlinger() = default;
419
420void SurfaceFlinger::onFirstRef() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800421 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422}
423
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700424void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700426 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427
Andy McFadden13a082e2012-08-24 10:16:42 -0700428 // restore initial conditions (default device unblank, etc)
429 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430
431 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700432 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433}
434
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700435void SurfaceFlinger::run() {
436 while (true) {
437 mEventQueue->waitMessage();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800438 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700439}
440
441template <typename F, typename T>
442inline std::future<T> SurfaceFlinger::schedule(F&& f) {
443 auto [task, future] = makeTask(std::move(f));
444 mEventQueue->postMessage(std::move(task));
445 return std::move(future);
Robert Carr1db73f62016-12-21 12:58:51 -0800446}
447
448sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700449 const sp<Client> client = new Client(this);
450 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800451}
452
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700453sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700454 class DisplayToken : public BBinder {
455 sp<SurfaceFlinger> flinger;
456 virtual ~DisplayToken() {
457 // no more references, this display must be terminated
458 Mutex::Autolock _l(flinger->mStateLock);
459 flinger->mCurrentState.displays.removeItem(this);
460 flinger->setTransactionFlags(eDisplayTransactionNeeded);
461 }
462 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700463 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464 : flinger(flinger) {
465 }
466 };
467
468 sp<BBinder> token = new DisplayToken(this);
469
470 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700471 // Display ID is assigned when virtual display is allocated by HWC.
472 DisplayDeviceState state;
473 state.isSecure = secure;
474 state.displayName = displayName;
475 mCurrentState.displays.add(token, state);
476 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 return token;
478}
479
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700480void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700481 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700482
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700483 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700485 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700486 return;
487 }
488
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700490 if (state.physical) {
491 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 return;
493 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494 mInterceptor->saveDisplayDeletion(state.sequenceId);
495 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700496 setTransactionFlags(eDisplayTransactionNeeded);
497}
498
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800499std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
500 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700501
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800502 const auto internalDisplayId = getInternalDisplayIdLocked();
503 if (!internalDisplayId) {
504 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700505 }
506
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800507 std::vector<PhysicalDisplayId> displayIds;
508 displayIds.reserve(mPhysicalDisplayTokens.size());
509 displayIds.push_back(internalDisplayId->value);
510
511 for (const auto& [id, token] : mPhysicalDisplayTokens) {
512 if (id != *internalDisplayId) {
513 displayIds.push_back(id.value);
514 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700515 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700516
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800517 return displayIds;
518}
519
520sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
521 Mutex::Autolock lock(mStateLock);
522 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523}
524
Ady Abraham37965d42018-11-01 13:43:32 -0700525status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
526 if (!outGetColorManagement) {
527 return BAD_VALUE;
528 }
529 *outGetColorManagement = useColorManagement;
530 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700531}
532
Lloyd Pique441d5042018-10-18 16:49:51 -0700533HWComposer& SurfaceFlinger::getHwComposer() const {
534 return mCompositionEngine->getHwComposer();
535}
536
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700537renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
538 return mCompositionEngine->getRenderEngine();
539}
540
Lloyd Pique70d91362018-10-18 16:02:55 -0700541compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
542 return *mCompositionEngine.get();
543}
544
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800545void SurfaceFlinger::bootFinished()
546{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700547 if (mBootFinished == true) {
548 ALOGE("Extra call to bootFinished");
549 return;
550 }
551 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700552 if (mStartPropertySetThread->join() != NO_ERROR) {
553 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800554 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800555 const nsecs_t now = systemTime();
556 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000557 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700558
Mikael Pessa90092f42019-08-26 17:22:04 -0700559 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000560 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700561
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 // wait patiently for the window manager death
563 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700564 mWindowManager = defaultServiceManager()->getService(name);
565 if (mWindowManager != 0) {
566 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700567 }
Robert Carr720e5062018-07-30 17:45:14 -0700568 sp<IBinder> input(defaultServiceManager()->getService(
569 String16("inputflinger")));
570 if (input == nullptr) {
571 ALOGE("Failed to link to input service");
572 } else {
573 mInputFlinger = interface_cast<IInputFlinger>(input);
574 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700575
Steven Thomas050b2c82017-03-06 11:45:16 -0800576 if (mVrFlinger) {
577 mVrFlinger->OnBootFinished();
578 }
579
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700580 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700581 // formerly we would just kill the process, but we now ask it to exit so it
582 // can choose where to stop the animation.
583 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700584
585 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
586 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
587 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700588
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700589 static_cast<void>(schedule([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800590 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700591 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800592 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800593
Ady Abraham8a82ba62020-01-17 12:43:17 -0800594 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
595 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
596 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
597 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800598 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800599}
600
Dan Stoza436ccf32018-06-21 12:10:12 -0700601uint32_t SurfaceFlinger::getNewTexture() {
602 {
603 std::lock_guard lock(mTexturePoolMutex);
604 if (!mTexturePool.empty()) {
605 uint32_t name = mTexturePool.back();
606 mTexturePool.pop_back();
607 ATRACE_INT("TexturePoolSize", mTexturePool.size());
608 return name;
609 }
610
611 // The pool was too small, so increase it for the future
612 ++mTexturePoolSize;
613 }
614
615 // The pool was empty, so we need to get a new texture name directly using a
616 // blocking call to the main thread
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700617 return schedule([this] {
618 uint32_t name = 0;
619 getRenderEngine().genTextures(1, &name);
620 return name;
621 })
622 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700623}
624
Mathias Agopian3f844832013-08-07 21:24:32 -0700625void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700626 std::lock_guard lock(mTexturePoolMutex);
627 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
628 // to actually delete this or not based on mTexturePoolSize
629 mTexturePool.push_back(texture);
630 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700631}
632
Wei Wangf9b05ee2017-07-19 20:59:39 -0700633// Do not call property_set on main thread which will be blocked by init
634// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700635void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700636 ALOGI( "SurfaceFlinger's main thread ready to run. "
637 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700638 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800639
Steven Thomasb02664d2017-07-26 18:48:28 -0700640 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700641 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800642 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700643 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
644 renderengine::RenderEngineCreationArgs::Builder()
645 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
646 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
647 .setUseColorManagerment(useColorManagement)
648 .setEnableProtectedContext(enable_protected_contents(false))
649 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700650 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700651 .setContextPriority(useContextPriority
652 ? renderengine::RenderEngine::ContextPriority::HIGH
653 : renderengine::RenderEngine::ContextPriority::MEDIUM)
654 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800655 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700656
657 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
658 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700659 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800660 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800661 // Process any initial hotplug and resulting display changes.
662 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700663 const auto display = getDefaultDisplayDeviceLocked();
664 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700665 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700666 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800667
Steven Thomas050b2c82017-03-06 11:45:16 -0800668 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700669 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700670 // This callback is called from the vr flinger dispatch thread. We
671 // need to call signalTransaction(), which requires holding
672 // mStateLock when we're not on the main thread. Acquiring
673 // mStateLock from the vr flinger dispatch thread might trigger a
674 // deadlock in surface flinger (see b/66916578), so post a message
675 // to be handled on the main thread instead.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700676 static_cast<void>(schedule([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700677 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
678 mVrFlingerRequestsDisplay = requestDisplay;
679 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700680 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800681 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
683 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700684 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700685 .value_or(0),
686 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 if (!mVrFlinger) {
688 ALOGE("Failed to start vrflinger");
689 }
690 }
691
Mathias Agopian92a979a2012-08-02 18:32:23 -0700692 // initialize our drawing state
693 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700694
Andy McFadden13a082e2012-08-24 10:16:42 -0700695 // set initial conditions (e.g. unblank default device)
696 initializeDisplays();
697
Steven Thomas137d4bc2019-07-25 16:55:14 -0700698 char primeShaderCache[PROPERTY_VALUE_MAX];
699 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
700 if (atoi(primeShaderCache)) {
701 getRenderEngine().primeCache();
702 }
Dan Stoza4e637772016-07-28 13:31:51 -0700703
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700705
706 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700707 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700708 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709
710 if (mStartPropertySetThread->Start() != NO_ERROR) {
711 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800713
Dan Stoza9e56aa02015-11-02 13:00:03 -0800714 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700715}
716
Romain Guy11d63f42017-07-20 12:47:14 -0700717void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700718 Mutex::Autolock _l(mStateLock);
719
Romain Guy11d63f42017-07-20 12:47:14 -0700720 char value[PROPERTY_VALUE_MAX];
721
722 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800723 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700724 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800725 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100726
727 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700728 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800729
730 property_get("persist.sys.sf.color_mode", value, "0");
731 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700732
733 property_get("persist.sys.sf.disable_blurs", value, "0");
734 bool disableBlurs = atoi(value);
735 mDisableBlurs = disableBlurs;
736 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700737}
738
Mathias Agopiana67e4182012-06-19 17:26:12 -0700739void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800740 // Start boot animation service by setting a property mailbox
741 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800743 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 if (mStartPropertySetThread->join() != NO_ERROR) {
745 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800746 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700747}
748
Mathias Agopian875d8e12013-06-07 15:35:48 -0700749size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700750 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700754 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800757// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800758
Jamie Gennis582270d2011-08-17 18:19:00 -0700759bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800760 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800761 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800762 return authenticateSurfaceTextureLocked(bufferProducer);
763}
764
765bool SurfaceFlinger::authenticateSurfaceTextureLocked(
766 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800767 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800768 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800769}
770
Brian Anderson6b376712017-04-04 10:51:39 -0700771status_t SurfaceFlinger::getSupportedFrameTimestamps(
772 std::vector<FrameEvent>* outSupported) const {
773 *outSupported = {
774 FrameEvent::REQUESTED_PRESENT,
775 FrameEvent::ACQUIRE,
776 FrameEvent::LATCH,
777 FrameEvent::FIRST_REFRESH_START,
778 FrameEvent::LAST_REFRESH_START,
779 FrameEvent::GPU_COMPOSITION_DONE,
780 FrameEvent::DEQUEUE_READY,
781 FrameEvent::RELEASE,
782 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700783 ConditionalLock _l(mStateLock,
784 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700785 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700786 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
787 }
788 return NO_ERROR;
789}
790
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800791status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
792 if (!displayToken || !state) {
793 return BAD_VALUE;
794 }
795
796 Mutex::Autolock lock(mStateLock);
797
798 const auto display = getDisplayDeviceLocked(displayToken);
799 if (!display) {
800 return NAME_NOT_FOUND;
801 }
802
803 state->layerStack = display->getLayerStack();
804 state->orientation = display->getOrientation();
805
806 const Rect viewport = display->getViewport();
807 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
808
809 return NO_ERROR;
810}
811
812status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
813 if (!displayToken || !info) {
814 return BAD_VALUE;
815 }
816
817 Mutex::Autolock lock(mStateLock);
818
819 const auto display = getDisplayDeviceLocked(displayToken);
820 if (!display) {
821 return NAME_NOT_FOUND;
822 }
823
Dominik Laskowski55c85402020-01-21 16:25:47 -0800824 if (const auto connectionType = display->getConnectionType())
825 info->connectionType = *connectionType;
826 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800827 return INVALID_OPERATION;
828 }
829
830 if (mEmulatedDisplayDensity) {
831 info->density = mEmulatedDisplayDensity;
832 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800833 info->density = info->connectionType == DisplayConnectionType::Internal
834 ? mInternalDisplayDensity
835 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800836 }
837
838 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200839 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800840
841 return NO_ERROR;
842}
843
Dominik Laskowski22488f62019-03-28 09:53:04 -0700844status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800845 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700846 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 return BAD_VALUE;
848 }
849
Dominik Laskowski22488f62019-03-28 09:53:04 -0700850 Mutex::Autolock lock(mStateLock);
851
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800852 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700853 if (!displayId) {
854 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700855 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700856
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800857 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700858
Dan Stoza7f7da322014-05-02 15:26:25 -0700859 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700860
Dominik Laskowski075d3172018-05-24 15:50:06 -0700861 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800862 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700863
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800864 auto width = hwConfig->getWidth();
865 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700866
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800867 auto xDpi = hwConfig->getDpiX();
868 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700869
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800870 if (isInternal &&
871 (internalDisplayOrientation == ui::ROTATION_90 ||
872 internalDisplayOrientation == ui::ROTATION_270)) {
873 std::swap(width, height);
874 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 }
876
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800877 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800878
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800879 if (mEmulatedDisplayDensity) {
880 config.xDpi = mEmulatedDisplayDensity;
881 config.yDpi = mEmulatedDisplayDensity;
882 } else {
883 config.xDpi = xDpi;
884 config.yDpi = yDpi;
885 }
886
887 const nsecs_t period = hwConfig->getVsyncPeriod();
888 config.refreshRate = 1e9f / period;
889
890 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
891 config.appVsyncOffset = offsets.late.app;
892 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800893 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894
Andy McFadden91b2ca82014-06-13 14:04:23 -0700895 // This is how far in advance a buffer must be queued for
896 // presentation at a given time. If you want a buffer to appear
897 // on the screen at time N, you must submit the buffer before
898 // (N - presentationDeadline).
899 //
900 // Normally it's one full refresh period (to give SF a chance to
901 // latch the buffer), but this can be reduced by configuring a
902 // DispSync offset. Any additional delays introduced by the hardware
903 // composer or panel must be accounted for here.
904 //
905 // We add an additional 1ms to allow for processing time and
906 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800907 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700908
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800909 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700910 }
911
Dan Stoza7f7da322014-05-02 15:26:25 -0700912 return NO_ERROR;
913}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700914
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700915status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
916 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700917 return BAD_VALUE;
918 }
919
Ana Krulecc2870422019-01-29 19:00:58 -0800920 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700921 return NO_ERROR;
922}
923
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700925 int activeConfig;
926 bool isPrimary;
927
928 {
929 Mutex::Autolock lock(mStateLock);
930
931 if (const auto display = getDisplayDeviceLocked(displayToken)) {
932 activeConfig = display->getActiveConfig().value();
933 isPrimary = display->isPrimary();
934 } else {
935 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
936 return NAME_NOT_FOUND;
937 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800938 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700939
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700940 if (isPrimary) {
Steven Thomasc9098452019-09-30 17:15:05 -0700941 std::lock_guard<std::mutex> lock(mActiveConfigLock);
942 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800943 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700944 }
Steven Thomasc9098452019-09-30 17:15:05 -0700945 }
Ady Abraham2139f732019-11-13 18:56:40 -0800946
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700947 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700948}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700949
Ady Abraham03b02dd2019-03-21 15:40:11 -0700950void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800951 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800952 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700953 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800954
Ady Abrahamb838aed2019-02-12 15:30:16 -0800955 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800956 if (mDesiredActiveConfigChanged) {
957 // If a config change is pending, just cache the latest request in
958 // mDesiredActiveConfig
959 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
960 mDesiredActiveConfig = info;
961 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
962 } else {
963 // Check is we are already at the desired config
964 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700965 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800966 return;
967 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800968
Ady Abraham59db0a32020-03-02 18:04:20 -0800969 // Initiate a config change.
970 mDesiredActiveConfigChanged = true;
971 mDesiredActiveConfig = info;
972
Ady Abrahamb838aed2019-02-12 15:30:16 -0800973 // This will trigger HWC refresh without resetting the idle timer.
974 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700975 // Start receiving vsync samples now, so that we can detect a period
976 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700977 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700978 // As we called to set period, we will call to onRefreshRateChangeCompleted once
979 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700980 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800981
Ady Abrahamabc27602020-04-08 17:20:29 -0700982 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800983 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800984 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700985
986 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800987 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700988 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989}
990
991status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
992 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800993
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100994 if (!displayToken) {
995 return BAD_VALUE;
996 }
Ady Abraham838de062019-02-04 10:24:03 -0800997
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700998 auto future = schedule([=]() -> status_t {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100999 const auto display = getDisplayDeviceLocked(displayToken);
1000 if (!display) {
1001 ALOGE("Attempt to set allowed display configs for invalid display token %p",
1002 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001003 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001004 } else if (display->isVirtual()) {
1005 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001006 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001007 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001008 const HwcConfigIndexType config(mode);
1009 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
1010 const scheduler::RefreshRateConfigs::Policy policy{config, fps, fps};
1011 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001012
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001013 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1014 }
1015 });
1016
1017 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001018}
1019
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020void SurfaceFlinger::setActiveConfigInternal() {
1021 ATRACE_CALL();
1022
Dominik Laskowski22488f62019-03-28 09:53:04 -07001023 const auto display = getDefaultDisplayDeviceLocked();
1024 if (!display) {
1025 return;
1026 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001027
Alec Mouri8de697e2020-03-19 10:52:01 -07001028 auto& oldRefreshRate =
1029 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1030
Dominik Laskowski22488f62019-03-28 09:53:04 -07001031 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001032 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001033 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001034 display->setActiveConfig(mUpcomingActiveConfig.configId);
1035
Ady Abraham2e1dd892020-03-05 13:48:36 -08001036 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001037 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001038 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001039 mTimeStats->incrementRefreshRateSwitches();
1040 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001041 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001042 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001043 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001044
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001045 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001046 const nsecs_t vsyncPeriod =
1047 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001048 .getVsyncPeriod();
Ady Abraham447052e2019-02-13 16:07:27 -08001049 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001050 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001051 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001052}
1053
Ady Abraham53852a52019-05-28 18:07:44 -07001054void SurfaceFlinger::desiredActiveConfigChangeDone() {
1055 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1056 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1057 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001058
Ady Abraham2e1dd892020-03-05 13:48:36 -08001059 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001060 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001061 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1062 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001063 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001064}
1065
Ady Abraham27cbed72020-04-10 12:56:59 -07001066void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001067 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001068 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001069 // Store the local variable to release the lock.
Ady Abraham27cbed72020-04-10 12:56:59 -07001070 const auto desiredActiveConfig = [&]() -> std::optional<ActiveConfigInfo> {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001071 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham27cbed72020-04-10 12:56:59 -07001072 if (mDesiredActiveConfigChanged) {
1073 return mDesiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001074 }
Ady Abraham27cbed72020-04-10 12:56:59 -07001075 return std::nullopt;
1076 }();
1077
1078 if (!desiredActiveConfig) {
1079 // No desired active config pending to be applied
1080 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001081 }
1082
Ady Abraham2e1dd892020-03-05 13:48:36 -08001083 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001084 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001085 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1086 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001087 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001088 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001089 // display is not valid or we are already in the requested mode
1090 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001091 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001092 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001093 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001094
Ady Abraham838de062019-02-04 10:24:03 -08001095 // Desired active config was set, it is different than the config currently in use, however
1096 // allowed configs might have change by the time we process the refresh.
1097 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001098 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001099 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001100 return;
Ady Abraham838de062019-02-04 10:24:03 -08001101 }
Alec Mouri7f015182019-07-11 13:56:22 -07001102
Ady Abraham27cbed72020-04-10 12:56:59 -07001103 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001104 const auto displayId = display->getId();
1105 LOG_ALWAYS_FATAL_IF(!displayId);
1106
Ady Abrahamabc27602020-04-08 17:20:29 -07001107 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001108
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001109 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001110 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001111 constraints.desiredTimeNanos = systemTime();
1112 constraints.seamlessRequired = false;
1113
Peiyong Line9d809e2020-04-14 13:10:48 -07001114 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001115 auto status =
1116 getHwComposer().setActiveConfigWithConstraints(*displayId,
1117 mUpcomingActiveConfig.configId.value(),
1118 constraints, &outTimeline);
1119 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001120 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1121 // to be sent. We just log the error in this case.
1122 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001123 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001124 }
1125
1126 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1127 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001128 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001129}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001130
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001131status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1132 Vector<ColorMode>* outColorModes) {
1133 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001134 return BAD_VALUE;
1135 }
1136
Peiyong Lina52f0292018-03-14 17:26:31 -07001137 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001138 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001139 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001140 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1141
1142 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1143 if (!displayId) {
1144 return NAME_NOT_FOUND;
1145 }
1146
Dominik Laskowski075d3172018-05-24 15:50:06 -07001147 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001148 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001149 }
Michael Wright28f24d02016-07-12 13:30:53 -07001150 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001151
1152 // If it's built-in display and the configuration claims it's not wide color capable,
1153 // filter out all wide color modes. The typical reason why this happens is that the
1154 // hardware is not good enough to support GPU composition of wide color, and thus the
1155 // OEMs choose to disable this capability.
1156 if (isInternalDisplay && !hasWideColorDisplay) {
1157 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1158 isWideColorMode);
1159 } else {
1160 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1161 }
Michael Wright28f24d02016-07-12 13:30:53 -07001162
1163 return NO_ERROR;
1164}
1165
Daniel Solomon42d04562019-01-20 21:03:19 -08001166status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1167 ui::DisplayPrimaries &primaries) {
1168 if (!displayToken) {
1169 return BAD_VALUE;
1170 }
1171
1172 // Currently we only support this API for a single internal display.
1173 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001174 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001175 }
1176
1177 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1178 return NO_ERROR;
1179}
1180
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001181ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001182 Mutex::Autolock lock(mStateLock);
1183
1184 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001185 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001186 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001187 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001188}
1189
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001190status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001191 schedule([=] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001192 Vector<ColorMode> modes;
1193 getDisplayColorModes(displayToken, &modes);
1194 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1195 if (mode < ColorMode::NATIVE || !exists) {
1196 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1197 decodeColorMode(mode).c_str(), mode, displayToken.get());
1198 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001199 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001200 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001201 if (!display) {
1202 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1203 decodeColorMode(mode).c_str(), mode, displayToken.get());
1204 } else if (display->isVirtual()) {
1205 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1206 decodeColorMode(mode).c_str(), mode);
1207 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001208 display->getCompositionDisplay()->setColorProfile(
1209 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1210 RenderIntent::COLORIMETRIC,
1211 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001212 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001213 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001214
Michael Wright28f24d02016-07-12 13:30:53 -07001215 return NO_ERROR;
1216}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001217
Galia Peycheva5492cb52019-10-30 14:13:16 +01001218status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1219 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001220 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001221 return BAD_VALUE;
1222 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001223
1224 Mutex::Autolock lock(mStateLock);
1225
Galia Peycheva5492cb52019-10-30 14:13:16 +01001226 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1227 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001228 return NAME_NOT_FOUND;
1229 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001230 *outSupport =
1231 getHwComposer().hasDisplayCapability(*displayId,
1232 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001233 return NO_ERROR;
1234}
1235
1236void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001237 static_cast<void>(schedule([=] {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001238 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1239 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1240 } else {
1241 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1242 }
1243 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001244}
1245
1246status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1247 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001248 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001249 return BAD_VALUE;
1250 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001251
1252 Mutex::Autolock lock(mStateLock);
1253
Galia Peycheva5492cb52019-10-30 14:13:16 +01001254 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1255 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001256 return NAME_NOT_FOUND;
1257 }
1258
Peiyong Line9d809e2020-04-14 13:10:48 -07001259 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001260 getHwComposer().getSupportedContentTypes(*displayId, &types);
1261
1262 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001263 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001264 return NO_ERROR;
1265}
1266
1267void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001268 static_cast<void>(schedule([=] {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001269 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001270 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001271 getHwComposer().setContentType(*displayId, type);
1272 } else {
1273 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1274 }
1275 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001276}
1277
Svetoslavd85084b2014-03-20 10:28:31 -07001278status_t SurfaceFlinger::clearAnimationFrameStats() {
1279 Mutex::Autolock _l(mStateLock);
1280 mAnimFrameTracker.clearStats();
1281 return NO_ERROR;
1282}
1283
1284status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1285 Mutex::Autolock _l(mStateLock);
1286 mAnimFrameTracker.getStats(outStats);
1287 return NO_ERROR;
1288}
1289
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001290status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1291 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001292 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001293
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001294 const auto display = getDisplayDeviceLocked(displayToken);
1295 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001296 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1297 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001298 }
1299
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001300 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001301 // meaning the luminance information is already queried from
1302 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001303 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001304 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1305 capabilities.getDesiredMaxLuminance(),
1306 capabilities.getDesiredMaxAverageLuminance(),
1307 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001308
1309 return NO_ERROR;
1310}
1311
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001312std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1313 const DisplayDevice& display) const {
1314 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1315 // avoid repetitive HAL IPC and EDID parsing.
1316 const auto displayId = display.getId();
1317 LOG_FATAL_IF(!displayId);
1318
1319 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1320 LOG_FATAL_IF(!hwcDisplayId);
1321
1322 uint8_t port;
1323 DisplayIdentificationData data;
1324 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1325 ALOGV("%s: No identification data.", __FUNCTION__);
1326 return {};
1327 }
1328
1329 const auto info = parseDisplayIdentificationData(port, data);
1330 if (!info) {
1331 return {};
1332 }
1333 return info->deviceProductInfo;
1334}
1335
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001336status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1337 ui::PixelFormat* outFormat,
1338 ui::Dataspace* outDataspace,
1339 uint8_t* outComponentMask) const {
1340 if (!outFormat || !outDataspace || !outComponentMask) {
1341 return BAD_VALUE;
1342 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001343
1344 Mutex::Autolock lock(mStateLock);
1345
1346 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1347 if (!displayId) {
1348 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001349 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001350
1351 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001352 outDataspace, outComponentMask);
1353}
1354
Kevin DuBois74e53772018-11-19 10:52:38 -08001355status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1356 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001357 uint64_t maxFrames) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001358 return schedule([=]() -> status_t {
1359 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1360 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1361 componentMask,
1362 maxFrames);
1363 } else {
1364 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1365 return NAME_NOT_FOUND;
1366 }
1367 })
1368 .get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001369}
1370
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001371status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1372 uint64_t maxFrames, uint64_t timestamp,
1373 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001374 Mutex::Autolock lock(mStateLock);
1375
1376 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1377 if (!displayId) {
1378 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001379 }
1380
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001381 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001382}
1383
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001384status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1385 if (!outSupported) {
1386 return BAD_VALUE;
1387 }
1388 *outSupported = getRenderEngine().supportsProtectedContent();
1389 return NO_ERROR;
1390}
1391
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001392status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1393 bool* outIsWideColorDisplay) const {
1394 if (!displayToken || !outIsWideColorDisplay) {
1395 return BAD_VALUE;
1396 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001397
1398 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001399 const auto display = getDisplayDeviceLocked(displayToken);
1400 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001401 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001402 }
Peiyong Linff84a152019-05-17 18:36:19 -07001403
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001404 *outIsWideColorDisplay =
1405 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001406 return NO_ERROR;
1407}
1408
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001409status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001410 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001411 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001412
Dominik Laskowski6505f792019-09-18 11:10:05 -07001413 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1414 mEventQueue->setEventConnection(
1415 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001416 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001417 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001418
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001419 return NO_ERROR;
1420}
1421
1422status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001423 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001424 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001425}
1426
Lloyd Pique755e3192018-01-31 16:46:15 -08001427status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1428 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001429 // Try to acquire a lock for 1s, fail gracefully
1430 const status_t err = mStateLock.timedLock(s2ns(1));
1431 const bool locked = (err == NO_ERROR);
1432 if (!locked) {
1433 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1434 return TIMED_OUT;
1435 }
1436
1437 outLayers->clear();
1438 mCurrentState.traverseInZOrder([&](Layer* layer) {
1439 outLayers->push_back(layer->getLayerDebugInfo());
1440 });
1441
1442 mStateLock.unlock();
1443 return NO_ERROR;
1444}
1445
Peiyong Linc6780972018-10-28 15:24:08 -07001446status_t SurfaceFlinger::getCompositionPreference(
1447 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1448 Dataspace* outWideColorGamutDataspace,
1449 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001450 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001451 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001452 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001453 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001454 return NO_ERROR;
1455}
1456
Dan Stozaec460082018-12-17 15:35:09 -08001457status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1458 const sp<IBinder>& stopLayerHandle,
1459 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001460 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001461 return BAD_VALUE;
1462 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001463
1464 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1465 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001466 return NO_ERROR;
1467}
1468
Dan Stozaec460082018-12-17 15:35:09 -08001469status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001470 if (!listener) {
1471 return BAD_VALUE;
1472 }
Dan Stozaec460082018-12-17 15:35:09 -08001473 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001474 return NO_ERROR;
1475}
Dan Gittik57e63c52019-01-18 16:37:54 +00001476
1477status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1478 bool* outSupport) const {
1479 if (!displayToken || !outSupport) {
1480 return BAD_VALUE;
1481 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001482
1483 Mutex::Autolock lock(mStateLock);
1484
Dan Gittik57e63c52019-01-18 16:37:54 +00001485 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1486 if (!displayId) {
1487 return NAME_NOT_FOUND;
1488 }
1489 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001490 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001491 return NO_ERROR;
1492}
1493
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001494status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001495 if (!displayToken) {
1496 return BAD_VALUE;
1497 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001498
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001499 return promise::chain(schedule([=] {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001500 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1501 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1502 } else {
1503 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001504 return promise::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001505 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001506 }))
1507 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001508 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001509}
1510
Ady Abraham8532d012019-05-08 14:50:56 -07001511status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1512 PowerHint powerHint = static_cast<PowerHint>(hintId);
1513
1514 if (powerHint == PowerHint::INTERACTION) {
1515 mScheduler->notifyTouchEvent();
1516 }
1517
1518 return NO_ERROR;
1519}
1520
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001521// ----------------------------------------------------------------------------
1522
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001523sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001524 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001525 const auto& handle =
1526 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001527
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001528 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001529}
1530
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001531void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001532 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001533 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001534 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001535}
1536
1537void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001538 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001539 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001540 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001541}
1542
1543void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001544 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001545 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001546}
1547
Dominik Laskowski83b88212018-12-11 13:34:06 -08001548nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001549 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001550 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1551 return 0;
1552 }
1553
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001554 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001555}
1556
Peiyong Line9d809e2020-04-14 13:10:48 -07001557void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001558 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001559 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001560 ATRACE_NAME("SF onVsync");
1561
Steven Thomas3cfac282017-02-06 12:29:30 -08001562 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001563 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001564 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001565 return;
1566 }
1567
Dominik Laskowski075d3172018-05-24 15:50:06 -07001568 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001569 return;
1570 }
1571
Dominik Laskowski075d3172018-05-24 15:50:06 -07001572 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001573 // For now, we don't do anything with external display vsyncs.
1574 return;
1575 }
1576
Alec Mourif8e689c2019-05-20 18:32:22 -07001577 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001578 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001579 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001580 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001581 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001582}
1583
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001584void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001585 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1586 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001587}
1588
Ady Abraham2139f732019-11-13 18:56:40 -08001589bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001590 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001591}
1592
Ady Abraham2139f732019-11-13 18:56:40 -08001593void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1594 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001595 const auto display = getDefaultDisplayDeviceLocked();
1596 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001597 return;
1598 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001599 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001600
Ana Krulec7d1d6832018-12-27 11:10:09 -08001601 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001602 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001603 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001604 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001605 return;
1606 }
1607
Ady Abrahamabc27602020-04-08 17:20:29 -07001608 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001609}
1610
Peiyong Line9d809e2020-04-14 13:10:48 -07001611void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
1612 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001613 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001614 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001615
Lloyd Piqueba04e622017-12-14 17:11:26 -08001616 // Ignore events that do not have the right sequenceId.
1617 if (sequenceId != getBE().mComposerSequenceId) {
1618 return;
1619 }
1620
Steven Thomasb02664d2017-07-26 18:48:28 -07001621 // Only lock if we're not on the main thread. This function is normally
1622 // called on a hwbinder thread, but for the primary display it's called on
1623 // the main thread with the state lock already held, so don't attempt to
1624 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001625 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001626
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001627 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001628
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001629 if (std::this_thread::get_id() == mMainThreadId) {
1630 // Process all pending hot plug events immediately if we are on the main thread.
1631 processDisplayHotplugEventsLocked();
1632 }
1633
Lloyd Piqueba04e622017-12-14 17:11:26 -08001634 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001635}
1636
Ady Abraham7159f572019-10-11 11:10:18 -07001637void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001638 int32_t sequenceId, hal::HWDisplayId /*display*/,
1639 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001640 Mutex::Autolock lock(mStateLock);
1641 if (sequenceId != getBE().mComposerSequenceId) {
1642 return;
1643 }
1644 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001645}
1646
Peiyong Line9d809e2020-04-14 13:10:48 -07001647void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001648 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1649 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1650}
1651
Peiyong Line9d809e2020-04-14 13:10:48 -07001652void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001653 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001654 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001655 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001656 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001657 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001658}
1659
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001660void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001661 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001662
1663 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1664 // display power state.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001665 static_cast<void>(
1666 schedule([=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001667}
1668
1669void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1670 ATRACE_CALL();
1671
Peiyong Line9d809e2020-04-14 13:10:48 -07001672 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001673
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001674 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001675 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1676 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001677 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001678 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001679 }
Mathias Agopian86303202012-07-24 22:46:10 -07001680}
1681
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001682// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001683void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001684 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001685 // Clear the drawing state so that the logic inside of
1686 // handleTransactionLocked will fire. It will determine the delta between
1687 // mCurrentState and mDrawingState and re-apply all changes when we make the
1688 // transition.
1689 mDrawingState.displays.clear();
1690 mDisplays.clear();
1691}
1692
Steven Thomas050b2c82017-03-06 11:45:16 -08001693void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001694 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001695 if (!mVrFlinger)
1696 return;
1697 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001698 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001699 return;
1700 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001701
Lloyd Pique441d5042018-10-18 16:49:51 -07001702 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001703 ALOGE("Vr flinger is only supported for remote hardware composer"
1704 " service connections. Ignoring request to transition to vr"
1705 " flinger.");
1706 mVrFlingerRequestsDisplay = false;
1707 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001708 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001709
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001710 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001711
Steven Thomas0123ac62018-07-12 11:32:34 -07001712 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001713 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001714
Peiyong Lin65248e02020-04-18 21:15:07 -07001715 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001716
1717 // Clear out all the output layers from the composition engine for all
1718 // displays before destroying the hardware composer interface. This ensures
1719 // any HWC layers are destroyed through that interface before it becomes
1720 // invalid.
1721 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001722 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001723 }
1724
Steven Thomas0123ac62018-07-12 11:32:34 -07001725 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1726 // called below. Clear the reference now so we don't accidentally use it
1727 // later.
1728 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001729
Steven Thomasb02664d2017-07-26 18:48:28 -07001730 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001731 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001732 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001733
Steven Thomasb02664d2017-07-26 18:48:28 -07001734 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001735 // Delete the current instance before creating the new one
1736 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1737 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1738 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001739 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001740
Lloyd Pique441d5042018-10-18 16:49:51 -07001741 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001742 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001743
1744 if (vrFlingerRequestsDisplay) {
1745 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001746 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001747
1748 mVisibleRegionsDirty = true;
1749 invalidateHwcGeometry();
1750
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001751 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001752 display = getDefaultDisplayDeviceLocked();
1753 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001754 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001755
Steven Thomasb02664d2017-07-26 18:48:28 -07001756 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001757 const nsecs_t vsyncPeriod = getVsyncPeriod();
1758 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001759
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001760 // The present fences returned from vr_hwc are not an accurate
1761 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001762 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001763
Steven Thomasb02664d2017-07-26 18:48:28 -07001764 // Use phase of 0 since phase is not known.
1765 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001766 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001767 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001768
Ana Krulecc2870422019-01-29 19:00:58 -08001769 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001770
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001771 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001772 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001773}
1774
Alec Mouri6d414b52020-03-17 11:18:05 -07001775sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001776 // We are storing the last 2 present fences. If sf's phase offset is to be
1777 // woken up before the actual vsync but targeting the next vsync, we need to check
1778 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001779 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1780 : mPreviousPresentFences[1];
1781}
1782
1783bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1784 ATRACE_CALL();
1785 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001786
Ady Abraham11579302019-09-19 12:35:58 -07001787 if (fence == Fence::NO_FENCE) {
1788 return false;
1789 }
1790
Dan Stoza59083052020-04-28 10:13:20 -07001791 const status_t status = fence->wait(graceTimeMs);
1792 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1793 // which calls wait(0) again internally
1794 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001795}
1796
Alec Mouri6d414b52020-03-17 11:18:05 -07001797nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1798 const sp<Fence>& fence = previousFrameFence();
1799
1800 if (fence == Fence::NO_FENCE) {
1801 return Fence::SIGNAL_TIME_INVALID;
1802 }
1803
1804 return fence->getSignalTime();
1805}
1806
Ady Abraham5facfb12020-04-22 15:18:31 -07001807nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001808 DisplayStatInfo stats;
1809 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001810 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001811 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001812 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001813}
1814
Ady Abraham5facfb12020-04-22 15:18:31 -07001815void SurfaceFlinger::onMessageReceived(int32_t what,
1816 nsecs_t expectedVSyncTime) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001817 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001818 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001819 case MessageQueue::INVALIDATE: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001820 onMessageInvalidate(expectedVSyncTime);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001821 break;
1822 }
1823 case MessageQueue::REFRESH: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001824 onMessageRefresh();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001825 break;
1826 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001827 }
1828}
1829
Dan Stoza28d46a52020-04-28 09:54:54 -07001830void SurfaceFlinger::onMessageInvalidate(nsecs_t expectedVSyncTime) NO_THREAD_SAFETY_ANALYSIS {
1831 ATRACE_CALL();
1832
1833 const nsecs_t frameStart = systemTime();
1834 // calculate the expected present time once and use the cached
1835 // value throughout this frame to make sure all layers are
1836 // seeing this same value.
1837 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
1838 mExpectedPresentTime = expectedVSyncTime;
1839
1840 // When Backpressure propagation is enabled we want to give a small grace period
1841 // for the present fence to fire instead of just giving up on this frame to handle cases
1842 // where present fence is just about to get signaled.
1843 const int graceTimeForPresentFenceMs =
1844 (mPropagateBackpressure &&
1845 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1846 ? 1
1847 : 0;
1848
1849 // Pending frames may trigger backpressure propagation.
1850 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1851 previousFramePending(graceTimeForPresentFenceMs)};
1852
1853 // Frame missed counts for metrics tracking.
1854 // A frame is missed if the prior frame is still pending. If no longer pending,
1855 // then we still count the frame as missed if the predicted present time
1856 // was further in the past than when the fence actually fired.
1857
1858 // Add some slop to correct for drift. This should generally be
1859 // smaller than a typical frame duration, but should not be so small
1860 // that it reports reasonable drift as a missed frame.
1861 DisplayStatInfo stats;
1862 mScheduler->getDisplayStatInfo(&stats);
1863 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1864 const nsecs_t previousPresentTime = previousFramePresentTime();
1865 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
1866 framePending ||
1867 (previousPresentTime >= 0 &&
1868 (lastExpectedPresentTime <
1869 previousPresentTime - frameMissedSlop))};
1870 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
1871 mHadDeviceComposition && frameMissed};
1872 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
1873 mHadClientComposition && frameMissed};
1874
1875 if (frameMissed) {
1876 mFrameMissedCount++;
1877 mTimeStats->incrementMissedFrames();
1878 if (mMissedFrameJankCount == 0) {
1879 mMissedFrameJankStart = systemTime();
1880 }
1881 mMissedFrameJankCount++;
1882 }
1883
1884 if (hwcFrameMissed) {
1885 mHwcFrameMissedCount++;
1886 }
1887
1888 if (gpuFrameMissed) {
1889 mGpuFrameMissedCount++;
1890 }
1891
1892 // If we are in the middle of a config change and the fence hasn't
1893 // fired yet just wait for the next invalidate
1894 if (mSetActiveConfigPending) {
1895 if (framePending) {
1896 mEventQueue->invalidate();
1897 return;
1898 }
1899
1900 // We received the present fence from the HWC, so we assume it successfully updated
1901 // the config, hence we update SF.
1902 mSetActiveConfigPending = false;
1903 setActiveConfigInternal();
1904 }
1905
1906 if (framePending && mPropagateBackpressure) {
1907 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
1908 signalLayerUpdate();
1909 return;
1910 }
1911 }
1912
1913 // Our jank window is always at least 100ms since we missed a
1914 // frame...
1915 static constexpr nsecs_t kMinJankyDuration =
1916 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1917 // ...but if it's larger than 1s then we missed the trace cutoff.
1918 static constexpr nsecs_t kMaxJankyDuration =
1919 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1920 // If we're in a user build then don't push any atoms
1921 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1922 const auto displayDevice = getDefaultDisplayDeviceLocked();
1923 // Only report jank when the display is on, as displays in DOZE
1924 // power mode may operate at a different frame rate than is
1925 // reported in their config, which causes noticeable (but less
1926 // severe) jank.
1927 if (displayDevice && displayDevice->getPowerMode() == hal::PowerMode::ON) {
1928 const nsecs_t currentTime = systemTime();
1929 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1930 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1931 ATRACE_NAME("Jank detected");
1932 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1933 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1934 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1935 jankyDurationMillis, mMissedFrameJankCount);
1936 }
1937
1938 // We either reported a jank event or we missed the trace
1939 // window, so clear counters here.
1940 if (jankDuration > kMinJankyDuration) {
1941 mMissedFrameJankCount = 0;
1942 mMissedFrameJankStart = 0;
1943 }
1944 }
1945 }
1946
1947 // Now that we're going to make it to the handleMessageTransaction()
1948 // call below it's safe to call updateVrFlinger(), which will
1949 // potentially trigger a display handoff.
1950 updateVrFlinger();
1951
1952 if (mTracingEnabledChanged) {
1953 mTracingEnabled = mTracing.isEnabled();
1954 mTracingEnabledChanged = false;
1955 }
1956
1957 bool refreshNeeded;
1958 {
1959 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1960
1961 refreshNeeded = handleMessageTransaction();
1962 refreshNeeded |= handleMessageInvalidate();
1963 if (mTracingEnabled) {
1964 mAddCompositionStateToTrace =
1965 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1966 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1967 mTracing.notifyLocked("visibleRegionsDirty");
1968 }
1969 }
1970 }
1971
1972 // Layers need to get updated (in the previous line) before we can use them for
1973 // choosing the refresh rate.
1974 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1975 // and may eventually call to ~Layer() if it holds the last reference
1976 {
1977 Mutex::Autolock _l(mStateLock);
1978 mScheduler->chooseRefreshRateForContent();
1979 }
1980
1981 performSetActiveConfig();
1982
1983 updateCursorAsync();
1984 updateInputFlinger();
1985
1986 refreshNeeded |= mRepaintEverything;
1987 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
1988 // Signal a refresh if a transaction modified the window state,
1989 // a new buffer was latched, or if HWC has requested a full
1990 // repaint
1991 if (mFrameStartTime <= 0) {
1992 // We should only use the time of the first invalidate
1993 // message that signals a refresh as the beginning of the
1994 // frame. Otherwise the real frame time will be
1995 // underestimated.
1996 mFrameStartTime = frameStart;
1997 }
1998 signalRefresh();
1999 }
2000}
2001
Dan Stoza6b9454d2014-11-07 16:00:59 -08002002bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08002003 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002004 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002005
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002006 bool flushedATransaction = flushTransactionQueues();
2007
2008 bool runHandleTransaction = transactionFlags &&
2009 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
2010
2011 if (runHandleTransaction) {
2012 handleTransaction(eTransactionMask);
2013 } else {
2014 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002015 }
2016
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002017 if (transactionFlushNeeded()) {
2018 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002019 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002020
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002021 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002022}
2023
Dan Stoza28d46a52020-04-28 09:54:54 -07002024void SurfaceFlinger::onMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002025 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002026
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002027 mRefreshPending = false;
2028
Lloyd Piqueab039b52019-02-13 14:22:42 -08002029 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002030 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002031 for (const auto& [_, display] : mDisplays) {
2032 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2033 }
2034 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002035 if (auto layerFE = layer->getCompositionEngineLayerFE())
2036 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002037 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002038 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2039 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002040 if (auto layerFE = layer->getCompositionEngineLayerFE())
2041 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002042 }
2043
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002044 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002045 refreshArgs.outputColorSetting = useColorManagement
2046 ? mDisplayColorSetting
2047 : compositionengine::OutputColorSetting::kUnmanaged;
2048 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2049 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002050
2051 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2052 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002053 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002054
2055 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2056 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2057 mDrawingState.colorMatrixChanged = false;
2058 }
2059
2060 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2061
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002062 if (mDebugRegion != 0) {
2063 refreshArgs.devOptFlashDirtyRegionsDelay =
2064 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2065 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002066
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002067 mGeometryInvalid = false;
2068
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002069 // Store the present time just before calling to the composition engine so we could notify
2070 // the scheduler.
2071 const auto presentTime = systemTime();
2072
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002073 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002074 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2075 // Reset the frame start time now that we've recorded this frame.
2076 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002077
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002078 mScheduler->onDisplayRefreshed(presentTime);
2079
David Sodmanfa9b2af2017-12-24 13:28:59 -08002080 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002081 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002082
Alec Mouri8f7a0102020-04-15 12:11:10 -07002083 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2084
Lloyd Pique66d68602019-02-13 14:23:31 -08002085 mHadClientComposition =
2086 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2087 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002088 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2089 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002090 });
2091 mHadDeviceComposition =
2092 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2093 auto& displayDevice = tokenDisplayPair.second;
2094 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2095 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002096 mReusedClientComposition =
2097 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2098 auto& displayDevice = tokenDisplayPair.second;
2099 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2100 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002101
Alec Mouri8f7a0102020-04-15 12:11:10 -07002102 // Only report a strategy change if we move in and out of composition with hw overlays
2103 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2104 mTimeStats->incrementCompositionStrategyChanges();
2105 }
2106
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002107 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002108
David Sodman7e4ae112018-02-09 15:02:28 -08002109 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002110 if (mVisibleRegionsDirty) {
2111 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002112 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002113 mTracing.notify("visibleRegionsDirty");
2114 }
2115 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002116
2117 if (mCompositionEngine->needsAnotherUpdate()) {
2118 signalLayerUpdate();
2119 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002120}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002121
David Sodmanfa9b2af2017-12-24 13:28:59 -08002122bool SurfaceFlinger::handleMessageInvalidate() {
2123 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002124 bool refreshNeeded = handlePageFlip();
2125
Vishnu Nair4351ad52019-02-11 14:13:02 -08002126 if (mVisibleRegionsDirty) {
2127 computeLayerBounds();
2128 }
2129
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002130 for (auto& layer : mLayersPendingRefresh) {
2131 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002132 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002133 invalidateLayerStack(layer, visibleReg);
2134 }
2135 mLayersPendingRefresh.clear();
2136 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002137}
2138
Ana Krulece588e312018-09-18 12:32:24 -07002139void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2140 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002141 // Update queue of past composite+present times and determine the
2142 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002143 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002144 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002145 while (!getBE().mCompositePresentTimes.empty()) {
2146 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002147 // Cached values should have been updated before calling this method,
2148 // which helps avoid duplicate syscalls.
2149 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2150 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2151 break;
2152 }
2153 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002154 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002155 }
2156
2157 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002158 while (getBE().mCompositePresentTimes.size() > 16) {
2159 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002160 }
2161
Ana Krulece588e312018-09-18 12:32:24 -07002162 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002163}
2164
Ana Krulece588e312018-09-18 12:32:24 -07002165void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2166 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002167 // Integer division and modulo round toward 0 not -inf, so we need to
2168 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002169 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2170 ? (stats.vsyncPeriod -
2171 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2172 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002173
Ady Abraham9e16a482019-12-03 17:19:41 -08002174 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002175 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002176 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002177 }
2178
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002179 // Snap the latency to a value that removes scheduling jitter from the
2180 // composition and present times, which often have >1ms of jitter.
2181 // Reducing jitter is important if an app attempts to extrapolate
2182 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002183 // Snapping also allows an app to precisely calculate
2184 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002185 nsecs_t bias = stats.vsyncPeriod / 2;
2186 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2187 nsecs_t snappedCompositeToPresentLatency =
2188 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002189
David Sodman99974d22017-11-28 12:04:33 -08002190 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002191 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2192 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002193 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002194}
2195
David Sodman2b406362017-12-15 13:33:47 -08002196void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002197{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002198 ATRACE_CALL();
2199 ALOGV("postComposition");
2200
Brian Andersonf6386862016-10-31 16:34:13 -07002201 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002202 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002203 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002204 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002205 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002206 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002207
David Sodman73beded2017-11-15 11:56:06 -08002208 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002209 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002210 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002211 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002212 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2213 ->getRenderSurface()
2214 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002215 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002216 } else {
2217 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2218 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002219
David Sodman73beded2017-11-15 11:56:06 -08002220 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002221 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2222 mPreviousPresentFences[0] = displayDevice
2223 ? getHwComposer().getPresentFence(*displayDevice->getId())
2224 : Fence::NO_FENCE;
2225 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002226 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002227
Ana Krulece588e312018-09-18 12:32:24 -07002228 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002229 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002230
Lloyd Piqueab039b52019-02-13 14:22:42 -08002231 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2232 // be sampled a little later than when we started doing work for this frame,
2233 // but that should be okay since updateCompositorTiming has snapping logic.
2234 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2235 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002236 CompositorTiming compositorTiming;
2237 {
David Sodman99974d22017-11-28 12:04:33 -08002238 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2239 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002240 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002241
Edgar Arriaga844fa672020-01-16 14:21:42 -08002242 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002243 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2244 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002245 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002246 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002247 }
Robert Carr2047fae2016-11-28 14:09:09 -08002248 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002249
Valerie Hau4b678442020-04-14 10:50:42 -07002250 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2251 mTransactionCompletedThread.sendCallbacks();
2252
Ady Abraham92fa2f42020-02-11 15:33:56 -08002253 if (displayDevice && displayDevice->isPrimary() &&
Peiyong Lin65248e02020-04-18 21:15:07 -07002254 displayDevice->getPowerMode() == hal::PowerMode::ON && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002255 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002256 }
2257
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002258 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002259 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2260 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002261 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002262 }
2263 }
2264
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002265 if (mAnimCompositionPending) {
2266 mAnimCompositionPending = false;
2267
Brian Anderson4e606e32017-03-16 15:34:57 -07002268 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002269 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002270 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002271 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002272 // The HWC doesn't support present fences, so use the refresh
2273 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002274 const nsecs_t presentTime =
2275 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002276 mAnimFrameTracker.setActualPresentTime(presentTime);
2277 }
2278 mAnimFrameTracker.advanceFrame();
2279 }
Dan Stozab90cf072015-03-05 11:05:59 -08002280
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002281 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002282 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002283 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002284 }
2285
Vishnu Nair9b079a22020-01-21 14:36:08 -08002286 if (mReusedClientComposition) {
2287 mTimeStats->incrementClientCompositionReusedFrames();
2288 }
2289
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002290 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002291
Alec Mouri717bcb62020-02-10 17:07:19 -08002292 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2293 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2294 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2295
Lloyd Pique32cbe282018-10-19 13:09:22 -07002296 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2297 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002298 return;
2299 }
2300
2301 nsecs_t currentTime = systemTime();
2302 if (mHasPoweredOff) {
2303 mHasPoweredOff = false;
2304 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002305 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002306 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002307 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2308 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002309 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002310 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002311 }
David Sodman4a36e932017-11-07 14:29:47 -08002312 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002313 }
David Sodman4a36e932017-11-07 14:29:47 -08002314 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002315
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002316 // Cleanup any outstanding resources due to rendering a prior frame.
2317 getRenderEngine().cleanupPostRender();
2318
Dan Stoza436ccf32018-06-21 12:10:12 -07002319 {
2320 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002321 if (mTexturePool.size() < mTexturePoolSize) {
2322 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002323 const size_t offset = mTexturePool.size();
2324 mTexturePool.resize(mTexturePoolSize);
2325 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2326 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002327 } else if (mTexturePool.size() > mTexturePoolSize) {
2328 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2329 const size_t offset = mTexturePoolSize;
2330 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2331 mTexturePool.resize(mTexturePoolSize);
2332 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002333 }
2334 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002335
Kevin DuBois413287f2019-02-25 08:46:47 -08002336 if (mLumaSampling && mRegionSamplingThread) {
2337 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002338 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002339
2340 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2341 // side-effect of getTotalSize(), so we check that again here
2342 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002343 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002344 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2345 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002346}
2347
Lloyd Pique7eebe692020-04-22 22:40:06 -07002348FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2349 return displayDevice.getViewport().toFloatRect();
2350}
2351
Vishnu Nair4351ad52019-02-11 14:13:02 -08002352void SurfaceFlinger::computeLayerBounds() {
2353 for (const auto& pair : mDisplays) {
2354 const auto& displayDevice = pair.second;
2355 const auto display = displayDevice->getCompositionDisplay();
2356 for (const auto& layer : mDrawingState.layersSortedByZ) {
2357 // only consider the layers on the given layer stack
2358 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002359 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002360 }
2361
Lloyd Pique7eebe692020-04-22 22:40:06 -07002362 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002363 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002364 }
2365 }
2366}
2367
David Sodmanfa9b2af2017-12-24 13:28:59 -08002368void SurfaceFlinger::postFrame()
2369{
2370 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002371 const auto display = getDefaultDisplayDeviceLocked();
2372 if (display && getHwComposer().isConnected(*display->getId())) {
2373 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002374 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2375 logFrameStats();
2376 }
2377 }
2378}
2379
Mathias Agopian87baae12012-07-31 12:38:26 -07002380void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002381{
Mathias Agopian841cde52012-03-01 15:44:37 -08002382 ATRACE_CALL();
2383
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002384 // here we keep a copy of the drawing state (that is the state that's
2385 // going to be overwritten by handleTransactionLocked()) outside of
2386 // mStateLock so that the side-effects of the State assignment
2387 // don't happen with mStateLock held (which can cause deadlocks).
2388 State drawingState(mDrawingState);
2389
Mathias Agopianca4d3602011-05-19 15:38:14 -07002390 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002391 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392
Mathias Agopianca4d3602011-05-19 15:38:14 -07002393 // Here we're guaranteed that some transaction flags are set
2394 // so we can call handleTransactionLocked() unconditionally.
2395 // We call getTransactionFlags(), which will also clear the flags,
2396 // with mStateLock held to guarantee that mCurrentState won't change
2397 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002398
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002399 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002400 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002401 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002402
Mathias Agopianca4d3602011-05-19 15:38:14 -07002403 mDebugInTransaction = 0;
2404 invalidateHwcGeometry();
2405 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002406}
2407
Lloyd Piqueba04e622017-12-14 17:11:26 -08002408void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2409 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002410 const std::optional<DisplayIdentificationInfo> info =
2411 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002412
Dominik Laskowski075d3172018-05-24 15:50:06 -07002413 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002414 continue;
2415 }
2416
Dominik Laskowski55c85402020-01-21 16:25:47 -08002417 const DisplayId displayId = info->id;
2418 const auto it = mPhysicalDisplayTokens.find(displayId);
2419
Peiyong Line9d809e2020-04-14 13:10:48 -07002420 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002421 if (it == mPhysicalDisplayTokens.end()) {
2422 ALOGV("Creating display %s", to_string(displayId).c_str());
2423
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002424 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002425 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002426 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002427
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 DisplayDeviceState state;
Marin Shalamanov700e6392020-02-12 20:22:26 +01002429 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2430 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002431 state.isSecure = true; // All physical displays are currently considered secure.
2432 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002433
2434 sp<IBinder> token = new BBinder();
2435 mCurrentState.displays.add(token, state);
2436 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2437
Dominik Laskowski075d3172018-05-24 15:50:06 -07002438 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002439 } else {
2440 ALOGV("Recreating display %s", to_string(displayId).c_str());
2441
2442 const auto token = it->second;
2443 auto& state = mCurrentState.displays.editValueFor(token);
2444 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002445 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002446 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002447 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002448
Dominik Laskowski55c85402020-01-21 16:25:47 -08002449 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002450 if (index >= 0) {
2451 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2452 mInterceptor->saveDisplayDeletion(state.sequenceId);
2453 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002454 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002455 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002456 }
2457
2458 processDisplayChangesLocked();
2459 }
2460
2461 mPendingHotplugEvents.clear();
2462}
2463
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002464void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002465 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2466 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002467}
2468
Lloyd Pique99d3da52018-01-22 17:48:03 -08002469sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002470 const wp<IBinder>& displayToken,
2471 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002472 const DisplayDeviceState& state,
2473 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002474 const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique9370a482019-10-03 17:58:30 -07002475 auto displayId = compositionDisplay->getDisplayId();
2476 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002477 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002478 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002479 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002480 creationArgs.hasWideColorGamut = false;
2481 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002482
Dominik Laskowski55c85402020-01-21 16:25:47 -08002483 if (const auto& physical = state.physical) {
2484 creationArgs.connectionType = physical->type;
2485 }
2486
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002487 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002488 creationArgs.isPrimary = isInternalDisplay;
2489
2490 if (useColorManagement && displayId) {
2491 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002492 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002493 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002494 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002495 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002496
Dominik Laskowski7e045462018-05-30 13:02:02 -07002497 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002498 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002499 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002500 }
tangrobin6753a022018-08-10 10:58:54 +08002501 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502
Dominik Laskowski075d3172018-05-24 15:50:06 -07002503 if (displayId) {
2504 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002505 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002506 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002507 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002508
Lloyd Pique90c115d2018-09-18 21:39:42 -07002509 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002510 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002511 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002512
Lloyd Pique99d3da52018-01-22 17:48:03 -08002513 // Make sure that composition can never be stalled by a virtual display
2514 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002515 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002516 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002517 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2518 }
2519
Dominik Laskowski718f9602019-11-09 20:01:35 -08002520 creationArgs.physicalOrientation =
2521 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002522
Lloyd Pique99d3da52018-01-22 17:48:03 -08002523 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002524 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002525
Lloyd Pique9370a482019-10-03 17:58:30 -07002526 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002527
2528 if (maxFrameBufferAcquiredBuffers >= 3) {
2529 nativeWindowSurface->preallocateBuffers();
2530 }
2531
2532 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002533 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002534 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002535 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002536 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002537 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002538 display->getCompositionDisplay()->setColorProfile(
2539 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2540 RenderIntent::COLORIMETRIC,
2541 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002542 if (!state.isVirtual()) {
2543 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002544 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2545 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002546 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002547
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002548 display->setLayerStack(state.layerStack);
2549 display->setProjection(state.orientation, state.viewport, state.frame);
2550 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002551
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002552 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002553}
2554
Marin Shalamanovae685592020-02-12 17:12:22 +01002555void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2556 const DisplayDeviceState& state) {
2557 int width = 0;
2558 int height = 0;
2559 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2560 if (state.physical) {
2561 const auto& activeConfig =
2562 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2563 width = activeConfig->getWidth();
2564 height = activeConfig->getHeight();
2565 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2566 } else if (state.surface != nullptr) {
2567 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2568 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2569 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2570 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2571 int intPixelFormat;
2572 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2573 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2574 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2575 } else {
2576 // Virtual displays without a surface are dormant:
2577 // they have external state (layer stack, projection,
2578 // etc.) but no internal state (i.e. a DisplayDevice).
2579 return;
2580 }
2581
2582 compositionengine::DisplayCreationArgsBuilder builder;
2583 if (const auto& physical = state.physical) {
2584 builder.setPhysical({physical->id, physical->type});
2585 }
2586 builder.setPixels(ui::Size(width, height));
2587 builder.setPixelFormat(pixelFormat);
2588 builder.setIsSecure(state.isSecure);
2589 builder.setLayerStackId(state.layerStack);
2590 builder.setPowerAdvisor(&mPowerAdvisor);
2591 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2592 builder.setName(state.displayName);
2593 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2594
2595 sp<compositionengine::DisplaySurface> displaySurface;
2596 sp<IGraphicBufferProducer> producer;
2597 sp<IGraphicBufferProducer> bqProducer;
2598 sp<IGraphicBufferConsumer> bqConsumer;
2599 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2600
2601 std::optional<DisplayId> displayId = compositionDisplay->getId();
2602
2603 if (state.isVirtual()) {
2604 sp<VirtualDisplaySurface> vds =
2605 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2606 bqConsumer, state.displayName);
2607
2608 displaySurface = vds;
2609 producer = vds;
2610 } else {
2611 ALOGE_IF(state.surface != nullptr,
2612 "adding a supported display, but rendering "
2613 "surface is provided (%p), ignoring it",
2614 state.surface.get());
2615
2616 LOG_ALWAYS_FATAL_IF(!displayId);
2617 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2618 maxGraphicsWidth, maxGraphicsHeight);
2619 producer = bqProducer;
2620 }
2621
Marin Shalamanov700e6392020-02-12 20:22:26 +01002622 LOG_FATAL_IF(!displaySurface);
2623 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2624 displaySurface, producer);
2625 mDisplays.emplace(displayToken, display);
2626 if (!state.isVirtual()) {
2627 LOG_FATAL_IF(!displayId);
2628 dispatchDisplayHotplugEvent(displayId->value, true);
2629 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002630
Marin Shalamanov700e6392020-02-12 20:22:26 +01002631 if (display->isPrimary()) {
2632 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanovae685592020-02-12 17:12:22 +01002633 }
2634}
2635
2636void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2637 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2638 // Save display ID before disconnecting.
2639 const auto displayId = display->getId();
2640 display->disconnect();
2641
2642 if (!display->isVirtual()) {
Marin Shalamanov700e6392020-02-12 20:22:26 +01002643 LOG_FATAL_IF(!displayId);
Marin Shalamanovae685592020-02-12 17:12:22 +01002644 dispatchDisplayHotplugEvent(displayId->value, false);
2645 }
2646 }
2647
2648 mDisplays.erase(displayToken);
2649}
2650
2651void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2652 const DisplayDeviceState& currentState,
2653 const DisplayDeviceState& drawingState) {
2654 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2655 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002656 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002657 // changing the surface is like destroying and recreating the DisplayDevice
2658 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2659 display->disconnect();
2660 }
2661 mDisplays.erase(displayToken);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002662 if (const auto& physical = currentState.physical) {
2663 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2664 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002665 processDisplayAdded(displayToken, currentState);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002666 if (currentState.physical) {
2667 initializeDisplays();
2668 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002669 return;
2670 }
2671
2672 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2673 if (currentState.layerStack != drawingState.layerStack) {
2674 display->setLayerStack(currentState.layerStack);
2675 }
2676 if ((currentState.orientation != drawingState.orientation) ||
2677 (currentState.viewport != drawingState.viewport) ||
2678 (currentState.frame != drawingState.frame)) {
2679 display->setProjection(currentState.orientation, currentState.viewport,
2680 currentState.frame);
2681 }
2682 if (currentState.width != drawingState.width ||
2683 currentState.height != drawingState.height) {
2684 display->setDisplaySize(currentState.width, currentState.height);
2685 if (display->isPrimary()) {
2686 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2687 }
2688 }
2689 }
2690}
2691
Lloyd Pique347200f2017-12-14 17:00:15 -08002692void SurfaceFlinger::processDisplayChangesLocked() {
2693 // here we take advantage of Vector's copy-on-write semantics to
2694 // improve performance by skipping the transaction entirely when
2695 // know that the lists are identical
2696 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2697 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2698 if (!curr.isIdenticalTo(draw)) {
2699 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002700
2701 // find the displays that were removed
2702 // (ie: in drawing state but not in current state)
2703 // also handle displays that changed
2704 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01002705 for (size_t i = 0; i < draw.size(); i++) {
2706 const wp<IBinder>& displayToken = draw.keyAt(i);
2707 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 if (j < 0) {
2709 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01002710 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 } else {
2712 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01002713 const DisplayDeviceState& currentState = curr[j];
2714 const DisplayDeviceState& drawingState = draw[i];
2715 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002717 }
2718
2719 // find displays that were added
2720 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01002721 for (size_t i = 0; i < curr.size(); i++) {
2722 const wp<IBinder>& displayToken = curr.keyAt(i);
2723 if (draw.indexOfKey(displayToken) < 0) {
2724 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 }
2726 }
2727 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002728
2729 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002730}
2731
Mathias Agopian87baae12012-07-31 12:38:26 -07002732void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002733{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002734 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2735
Dan Stoza7dde5992015-05-22 09:51:44 -07002736 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002737 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002738 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002739 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002740
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741 /*
2742 * Traversal of the children
2743 * (perform the transaction for each of them if needed)
2744 */
2745
Marissa Wall06255332019-03-27 13:48:27 -07002746 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002747 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002749 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750
2751 const uint32_t flags = layer->doTransaction(0);
2752 if (flags & Layer::eVisibleRegion)
2753 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002754
2755 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002756 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002757 }
Robert Carr2047fae2016-11-28 14:09:09 -08002758 });
Marissa Wall06255332019-03-27 13:48:27 -07002759 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760 }
2761
2762 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002763 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764 */
2765
Mathias Agopiane57f2922012-08-09 16:29:12 -07002766 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002767 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002768 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002769 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002771 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002772 // The transform hint might have changed for some layers
2773 // (either because a display has changed, or because a layer
2774 // as changed).
2775 //
2776 // Walk through all the layers in currentLayers,
2777 // and update their transform hint.
2778 //
2779 // If a layer is visible only on a single display, then that
2780 // display is used to calculate the hint, otherwise we use the
2781 // default display.
2782 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002783 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002784 // the hint is set before we acquire a buffer from the surface texture.
2785 //
2786 // NOTE: layer transactions have taken place already, so we use their
2787 // drawing state. However, SurfaceFlinger's own transaction has not
2788 // happened yet, so we must use the current state layer list
2789 // (soon to become the drawing state list).
2790 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002791 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002792 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002793 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002794 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002795 // NOTE: we rely on the fact that layers are sorted by
2796 // layerStack first (so we don't have to traverse the list
2797 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002798 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002799 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002800 currentlayerStack = layerStack;
2801 // figure out if this layerstack is mirrored
2802 // (more than one display) if so, pick the default display,
2803 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002804 hintDisplay = nullptr;
2805 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002806 if (display->getCompositionDisplay()
2807 ->belongsInOutput(layer->getLayerStack(),
2808 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002809 if (hintDisplay) {
2810 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002811 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002812 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002813 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002814 }
2815 }
2816 }
2817 }
Chet Haase91d25932013-04-11 15:24:55 -07002818
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002819 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002820 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2821 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002822
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002823 // could be null when this layer is using a layerStack
2824 // that is not visible on any display. Also can occur at
2825 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002826 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002827 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002828
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002829 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002830 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002831 if (hintDisplay) {
2832 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002833 }
Robert Carr2047fae2016-11-28 14:09:09 -08002834
2835 first = false;
2836 });
Mathias Agopian84300952012-11-21 16:02:13 -08002837 }
2838
2839
Mathias Agopian3559b072012-08-15 13:46:03 -07002840 /*
2841 * Perform our own transaction if needed
2842 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002843
2844 if (mLayersAdded) {
2845 mLayersAdded = false;
2846 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002847 mVisibleRegionsDirty = true;
2848 }
2849
2850 // some layers might have been removed, so
2851 // we need to update the regions they're exposing.
2852 if (mLayersRemoved) {
2853 mLayersRemoved = false;
2854 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002855 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002856 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002857 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002858 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002859 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002860 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002861 }
Robert Carr2047fae2016-11-28 14:09:09 -08002862 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863 }
2864
Vishnu Nairec0ab382019-02-13 15:32:56 -08002865 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002867}
2868
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002869void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002870 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002871 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002872 return;
2873 }
2874
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002875 if (mVisibleRegionsDirty || mInputInfoChanged) {
2876 mInputInfoChanged = false;
2877 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002878 } else if (mInputWindowCommands.syncInputWindows) {
2879 // If the caller requested to sync input windows, but there are no
2880 // changes to input windows, notify immediately.
2881 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002882 }
2883
Arthur Hung6cbb9752019-09-05 16:38:18 +08002884 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002885}
2886
2887void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002888 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002889
2890 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2891 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002892 // When calculating the screen bounds we ignore the transparent region since it may
2893 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002894 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002895 }
2896 });
chaviw291d88a2019-02-14 10:33:58 -08002897
2898 mInputFlinger->setInputWindows(inputHandles,
2899 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2900 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002901}
2902
Vishnu Nairec0ab382019-02-13 15:32:56 -08002903void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002904 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002905 mPendingInputWindowCommands.clear();
2906}
2907
Riley Andrews03414a12014-07-01 14:22:59 -07002908void SurfaceFlinger::updateCursorAsync()
2909{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002910 compositionengine::CompositionRefreshArgs refreshArgs;
2911 for (const auto& [_, display] : mDisplays) {
2912 if (display->getId()) {
2913 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002914 }
2915 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002916
2917 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002918}
2919
Ady Abraham2139f732019-11-13 18:56:40 -08002920void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002921 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2922 // If this is called from the main thread mStateLock must be locked before
2923 // Currently the only way to call this function from the main thread is from
2924 // Sheduler::chooseRefreshRateForContent
2925
2926 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002927 changeRefreshRateLocked(refreshRate, event);
2928}
2929
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002930void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2931 if (mScheduler) {
2932 // In practice it's not allowed to hotplug in/out the primary display once it's been
2933 // connected during startup, but some tests do it, so just warn and return.
2934 ALOGW("Can't re-init scheduler");
2935 return;
2936 }
2937
Ady Abraham2139f732019-11-13 18:56:40 -08002938 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002939 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002940 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002941 primaryDisplayId),
2942 currentConfig);
2943 mRefreshRateStats =
2944 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002945 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002946 mRefreshRateStats->setConfigMode(currentConfig);
2947
Ady Abraham9e16a482019-12-03 17:19:41 -08002948 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2949
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002950 // start the EventThread
2951 mScheduler =
2952 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002953 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002954 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002955 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002956 impl::EventThread::InterceptVSyncsCallback());
2957 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002958 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002959 [this](nsecs_t timestamp) {
2960 mInterceptor->saveVSyncEvent(timestamp);
2961 });
2962
2963 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2964 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002965 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002966
2967 mRegionSamplingThread =
2968 new RegionSamplingThread(*this, *mScheduler,
2969 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002970 // Dispatch a config change request for the primary display on scheduler
2971 // initialization, so that the EventThreads always contain a reference to a
2972 // prior configuration.
2973 //
2974 // This is a bit hacky, but this avoids a back-pointer into the main SF
2975 // classes from EventThread, and there should be no run-time binder cost
2976 // anyway since there are no connected apps at this point.
2977 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002978 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Alec Mouri60aee1c2019-10-28 16:18:59 -07002979 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2980 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002981}
2982
Mathias Agopian4fec8732012-06-29 14:12:52 -07002983void SurfaceFlinger::commitTransaction()
2984{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002985 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002986 mTransactionPending = false;
2987 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002988 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989}
2990
Lloyd Pique58e24a32019-08-01 15:50:14 -07002991void SurfaceFlinger::commitTransactionLocked() {
2992 if (!mLayersPendingRemoval.isEmpty()) {
2993 // Notify removed layers now that they can't be drawn from
2994 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002995 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002996
2997 // Ensure any buffers set to display on any children are released.
2998 if (l->isRemovedFromCurrentState()) {
2999 l->latchAndReleaseBuffer();
3000 }
3001
3002 // If the layer has been removed and has no parent, then it will not be reachable
3003 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3004 // ensure we can copy its current to drawing state.
3005 if (!l->getParent()) {
3006 mOffscreenLayers.emplace(l.get());
3007 }
3008 }
3009 mLayersPendingRemoval.clear();
3010 }
3011
3012 // If this transaction is part of a window animation then the next frame
3013 // we composite should be considered an animation as well.
3014 mAnimCompositionPending = mAnimTransactionPending;
3015
3016 mDrawingState = mCurrentState;
3017 // clear the "changed" flags in current state
3018 mCurrentState.colorMatrixChanged = false;
3019
Edgar Arriaga844fa672020-01-16 14:21:42 -08003020 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003021 layer->commitChildList();
3022
3023 // If the layer can be reached when traversing mDrawingState, then the layer is no
3024 // longer offscreen. Remove the layer from the offscreenLayer set.
3025 if (mOffscreenLayers.count(layer)) {
3026 mOffscreenLayers.erase(layer);
3027 }
3028 });
3029
3030 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003031 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003032}
3033
chaviw74d90ad2019-04-26 14:45:26 -07003034void SurfaceFlinger::commitOffscreenLayers() {
3035 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003036 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003037 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3038 if (!trFlags) return;
3039
3040 layer->doTransaction(0);
3041 layer->commitChildList();
3042 });
3043 }
3044}
3045
Chia-I Wuab0c3192017-08-01 11:29:00 -07003046void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003047 for (const auto& [token, displayDevice] : mDisplays) {
3048 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003049 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003050 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003051 }
3052 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003053}
3054
Dan Stoza6b9454d2014-11-07 16:00:59 -08003055bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003056{
Ady Abraham09bd3922019-04-08 10:44:56 -07003057 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003058 ALOGV("handlePageFlip");
3059
Brian Andersond6927fb2016-07-23 23:37:30 -07003060 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003061
Mathias Agopian4fec8732012-06-29 14:12:52 -07003062 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003063 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003064 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003065
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003066 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3067
Eric Penner51c59cd2014-07-28 19:51:58 -07003068 // Store the set of layers that need updates. This set must not change as
3069 // buffers are being latched, as this could result in a deadlock.
3070 // Example: Two producers share the same command stream and:
3071 // 1.) Layer 0 is latched
3072 // 2.) Layer 0 gets a new frame
3073 // 2.) Layer 1 gets a new frame
3074 // 3.) Layer 1 is latched.
3075 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3076 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003077 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003078 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003079 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003080 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003081 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003082 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003083 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003084 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003085 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003086 } else {
3087 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003088 }
Robert Carr2047fae2016-11-28 14:09:09 -08003089 });
3090
chaviw49a108c2019-08-12 11:23:06 -07003091 // The client can continue submitting buffers for offscreen layers, but they will not
3092 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3093 // layers to ensure dequeueBuffer doesn't block indefinitely.
3094 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003095 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003096 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3097 }
3098
Lloyd Piquef2c79392018-12-20 16:23:33 -08003099 if (!mLayersWithQueuedFrames.empty()) {
3100 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3101 // writes to Layer current state. See also b/119481871
3102 Mutex::Autolock lock(mStateLock);
3103
3104 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003105 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003106 mLayersPendingRefresh.push_back(layer);
3107 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003108 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003109 if (layer->isBufferLatched()) {
3110 newDataLatched = true;
3111 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003112 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003113 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003114
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003115 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003116
3117 // If we will need to wake up at some time in the future to deal with a
3118 // queued frame that shouldn't be displayed during this vsync period, wake
3119 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003120 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003121 signalLayerUpdate();
3122 }
3123
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003124 // enter boot animation on first buffer latch
3125 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3126 ALOGI("Enter boot animation");
3127 mBootStage = BootStage::BOOTANIMATION;
3128 }
3129
Edgar Arriaga844fa672020-01-16 14:21:42 -08003130 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003131
Dan Stoza6b9454d2014-11-07 16:00:59 -08003132 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003133 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134}
3135
Mathias Agopianad456f92011-01-13 17:53:01 -08003136void SurfaceFlinger::invalidateHwcGeometry()
3137{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003138 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003139}
3140
Robert Carrc0df3122019-04-11 13:18:21 -07003141status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3142 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3143 const sp<IBinder>& parentHandle,
3144 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003145 // add this layer to the current state list
3146 {
3147 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003148 sp<Layer> parent;
3149 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003150 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003151 if (parent == nullptr) {
3152 return NAME_NOT_FOUND;
3153 }
3154 } else {
3155 parent = parentLayer;
3156 }
3157
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003158 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003159 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003160 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003161 return NO_MEMORY;
3162 }
Robert Carrc0df3122019-04-11 13:18:21 -07003163
3164 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3165
Robert Carrb89ea9d2018-12-10 13:01:14 -08003166 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003167 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003168 } else if (parent == nullptr) {
3169 lbc->onRemovedFromCurrentState();
3170 } else if (parent->isRemovedFromCurrentState()) {
3171 parent->addChild(lbc);
3172 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003173 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003174 parent->addChild(lbc);
3175 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003176
Yiwei Zhang243b3782018-05-15 17:40:04 -07003177 if (gbc != nullptr) {
3178 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3179 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3180 mMaxGraphicBufferProducerListSize,
3181 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3182 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003183 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003184 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3185 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3186 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3187 mNumLayers.load());
3188 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003189 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003190 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003191 }
3192
Mathias Agopian96f08192010-06-02 23:28:45 -07003193 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003194 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003195
Dan Stoza7d89d062015-04-30 13:29:25 -07003196 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003197}
3198
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003199void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3200 static_cast<void>(schedule([=] {
3201 Mutex::Autolock lock(mStateLock);
3202 mGraphicBufferProducerList.erase(binder);
3203 }));
3204}
3205
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003206uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003207 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003208}
3209
Mathias Agopian3f844832013-08-07 21:24:32 -07003210uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003211 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212}
3213
Mathias Agopian3f844832013-08-07 21:24:32 -07003214uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003215 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003216}
3217
3218uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003219 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003220 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003221 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003223 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224 }
3225 return old;
3226}
3227
Marissa Wall713b63f2018-10-17 15:42:43 -07003228bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003229 // to prevent onHandleDestroyed from being called while the lock is held,
3230 // we must keep a copy of the transactions (specifically the composer
3231 // states) around outside the scope of the lock
3232 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003233 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003234 {
3235 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003236
Valerie Haufce31b82019-04-30 16:41:14 -07003237 auto it = mTransactionQueues.begin();
3238 while (it != mTransactionQueues.end()) {
3239 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003240
Valerie Haufce31b82019-04-30 16:41:14 -07003241 while (!transactionQueue.empty()) {
3242 const auto& transaction = transactionQueue.front();
3243 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3244 transaction.states)) {
3245 setTransactionFlags(eTransactionFlushNeeded);
3246 break;
3247 }
3248 transactions.push_back(transaction);
3249 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3250 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003251 transaction.buffer, transaction.postTime,
3252 transaction.privileged, transaction.hasListenerCallbacks,
3253 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003254 transactionQueue.pop();
3255 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003256 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003257
Valerie Haufce31b82019-04-30 16:41:14 -07003258 if (transactionQueue.empty()) {
3259 it = mTransactionQueues.erase(it);
3260 mTransactionCV.broadcast();
3261 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003262 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003263 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003264 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003265 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003266 return flushedATransaction;
3267}
3268
3269bool SurfaceFlinger::transactionFlushNeeded() {
3270 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003271}
3272
chaviwca27f252018-02-06 16:46:39 -08003273
Marissa Wall17b4e452018-12-26 16:32:34 -08003274bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3275 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003276
3277 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003278 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3279 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3280 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3281 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3282 return false;
3283 }
3284
Marissa Wall713b63f2018-10-17 15:42:43 -07003285 for (const ComposerState& state : states) {
3286 const layer_state_t& s = state.state;
3287 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3288 continue;
3289 }
3290 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003291 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003292 }
3293 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003294 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003295}
3296
Valerie Hau9dab9732019-08-20 09:29:25 -07003297void SurfaceFlinger::setTransactionState(
3298 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3299 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3300 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3301 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003302 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003303
Valerie Haubc6ddb12019-03-08 11:10:15 -08003304 const int64_t postTime = systemTime();
3305
Robert Carr14167e02019-02-13 13:50:55 -08003306 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3307
Mathias Agopian698c0872011-06-28 19:09:31 -07003308 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003309
Marissa Wall713b63f2018-10-17 15:42:43 -07003310 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003311 auto itr = mTransactionQueues.find(applyToken);
3312 // if this is an animation frame, wait until prior animation frame has
3313 // been applied by SF
3314 if (flags & eAnimation) {
3315 while (itr != mTransactionQueues.end()) {
3316 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3317 if (CC_UNLIKELY(err != NO_ERROR)) {
3318 ALOGW_IF(err == TIMED_OUT,
3319 "setTransactionState timed out "
3320 "waiting for animation frame to apply");
3321 break;
3322 }
3323 itr = mTransactionQueues.find(applyToken);
3324 }
3325 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003326
Ady Abraham5facfb12020-04-22 15:18:31 -07003327 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003328 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003329 if (!pendingTransactions) {
3330 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3331 }
3332
3333 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003334 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003335 uncacheBuffer, postTime, privileged,
3336 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003337 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003338 return;
3339 }
3340
Valerie Haubc6ddb12019-03-08 11:10:15 -08003341 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003342 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3343 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003344}
3345
Valerie Hau9dab9732019-08-20 09:29:25 -07003346void SurfaceFlinger::applyTransactionState(
3347 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3348 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3349 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3350 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3351 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003352 uint32_t transactionFlags = 0;
3353
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003354 if (flags & eAnimation) {
3355 // For window updates that are part of an animation we must wait for
3356 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003357 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003358 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003359 if (CC_UNLIKELY(err != NO_ERROR)) {
3360 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003361 // caller after a few seconds.
3362 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3363 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003364 mAnimTransactionPending = false;
3365 break;
3366 }
3367 }
3368 }
3369
chaviwca27f252018-02-06 16:46:39 -08003370 for (const DisplayState& display : displays) {
3371 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003372 }
3373
Valerie Hau9dab9732019-08-20 09:29:25 -07003374 // start and end registration for listeners w/ no surface so they can get their callback. Note
3375 // that listeners with SurfaceControls will start registration during setClientStateLocked
3376 // below.
3377 for (const auto& listener : listenerCallbacks) {
3378 mTransactionCompletedThread.startRegistration(listener);
3379 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003380 }
3381
Valerie Hau9dab9732019-08-20 09:29:25 -07003382 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003383 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003384 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003385 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3386 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003387 }
3388
Valerie Hau9dab9732019-08-20 09:29:25 -07003389 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003390 mTransactionCompletedThread.endRegistration(listenerCallback);
3391 }
3392
Marissa Walle2ffb422018-10-12 11:33:52 -07003393 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003394 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003395 mTransactionCompletedThread.sendCallbacks();
3396 }
3397 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003398
chaviw273171b2018-12-26 11:46:30 -08003399 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3400
Marissa Wall947d34e2019-03-29 14:03:53 -07003401 if (uncacheBuffer.isValid()) {
3402 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003403 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003404 }
3405
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003406 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3407 // anyway. This can be used as a flush mechanism for previous async transactions.
3408 // Empty animation transaction can be used to simulate back-pressure, so also force a
3409 // transaction for empty animation transactions.
3410 if (transactionFlags == 0 &&
3411 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003412 transactionFlags = eTransactionNeeded;
3413 }
3414
Marissa Wall06255332019-03-27 13:48:27 -07003415 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3416 // so we don't have to wake up again next frame to preform an uneeded traversal.
3417 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3418 transactionFlags = transactionFlags & (~eTraversalNeeded);
3419 mTraversalNeededMainThread = true;
3420 }
3421
Mathias Agopian386aa982011-11-07 21:58:03 -08003422 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003423 if (mInterceptor->isEnabled()) {
3424 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003425 }
Irvel468051e2016-06-13 16:44:44 -07003426
Mathias Agopian386aa982011-11-07 21:58:03 -08003427 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003428 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3429 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003430 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003431
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003432 if (flags & eAnimation) {
3433 mAnimTransactionPending = true;
3434 }
Robert Carr238f4a22020-04-29 13:04:02 -07003435
3436 // if this is a synchronous transaction, wait for it to take effect
3437 // before returning.
3438 const bool synchronous = flags & eSynchronous;
3439 const bool syncInput = inputWindowCommands.syncInputWindows;
3440 if (!synchronous && !syncInput) {
3441 return;
3442 }
3443
3444 if (synchronous) {
3445 mTransactionPending = true;
3446 }
3447 if (syncInput) {
chaviw4fe36852019-04-15 16:25:49 -07003448 mPendingSyncInputWindows = true;
3449 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003450
Robert Carr238f4a22020-04-29 13:04:02 -07003451
Valerie Hau0779ded2019-03-19 12:43:04 -07003452 // applyTransactionState can be called by either the main SF thread or by
3453 // another process through setTransactionState. While a given process may wish
3454 // to wait on synchronous transactions, the main SF thread should never
3455 // be blocked. Therefore, we only wait if isMainThread is false.
3456 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003457 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3458 if (CC_UNLIKELY(err != NO_ERROR)) {
3459 // just in case something goes wrong in SF, return to the
3460 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003461 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3462 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003463 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003464 break;
3465 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003466 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003467 }
3468}
3469
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003470uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3471 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3472 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003473
Mathias Agopiane57f2922012-08-09 16:29:12 -07003474 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003475 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3476
3477 const uint32_t what = s.what;
3478 if (what & DisplayState::eSurfaceChanged) {
3479 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3480 state.surface = s.surface;
3481 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003482 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003483 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003484 if (what & DisplayState::eLayerStackChanged) {
3485 if (state.layerStack != s.layerStack) {
3486 state.layerStack = s.layerStack;
3487 flags |= eDisplayTransactionNeeded;
3488 }
3489 }
3490 if (what & DisplayState::eDisplayProjectionChanged) {
3491 if (state.orientation != s.orientation) {
3492 state.orientation = s.orientation;
3493 flags |= eDisplayTransactionNeeded;
3494 }
3495 if (state.frame != s.frame) {
3496 state.frame = s.frame;
3497 flags |= eDisplayTransactionNeeded;
3498 }
3499 if (state.viewport != s.viewport) {
3500 state.viewport = s.viewport;
3501 flags |= eDisplayTransactionNeeded;
3502 }
3503 }
3504 if (what & DisplayState::eDisplaySizeChanged) {
3505 if (state.width != s.width) {
3506 state.width = s.width;
3507 flags |= eDisplayTransactionNeeded;
3508 }
3509 if (state.height != s.height) {
3510 state.height = s.height;
3511 flags |= eDisplayTransactionNeeded;
3512 }
3513 }
3514
Mathias Agopiane57f2922012-08-09 16:29:12 -07003515 return flags;
3516}
3517
Steven Thomasd4071902020-03-24 16:02:53 -07003518bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003519 IPCThreadState* ipc = IPCThreadState::self();
3520 const int pid = ipc->getCallingPid();
3521 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003522 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003523 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3524 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003525 return false;
3526 }
3527 return true;
3528}
3529
Marissa Wall3dad52d2019-03-22 14:03:19 -07003530uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003531 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3532 bool privileged,
3533 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003534 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003535
Valerie Hau9dab9732019-08-20 09:29:25 -07003536 for (auto& listener : s.listeners) {
3537 // note that startRegistration will not re-register if the listener has
3538 // already be registered for a prior surface control
3539 mTransactionCompletedThread.startRegistration(listener);
3540 listenerCallbacks.insert(listener);
3541 }
3542
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003543 sp<Layer> layer = nullptr;
3544 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003545 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003546 } else {
3547 // The client may provide us a null handle. Treat it as if the layer was removed.
3548 ALOGW("Attempt to set client state with a null layer handle");
3549 }
chaviw8b3871a2017-11-01 17:41:01 -07003550 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003551 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003552 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003553 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003554 }
chaviw8b3871a2017-11-01 17:41:01 -07003555 return 0;
3556 }
3557
chaviw8b3871a2017-11-01 17:41:01 -07003558 uint32_t flags = 0;
3559
Garfield Tan8a3083e2018-12-03 13:21:07 -08003560 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003561
3562 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3563 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003564 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003565 layer->pushPendingState();
3566 }
3567
Valerie Hau871d6352020-01-29 08:44:02 -08003568 // Only set by BLAST adapter layers
3569 if (what & layer_state_t::eProducerDisconnect) {
3570 layer->onDisconnect();
3571 }
3572
chaviw8b3871a2017-11-01 17:41:01 -07003573 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003574 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003575 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003576 }
chaviw8b3871a2017-11-01 17:41:01 -07003577 }
3578 if (what & layer_state_t::eLayerChanged) {
3579 // NOTE: index needs to be calculated before we update the state
3580 const auto& p = layer->getParent();
3581 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003582 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003583 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003584 mCurrentState.layersSortedByZ.removeAt(idx);
3585 mCurrentState.layersSortedByZ.add(layer);
3586 // we need traversal (state changed)
3587 // AND transaction (list changed)
3588 flags |= eTransactionNeeded|eTraversalNeeded;
3589 }
chaviw8b3871a2017-11-01 17:41:01 -07003590 } else {
3591 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003592 flags |= eTransactionNeeded|eTraversalNeeded;
3593 }
3594 }
chaviw8b3871a2017-11-01 17:41:01 -07003595 }
3596 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003597 // NOTE: index needs to be calculated before we update the state
3598 const auto& p = layer->getParent();
3599 if (p == nullptr) {
3600 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3601 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3602 mCurrentState.layersSortedByZ.removeAt(idx);
3603 mCurrentState.layersSortedByZ.add(layer);
3604 // we need traversal (state changed)
3605 // AND transaction (list changed)
3606 flags |= eTransactionNeeded|eTraversalNeeded;
3607 }
3608 } else {
3609 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3610 flags |= eTransactionNeeded|eTraversalNeeded;
3611 }
chaviw8b3871a2017-11-01 17:41:01 -07003612 }
3613 }
3614 if (what & layer_state_t::eSizeChanged) {
3615 if (layer->setSize(s.w, s.h)) {
3616 flags |= eTraversalNeeded;
3617 }
3618 }
3619 if (what & layer_state_t::eAlphaChanged) {
3620 if (layer->setAlpha(s.alpha))
3621 flags |= eTraversalNeeded;
3622 }
3623 if (what & layer_state_t::eColorChanged) {
3624 if (layer->setColor(s.color))
3625 flags |= eTraversalNeeded;
3626 }
Peiyong Lind3788632018-09-18 16:01:31 -07003627 if (what & layer_state_t::eColorTransformChanged) {
3628 if (layer->setColorTransform(s.colorTransform)) {
3629 flags |= eTraversalNeeded;
3630 }
3631 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003632 if (what & layer_state_t::eBackgroundColorChanged) {
3633 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3634 flags |= eTraversalNeeded;
3635 }
3636 }
chaviw8b3871a2017-11-01 17:41:01 -07003637 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003638 // TODO: b/109894387
3639 //
3640 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3641 // rotation. To see the problem observe that if we have a square parent, and a child
3642 // of the same size, then we rotate the child 45 degrees around it's center, the child
3643 // must now be cropped to a non rectangular 8 sided region.
3644 //
3645 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3646 // private API, and the WindowManager only uses rotation in one case, which is on a top
3647 // level layer in which cropping is not an issue.
3648 //
3649 // However given that abuse of rotation matrices could lead to surfaces extending outside
3650 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3651 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3652 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003653 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003654 flags |= eTraversalNeeded;
3655 }
3656 if (what & layer_state_t::eTransparentRegionChanged) {
3657 if (layer->setTransparentRegionHint(s.transparentRegion))
3658 flags |= eTraversalNeeded;
3659 }
3660 if (what & layer_state_t::eFlagsChanged) {
3661 if (layer->setFlags(s.flags, s.mask))
3662 flags |= eTraversalNeeded;
3663 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003664 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003665 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003666 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003667 if (what & layer_state_t::eCornerRadiusChanged) {
3668 if (layer->setCornerRadius(s.cornerRadius))
3669 flags |= eTraversalNeeded;
3670 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003671 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003672 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3673 }
chaviw8b3871a2017-11-01 17:41:01 -07003674 if (what & layer_state_t::eLayerStackChanged) {
3675 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3676 // We only allow setting layer stacks for top level layers,
3677 // everything else inherits layer stack from its parent.
3678 if (layer->hasParent()) {
3679 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003680 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003681 } else if (idx < 0) {
3682 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003683 "that also does not appear in the top level layer list. Something"
3684 " has gone wrong.",
3685 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003686 } else if (layer->setLayerStack(s.layerStack)) {
3687 mCurrentState.layersSortedByZ.removeAt(idx);
3688 mCurrentState.layersSortedByZ.add(layer);
3689 // we need traversal (state changed)
3690 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003691 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003692 }
3693 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003694 if (what & layer_state_t::eDeferTransaction_legacy) {
3695 if (s.barrierHandle_legacy != nullptr) {
3696 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3697 } else if (s.barrierGbp_legacy != nullptr) {
3698 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003699 if (authenticateSurfaceTextureLocked(gbp)) {
3700 const auto& otherLayer =
3701 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003702 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003703 } else {
3704 ALOGE("Attempt to defer transaction to to an"
3705 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003706 }
3707 }
chaviw8b3871a2017-11-01 17:41:01 -07003708 // We don't trigger a traversal here because if no other state is
3709 // changed, we don't want this to cause any more work
3710 }
chaviw8b3871a2017-11-01 17:41:01 -07003711 if (what & layer_state_t::eReparentChildren) {
3712 if (layer->reparentChildren(s.reparentHandle)) {
3713 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003714 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003715 }
chaviw8b3871a2017-11-01 17:41:01 -07003716 if (what & layer_state_t::eDetachChildren) {
3717 layer->detachChildren();
3718 }
3719 if (what & layer_state_t::eOverrideScalingModeChanged) {
3720 layer->setOverrideScalingMode(s.overrideScalingMode);
3721 // We don't trigger a traversal here because if no other state is
3722 // changed, we don't want this to cause any more work
3723 }
Marissa Wall61c58622018-07-18 10:12:20 -07003724 if (what & layer_state_t::eTransformChanged) {
3725 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3726 }
3727 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3728 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3729 flags |= eTraversalNeeded;
3730 }
3731 if (what & layer_state_t::eCropChanged) {
3732 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3733 }
Marissa Wall861616d2018-10-22 12:52:23 -07003734 if (what & layer_state_t::eFrameChanged) {
3735 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3736 }
Marissa Wall61c58622018-07-18 10:12:20 -07003737 if (what & layer_state_t::eAcquireFenceChanged) {
3738 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3739 }
3740 if (what & layer_state_t::eDataspaceChanged) {
3741 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3742 }
3743 if (what & layer_state_t::eHdrMetadataChanged) {
3744 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3745 }
3746 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3747 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3748 }
3749 if (what & layer_state_t::eApiChanged) {
3750 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3751 }
3752 if (what & layer_state_t::eSidebandStreamChanged) {
3753 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3754 }
Robert Carr720e5062018-07-30 17:45:14 -07003755 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003756 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003757 layer->setInputInfo(s.inputInfo);
3758 flags |= eTraversalNeeded;
3759 } else {
3760 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3761 }
Robert Carr720e5062018-07-30 17:45:14 -07003762 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003763 if (what & layer_state_t::eMetadataChanged) {
3764 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3765 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003766 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3767 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3768 flags |= eTraversalNeeded;
3769 }
3770 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003771 if (what & layer_state_t::eShadowRadiusChanged) {
3772 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3773 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003774 if (what & layer_state_t::eFrameRateSelectionPriority) {
3775 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3776 flags |= eTraversalNeeded;
3777 }
3778 }
Steven Thomas3172e202020-01-06 19:25:30 -08003779 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003780 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3781 "SurfaceFlinger::setClientStateLocked") &&
3782 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3783 Layer::FrameRate::convertCompatibility(
3784 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003785 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003786 }
Steven Thomas3172e202020-01-06 19:25:30 -08003787 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003788 // This has to happen after we reparent children because when we reparent to null we remove
3789 // child layers from current state and remove its relative z. If the children are reparented in
3790 // the same transaction, then we have to make sure we reparent the children first so we do not
3791 // lose its relative z order.
3792 if (what & layer_state_t::eReparent) {
3793 bool hadParent = layer->hasParent();
3794 if (layer->reparent(s.parentHandleForChild)) {
3795 if (!hadParent) {
3796 mCurrentState.layersSortedByZ.remove(layer);
3797 }
3798 flags |= eTransactionNeeded | eTraversalNeeded;
3799 }
3800 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003801 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003802 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3803 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003804 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3805 }
3806 }
Marissa Wall78b72202019-03-15 14:58:34 -07003807 bool bufferChanged = what & layer_state_t::eBufferChanged;
3808 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3809 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003810 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003811 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003812 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3813 if (success) {
3814 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3815 success = ClientCache::getInstance()
3816 .registerErasedRecipient(s.cachedBuffer,
3817 wp<ClientCache::ErasedRecipient>(this));
3818 if (!success) {
3819 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3820 }
3821 }
Marissa Wall78b72202019-03-15 14:58:34 -07003822 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003823 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003824 } else if (bufferChanged) {
3825 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003826 }
Marissa Wall78b72202019-03-15 14:58:34 -07003827 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003828 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3829 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003830 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003831 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003832 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003833 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3834 // Do not put anything that updates layer state or modifies flags after
3835 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003836 return flags;
3837}
3838
chaviw273171b2018-12-26 11:46:30 -08003839uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3840 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003841 if (inputWindowCommands.syncInputWindows) {
3842 flags |= eTraversalNeeded;
3843 }
3844
Vishnu Nairec0ab382019-02-13 15:32:56 -08003845 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003846 return flags;
3847}
3848
chaviwfe94a222019-08-21 13:52:59 -07003849status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3850 sp<IBinder>* outHandle) {
3851 if (!mirrorFromHandle) {
3852 return NAME_NOT_FOUND;
3853 }
3854
3855 sp<Layer> mirrorLayer;
3856 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003857 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003858
3859 {
3860 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003861 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003862 if (!mirrorFrom) {
3863 return NAME_NOT_FOUND;
3864 }
3865
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003866 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3867 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003868 if (result != NO_ERROR) {
3869 return result;
3870 }
3871
3872 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3873 }
3874
3875 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3876}
3877
Marissa Wall2d814fb2019-04-09 18:52:57 +00003878status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3879 uint32_t h, PixelFormat format, uint32_t flags,
3880 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003881 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003882 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3883 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003884 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003885 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003886 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003887 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003888 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003889
Robert Carrc0df3122019-04-11 13:18:21 -07003890 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3891 "Expected only one of parentLayer or parentHandle to be non-null. "
3892 "Programmer error?");
3893
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003894 status_t result = NO_ERROR;
3895
3896 sp<Layer> layer;
3897
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003898 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003899
Evan Roskya1f1e152019-01-24 16:17:46 -08003900 bool primaryDisplayOnly = false;
3901
3902 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3903 // TODO b/64227542
3904 if (metadata.has(METADATA_WINDOW_TYPE)) {
3905 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3906 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003907 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003908 primaryDisplayOnly = true;
3909 }
3910 }
3911
Mathias Agopian3165cc22012-08-08 19:42:09 -07003912 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003913 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003914 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3915 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003916
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003917 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003918 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003919 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003920 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003921 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003922 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003923 // check if buffer size is set for color layer.
3924 if (w > 0 || h > 0) {
3925 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3926 int(w), int(h));
3927 return BAD_VALUE;
3928 }
3929
Vishnu Nairfa247b12020-02-11 08:58:26 -08003930 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3931 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003932 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003933 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003934 // check if buffer size is set for container layer.
3935 if (w > 0 || h > 0) {
3936 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3937 int(w), int(h));
3938 return BAD_VALUE;
3939 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003940 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3941 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003942 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003943 default:
3944 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003945 break;
3946 }
3947
Dan Stoza7d89d062015-04-30 13:29:25 -07003948 if (result != NO_ERROR) {
3949 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003950 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003951
Evan Roskya1f1e152019-01-24 16:17:46 -08003952 if (primaryDisplayOnly) {
3953 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003954 }
3955
Robert Carrb89ea9d2018-12-10 13:01:14 -08003956 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003957 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3958 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003959 if (result != NO_ERROR) {
3960 return result;
3961 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003962 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003963
3964 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003965 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003966}
3967
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003968std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3969 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003970
3971 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003972 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003973
Dan Stoza436ccf32018-06-21 12:10:12 -07003974 // Grab the state lock since we're accessing mCurrentState
3975 Mutex::Autolock lock(mStateLock);
3976
Cody Northropbc755282017-03-31 12:00:08 -06003977 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003978 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003979 while (matchFound) {
3980 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003981 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003982 if (layer->getName() == uniqueName) {
3983 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003984 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003985 }
3986 });
3987 }
3988
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003989 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003990 return uniqueName;
3991}
3992
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003993status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003994 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003995 LayerMetadata metadata, PixelFormat& format,
3996 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003997 sp<IGraphicBufferProducer>* gbp,
3998 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003999 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004000 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004001 case PIXEL_FORMAT_TRANSPARENT:
4002 case PIXEL_FORMAT_TRANSLUCENT:
4003 format = PIXEL_FORMAT_RGBA_8888;
4004 break;
4005 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004006 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004007 break;
4008 }
4009
chaviwb4c6e582019-08-16 14:35:07 -07004010 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004011 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004012 args.textureName = getNewTexture();
4013 {
4014 // Grab the SF state lock during this since it's the only safe way to access
4015 // RenderEngine when creating a BufferLayerConsumer
4016 // TODO: Check if this lock is still needed here
4017 Mutex::Autolock lock(mStateLock);
4018 layer = getFactory().createBufferQueueLayer(args);
4019 }
4020
Marissa Wallfd668622018-05-10 10:21:13 -07004021 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004022 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004023 *handle = layer->getHandle();
4024 *gbp = layer->getProducer();
4025 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004026 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004027
Marissa Wallfd668622018-05-10 10:21:13 -07004028 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004029 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004030}
4031
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004032status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004033 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004034 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004035 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004036 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004037 args.displayDevice = getDefaultDisplayDevice();
4038 args.textureName = getNewTexture();
4039 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004040 if (outTransformHint) {
4041 *outTransformHint = layer->getTransformHint();
4042 }
Marissa Wall61c58622018-07-18 10:12:20 -07004043 *handle = layer->getHandle();
4044 *outLayer = layer;
4045
4046 return NO_ERROR;
4047}
4048
Vishnu Nairfa247b12020-02-11 08:58:26 -08004049status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4050 uint32_t h, uint32_t flags, LayerMetadata metadata,
4051 sp<IBinder>* handle, sp<Layer>* outLayer) {
4052 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004053 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004054 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004055 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004056}
4057
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004058status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004059 uint32_t w, uint32_t h, uint32_t flags,
4060 LayerMetadata metadata, sp<IBinder>* handle,
4061 sp<Layer>* outLayer) {
4062 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004063 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004064 *handle = (*outLayer)->getHandle();
4065 return NO_ERROR;
4066}
4067
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004068void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004069 mLayersPendingRemoval.add(layer);
4070 mLayersRemoved = true;
4071 setTransactionFlags(eTransactionNeeded);
4072}
4073
Robert Carr695d5282018-12-18 15:27:58 -08004074void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004075{
Robert Carr2e102c92018-10-23 12:11:15 -07004076 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004077 // If a layer has a parent, we allow it to out-live it's handle
4078 // with the idea that the parent holds a reference and will eventually
4079 // be cleaned up. However no one cleans up the top-level so we do so
4080 // here.
4081 if (layer->getParent() == nullptr) {
4082 mCurrentState.layersSortedByZ.remove(layer);
4083 }
4084 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004085
4086 auto it = mLayersByLocalBinderToken.begin();
4087 while (it != mLayersByLocalBinderToken.end()) {
4088 if (it->second == layer) {
4089 it = mLayersByLocalBinderToken.erase(it);
4090 } else {
4091 it++;
4092 }
4093 }
4094
Robert Carr695d5282018-12-18 15:27:58 -08004095 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004096}
4097
Mathias Agopianb60314a2012-04-10 22:09:54 -07004098// ---------------------------------------------------------------------------
4099
Andy McFadden13a082e2012-08-24 10:16:42 -07004100void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004101 const auto display = getDefaultDisplayDeviceLocked();
4102 if (!display) return;
4103
4104 const sp<IBinder> token = display->getDisplayToken().promote();
4105 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004106
Jesse Hall01e29052013-02-19 16:13:35 -08004107 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004108 Vector<ComposerState> state;
4109 Vector<DisplayState> displays;
4110 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004111 d.what = DisplayState::eDisplayProjectionChanged |
4112 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004113 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004114 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004115 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004116 d.frame.makeInvalid();
4117 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004118 d.width = 0;
4119 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004120 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004121 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4122 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004123
Peiyong Lin65248e02020-04-18 21:15:07 -07004124 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004125
Dominik Laskowski83b88212018-12-11 13:34:06 -08004126 const nsecs_t vsyncPeriod = getVsyncPeriod();
4127 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004128
Brian Andersond0010582017-03-07 13:20:31 -08004129 // Use phase of 0 since phase is not known.
4130 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004131 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004132 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004133}
4134
4135void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004136 // Async since we may be called from the main thread.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004137 static_cast<void>(schedule([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004138}
4139
Peiyong Line9d809e2020-04-14 13:10:48 -07004140void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, hal::Vsync enabled) {
Ady Abraham27c70212019-06-11 10:52:26 -07004141 if (mHWCVsyncState != enabled) {
4142 getHwComposer().setVsyncEnabled(displayId, enabled);
4143 mHWCVsyncState = enabled;
4144 }
4145}
4146
Peiyong Lin65248e02020-04-18 21:15:07 -07004147void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004148 if (display->isVirtual()) {
4149 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004150 return;
4151 }
4152
Dominik Laskowski075d3172018-05-24 15:50:06 -07004153 const auto displayId = display->getId();
4154 LOG_ALWAYS_FATAL_IF(!displayId);
4155
Dominik Laskowski34157762018-10-31 13:07:19 -07004156 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004157
Peiyong Lin65248e02020-04-18 21:15:07 -07004158 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004159 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004160 return;
4161 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004162
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004163 display->setPowerMode(mode);
4164
Lloyd Pique4dccc412018-01-22 17:21:36 -08004165 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004166 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004167 }
4168
Peiyong Lin65248e02020-04-18 21:15:07 -07004169 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004170 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4171 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4172 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004173 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004174 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004175 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004176 mScheduler->onScreenAcquired(mAppConnectionHandle);
4177 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004178 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004179
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004180 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004181 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004182 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004183 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004184 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004185 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4186 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004187 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004188 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004189 mScheduler->disableHardwareVsync(true);
4190 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004191 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004192
Ady Abraham27c70212019-06-11 10:52:26 -07004193 // Make sure HWVsync is disabled before turning off the display
Peiyong Line9d809e2020-04-14 13:10:48 -07004194 setVsyncEnabledInHWC(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004195
Dominik Laskowski075d3172018-05-24 15:50:06 -07004196 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004197 mVisibleRegionsDirty = true;
4198 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004199 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004200 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004201 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004202 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004203 mScheduler->onScreenAcquired(mAppConnectionHandle);
4204 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004205 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004206 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004207 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004208 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004209 mScheduler->disableHardwareVsync(true);
4210 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004211 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004212 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004213 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004214 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004215 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004216 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004217
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004218 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004219 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004220 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004221 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004222 }
4223
Dominik Laskowski34157762018-10-31 13:07:19 -07004224 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004225}
4226
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004227void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004228 schedule([=]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004229 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004230 if (!display) {
4231 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4232 displayToken.get());
4233 } else if (display->isVirtual()) {
4234 ALOGW("Attempt to set power mode %d for virtual display", mode);
4235 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004236 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004237 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004238 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004239}
4240
Dominik Laskowskic2867142019-01-21 11:33:38 -08004241status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4242 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004243 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004244
Mathias Agopianbd115332013-04-18 16:41:04 -07004245 IPCThreadState* ipc = IPCThreadState::self();
4246 const int pid = ipc->getCallingPid();
4247 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004248
Mathias Agopianbd115332013-04-18 16:41:04 -07004249 if ((uid != AID_SHELL) &&
4250 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004251 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4252 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004253 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004254 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004255 // (this would indicate SF is stuck, but we want to be able to
4256 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004257 status_t err = mStateLock.timedLock(s2ns(1));
4258 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004259 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004260 StringAppendF(&result,
4261 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4262 "(no locks held)\n",
4263 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004264 }
4265
Dominik Laskowskic2867142019-01-21 11:33:38 -08004266 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004267 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004268 {"--dispsync"s,
4269 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004270 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004271 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4272 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4273 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4274 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4275 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4276 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004277 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004278 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4279 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004280
Dominik Laskowskic2867142019-01-21 11:33:38 -08004281 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004282
Dominik Laskowski46470112019-08-02 13:13:11 -07004283 const auto it = dumpers.find(flag);
4284 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004285 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004286 } else if (!asProto) {
4287 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004288 }
4289
Mathias Agopian9795c422009-08-26 16:36:26 -07004290 if (locked) {
4291 mStateLock.unlock();
4292 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004293
Dominik Laskowski46470112019-08-02 13:13:11 -07004294 if (it == dumpers.end()) {
4295 const LayersProto layersProto = dumpProtoFromMainThread();
4296 if (asProto) {
4297 result.append(layersProto.SerializeAsString());
4298 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004299 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004300 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4301 result.append(LayerProtoParser::layerTreeToString(layerTree));
4302 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004303 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004304 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004305 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004306 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004307 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004308 return NO_ERROR;
4309}
4310
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004311status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4312 if (asProto && mTracing.isEnabled()) {
4313 mTracing.writeToFileAsync();
4314 }
4315
4316 return doDump(fd, DumpArgs(), asProto);
4317}
4318
Dominik Laskowskic2867142019-01-21 11:33:38 -08004319void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004320 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004321 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004322}
4323
Dominik Laskowskic2867142019-01-21 11:33:38 -08004324void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004325 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004326
Dominik Laskowskic2867142019-01-21 11:33:38 -08004327 if (args.size() > 1) {
4328 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004329 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004330 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004331 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004332 }
Robert Carr2047fae2016-11-28 14:09:09 -08004333 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004334 } else {
4335 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004336 }
4337}
4338
Dominik Laskowskic2867142019-01-21 11:33:38 -08004339void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004340 const bool clearAll = args.size() < 2;
4341 const auto name = clearAll ? String8() : String8(args[1]);
4342
Edgar Arriaga844fa672020-01-16 14:21:42 -08004343 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004344 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004345 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004346 }
Robert Carr2047fae2016-11-28 14:09:09 -08004347 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004348
Svetoslavd85084b2014-03-20 10:28:31 -07004349 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004350}
4351
Dominik Laskowskic2867142019-01-21 11:33:38 -08004352void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4353 mTimeStats->parseArgs(asProto, args, result);
4354}
4355
Jamie Gennis6547ff42013-07-16 20:12:42 -07004356// This should only be called from the main thread. Otherwise it would need
4357// the lock and should use mCurrentState rather than mDrawingState.
4358void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004359 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004360 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004361 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004362
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004363 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004364}
4365
Yiwei Zhang5434a782018-12-05 18:06:32 -08004366void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004367 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004368
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004369 if (isLayerTripleBufferingDisabled())
4370 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004371
Yiwei Zhang5434a782018-12-05 18:06:32 -08004372 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4373 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4374 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4375 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4376 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4377 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004378 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004379}
4380
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004381void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004382 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004383
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004384 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004385 result.append("\n");
4386
Ady Abraham9e16a482019-12-03 17:19:41 -08004387 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004388 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004389 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004390 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004391
Steven Thomasd4071902020-03-24 16:02:53 -07004392 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004393 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004394 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004395 ", min: %.2f Hz, max: %.2f Hz",
Steven Thomasd4071902020-03-24 16:02:53 -07004396 policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004397 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4398 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004399 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4400 if (currentPolicy != policy) {
4401 StringAppendF(&result,
4402 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
4403 ", min: %.2f Hz, max: %.2f Hz\n\n",
4404 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
4405 currentPolicy.maxRefreshRate);
4406 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004407
Ana Krulecc2870422019-01-29 19:00:58 -08004408 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004409 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004410}
4411
Yiwei Zhang5434a782018-12-05 18:06:32 -08004412void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4413 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004414 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4415 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004416 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004417 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004418 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004419 }
David Sodman4a36e932017-11-07 14:29:47 -08004420 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004421 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004422 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004423 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4424 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004425}
4426
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004427void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4428 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004429 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4430 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004431 for (const auto& segment : history) {
4432 if (!segment.usedThirdBuffer) {
4433 stats.twoBufferTime += segment.totalTime;
4434 }
4435 if (segment.occupancyAverage < 1.0f) {
4436 stats.doubleBufferedTime += segment.totalTime;
4437 } else if (segment.occupancyAverage < 2.0f) {
4438 stats.tripleBufferedTime += segment.totalTime;
4439 }
4440 ++stats.numSegments;
4441 stats.totalTime += segment.totalTime;
4442 }
4443}
4444
Yiwei Zhang5434a782018-12-05 18:06:32 -08004445void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4446 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004447
4448 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4449 const size_t count = currentLayers.size();
4450 for (size_t i=0 ; i<count ; i++) {
4451 currentLayers[i]->dumpFrameEvents(result);
4452 }
4453}
4454
Yiwei Zhang5434a782018-12-05 18:06:32 -08004455void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004456 result.append("Buffering stats:\n");
4457 result.append(" [Layer name] <Active time> <Two buffer> "
4458 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004459 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004460 typedef std::tuple<std::string, float, float, float> BufferTuple;
4461 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004462 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004463 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004464 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004465 if (stats.numSegments == 0) {
4466 continue;
4467 }
4468 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4469 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4470 stats.totalTime;
4471 float doubleBufferRatio = static_cast<float>(
4472 stats.doubleBufferedTime) / stats.totalTime;
4473 float tripleBufferRatio = static_cast<float>(
4474 stats.tripleBufferedTime) / stats.totalTime;
4475 sorted.insert({activeTime, {name, twoBufferRatio,
4476 doubleBufferRatio, tripleBufferRatio}});
4477 }
4478 for (const auto& sortedPair : sorted) {
4479 float activeTime = sortedPair.first;
4480 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004481 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4482 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004483 }
4484 result.append("\n");
4485}
4486
Yiwei Zhang5434a782018-12-05 18:06:32 -08004487void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004488 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004489 const auto displayId = display->getId();
4490 if (!displayId) {
4491 continue;
4492 }
4493 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004494 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004495 continue;
4496 }
4497
Yiwei Zhang5434a782018-12-05 18:06:32 -08004498 StringAppendF(&result,
4499 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4500 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004501 uint8_t port;
4502 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004503 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004504 result.append("no identification data\n");
4505 continue;
4506 }
4507
4508 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004509 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004510 continue;
4511 }
4512
4513 const auto edid = parseEdid(data);
4514 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004515 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004516 continue;
4517 }
4518
Yiwei Zhang5434a782018-12-05 18:06:32 -08004519 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004520 result.append(edid->displayName.data(), edid->displayName.length());
4521 result.append("\"\n");
4522 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004523}
4524
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004525void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4526 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004527 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004528 uint8_t port;
4529 DisplayIdentificationData data;
4530
4531 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4532 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4533 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4534 }
4535}
4536
Yiwei Zhang5434a782018-12-05 18:06:32 -08004537void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004538 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004539 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4540 StringAppendF(&result, "DisplayColorSetting: %s\n",
4541 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004542
4543 // TODO: print out if wide-color mode is active or not
4544
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004545 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004546 const auto displayId = display->getId();
4547 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004548 continue;
4549 }
4550
Yiwei Zhang5434a782018-12-05 18:06:32 -08004551 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004552 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004553 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004554 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004555 }
4556
Lloyd Pique32cbe282018-10-19 13:09:22 -07004557 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004558 StringAppendF(&result, " Current color mode: %s (%d)\n",
4559 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004560 }
4561 result.append("\n");
4562}
4563
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004564LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4565 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
4566 const auto display = getDefaultDisplayDeviceLocked();
4567
chaviw1d044282017-09-27 12:19:28 -07004568 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004569 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004570 layer->writeToProto(layersProto, traceFlags, display);
chaviw08f3cb22020-01-13 13:17:21 -08004571 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004572
chaviw1d044282017-09-27 12:19:28 -07004573 return layersProto;
4574}
4575
Alec Mouri6b9e9912020-01-21 10:50:24 -08004576void SurfaceFlinger::dumpHwc(std::string& result) const {
4577 getHwComposer().dump(result);
4578}
4579
Vishnu Nair0f085c62019-08-30 08:49:12 -07004580void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4581 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4582 // it.
4583 LayerProto* rootProto = layersProto.add_layers();
4584 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4585 rootProto->set_id(offscreenRootLayerId);
4586 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004587 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004588
4589 for (Layer* offscreenLayer : mOffscreenLayers) {
4590 // Add layer as child of the fake root
4591 rootProto->add_children(offscreenLayer->sequence);
4592
4593 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004594 LayerProto* layerProto =
4595 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004596 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004597 }
4598}
4599
Vishnu Nair8406fd72019-07-30 11:29:31 -07004600LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004601 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004602}
4603
Vishnu Nair0f085c62019-08-30 08:49:12 -07004604void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4605 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004606 result.append(schedule([this] {
4607 std::string result;
4608 for (Layer* offscreenLayer : mOffscreenLayers) {
4609 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4610 [&](Layer* layer) {
4611 layer->dumpCallingUidPid(result);
4612 });
4613 }
4614 return result;
4615 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004616}
4617
Dominik Laskowskic2867142019-01-21 11:33:38 -08004618void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4619 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004620 Colorizer colorizer(colorize);
4621
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004622 // figure out if we're stuck somewhere
4623 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004624 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004625 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4626
4627 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004628 * Dump library configuration.
4629 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004630
4631 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004632 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004633 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004634 appendSfConfigString(result);
4635 appendUiConfigString(result);
4636 appendGuiConfigString(result);
4637 result.append("\n");
4638
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004639 result.append("\nDisplay identification data:\n");
4640 dumpDisplayIdentificationData(result);
4641
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004642 result.append("\nWide-Color information:\n");
4643 dumpWideColorInfo(result);
4644
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004645 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004646 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004647 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004648 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004649 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004650
Andy McFadden41d67d72014-04-25 16:58:34 -07004651 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004652 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004653 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004654 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004655 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004656
Dan Stozab90cf072015-03-05 11:05:59 -08004657 dumpStaticScreenStats(result);
4658 result.append("\n");
4659
Alec Mouri40189b02019-03-05 15:07:54 -08004660 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4661 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4662 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004663
Dan Stozae77c7662016-05-13 11:37:28 -07004664 dumpBufferingStats(result);
4665
Andy McFadden4803b742012-09-24 19:07:20 -07004666 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004667 * Dump the visible layer list
4668 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004669 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004670 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004671 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4672 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004673 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004674
Chia-I Wu2f884132018-09-13 15:17:58 -07004675 {
Lloyd Pique207def92019-02-28 16:09:52 -08004676 StringAppendF(&result, "Composition layers\n");
4677 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004678 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08004679 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08004680
4681 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4682 layer->getDebugName() ? layer->getDebugName()
4683 : "<unknown>");
4684 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004685 });
4686 }
4687
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004688 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004689 * Dump Display state
4690 */
4691
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004692 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004693 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004694 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004695 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004696 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004697 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004698 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004699
4700 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004701 * Dump CompositionEngine state
4702 */
4703
4704 mCompositionEngine->dump(result);
4705
4706 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004707 * Dump SurfaceFlinger global state
4708 */
4709
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004710 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004711 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004712 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004713
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004714 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004715
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004716 DebugEGLImageTracker::getInstance()->dump(result);
4717
Dominik Laskowski075d3172018-05-24 15:50:06 -07004718 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004719 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4720 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004721 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4722 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004723 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004724 StringAppendF(&result,
4725 " transaction-flags : %08x\n"
4726 " gpu_to_cpu_unsupported : %d\n",
4727 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004728
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004729 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004730 displayId && getHwComposer().isConnected(*displayId)) {
4731 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004732 StringAppendF(&result,
4733 " refresh-rate : %f fps\n"
4734 " x-dpi : %f\n"
4735 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004736 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4737 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004738 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004739
Yiwei Zhang5434a782018-12-05 18:06:32 -08004740 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004741
Dan Stozae22aec72016-08-01 13:20:59 -07004742 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004743 * Tracing state
4744 */
4745 mTracing.dump(result);
4746 result.append("\n");
4747
4748 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004749 * HWC layer minidump
4750 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004751 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004752 const auto displayId = display->getId();
4753 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004754 continue;
4755 }
4756
Yiwei Zhang5434a782018-12-05 18:06:32 -08004757 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004758 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004759 const sp<DisplayDevice> displayDevice = display;
4760 mCurrentState.traverseInZOrder(
4761 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004762 result.append("\n");
4763 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004764
4765 /*
4766 * Dump HWComposer state
4767 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004768 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004769 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004770 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004771 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004772 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004773 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004774
4775 /*
4776 * Dump gralloc state
4777 */
4778 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4779 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004780
4781 /*
4782 * Dump VrFlinger state if in use.
4783 */
4784 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4785 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004786 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004787 result.append("\n");
4788 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004789
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004790 result.append(mTimeStats->miniDump());
4791 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004792}
4793
Chia-I Wu28f320b2018-05-03 11:02:56 -07004794void SurfaceFlinger::updateColorMatrixLocked() {
4795 mat4 colorMatrix;
4796 if (mGlobalSaturationFactor != 1.0f) {
4797 // Rec.709 luma coefficients
4798 float3 luminance{0.213f, 0.715f, 0.072f};
4799 luminance *= 1.0f - mGlobalSaturationFactor;
4800 mat4 saturationMatrix = mat4(
4801 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4802 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4803 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4804 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4805 );
4806 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4807 } else {
4808 colorMatrix = mClientColorMatrix * mDaltonizer();
4809 }
4810
4811 if (mCurrentState.colorMatrix != colorMatrix) {
4812 mCurrentState.colorMatrix = colorMatrix;
4813 mCurrentState.colorMatrixChanged = true;
4814 setTransactionFlags(eTransactionNeeded);
4815 }
4816}
4817
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004818status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004819#pragma clang diagnostic push
4820#pragma clang diagnostic error "-Wswitch-enum"
4821 switch (static_cast<ISurfaceComposerTag>(code)) {
4822 // These methods should at minimum make sure that the client requested
4823 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004824 case BOOT_FINISHED:
4825 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004826 case CREATE_DISPLAY:
4827 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004828 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004829 case GET_ANIMATION_FRAME_STATS:
4830 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004831 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004832 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004833 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004834 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4835 case SET_AUTO_LOW_LATENCY_MODE:
4836 case GET_GAME_CONTENT_TYPE_SUPPORT:
4837 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004838 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004839 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004840 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004841 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004842 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004843 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004844 case SET_GLOBAL_SHADOW_SETTINGS:
4845 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4846 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4847 // necessary permission dynamically. Don't use the permission cache for this check.
4848 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4849 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004850 IPCThreadState* ipc = IPCThreadState::self();
4851 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4852 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004853 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004854 }
Robert Carr1db73f62016-12-21 12:58:51 -08004855 return OK;
4856 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004857 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004858 IPCThreadState* ipc = IPCThreadState::self();
4859 const int pid = ipc->getCallingPid();
4860 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004861 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4862 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004863 return PERMISSION_DENIED;
4864 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004865 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004866 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004867 // Used by apps to hook Choreographer to SurfaceFlinger.
4868 case CREATE_DISPLAY_EVENT_CONNECTION:
4869 // The following calls are currently used by clients that do not
4870 // request necessary permissions. However, they do not expose any secret
4871 // information, so it is OK to pass them.
4872 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004873 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004874 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004875 case GET_PHYSICAL_DISPLAY_IDS:
4876 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004877 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004878 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004879 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004880 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004881 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004882 case GET_DISPLAY_STATS:
4883 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4884 // Calling setTransactionState is safe, because you need to have been
4885 // granted a reference to Client* and Handle* to do anything with it.
4886 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004887 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004888 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004889 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004890 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004891 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004892 // setFrameRate() is deliberately available for apps to call without any
4893 // special permissions.
4894 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004895 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4896 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004897 return OK;
4898 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004899 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004900 case CAPTURE_SCREEN:
4901 case ADD_REGION_SAMPLING_LISTENER:
4902 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004903 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004904 IPCThreadState* ipc = IPCThreadState::self();
4905 const int pid = ipc->getCallingPid();
4906 const int uid = ipc->getCallingUid();
4907 if ((uid != AID_GRAPHICS) &&
4908 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4909 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4910 return PERMISSION_DENIED;
4911 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004912 return OK;
4913 }
chaviw93df2ea2019-04-30 16:45:12 -07004914 case CAPTURE_SCREEN_BY_ID: {
4915 IPCThreadState* ipc = IPCThreadState::self();
4916 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004917 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004918 return OK;
4919 }
4920 return PERMISSION_DENIED;
4921 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004922 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004923
4924 // These codes are used for the IBinder protocol to either interrogate the recipient
4925 // side of the transaction for its canonical interface descriptor or to dump its state.
4926 // We let them pass by default.
4927 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4928 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4929 code == IBinder::SYSPROPS_TRANSACTION) {
4930 return OK;
4931 }
Ady Abraham07e54702020-04-16 15:05:37 -07004932 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004933 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004934 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004935 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4936 return OK;
4937 }
4938 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4939 return PERMISSION_DENIED;
4940#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004941}
4942
Ana Krulec13be8ad2018-08-21 02:43:56 +00004943status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4944 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004945 status_t credentialCheck = CheckTransactCodeCredentials(code);
4946 if (credentialCheck != OK) {
4947 return credentialCheck;
4948 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004949
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004950 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4951 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004952 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004953 IPCThreadState* ipc = IPCThreadState::self();
4954 const int uid = ipc->getCallingUid();
4955 if (CC_UNLIKELY(uid != AID_SYSTEM
4956 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004957 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004958 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004959 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004960 return PERMISSION_DENIED;
4961 }
4962 int n;
4963 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004964 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004965 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004966 return NO_ERROR;
4967 case 1002: // SHOW_UPDATES
4968 n = data.readInt32();
4969 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004970 invalidateHwcGeometry();
4971 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004972 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004973 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004974 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004975 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004976 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004977 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004978 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004979 setTransactionFlags(
4980 eTransactionNeeded|
4981 eDisplayTransactionNeeded|
4982 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004983 return NO_ERROR;
4984 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004985 case 1006:{ // send empty update
4986 signalRefresh();
4987 return NO_ERROR;
4988 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004989 case 1008: // toggle use of hw composer
4990 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004991 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004992 invalidateHwcGeometry();
4993 repaintEverything();
4994 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004995 case 1009: // toggle use of transform hint
4996 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004997 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004998 invalidateHwcGeometry();
4999 repaintEverything();
5000 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005001 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005002 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005003 reply->writeInt32(0);
5004 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005005 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005006 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005007 return NO_ERROR;
5008 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005009 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005010 if (!display) {
5011 return NAME_NOT_FOUND;
5012 }
5013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005014 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005015 return NO_ERROR;
5016 }
5017 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005018 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005019 // daltonize
5020 n = data.readInt32();
5021 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005022 case 1:
5023 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5024 break;
5025 case 2:
5026 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5027 break;
5028 case 3:
5029 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5030 break;
5031 default:
5032 mDaltonizer.setType(ColorBlindnessType::None);
5033 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005034 }
5035 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005036 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005037 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005038 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005039 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005040
5041 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005042 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005043 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005044 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005045 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005046 // apply a color matrix
5047 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005048 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005049 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005050 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005051 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005052 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005053 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005054 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005055 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005056 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005057 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005058
5059 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5060 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005061 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005062 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5063 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5064 }
5065
Chia-I Wu28f320b2018-05-03 11:02:56 -07005066 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005067 return NO_ERROR;
5068 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005069 case 1016: { // Unused.
5070 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005071 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005072 case 1017: {
5073 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005074 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005075 return NO_ERROR;
5076 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005077 case 1018: { // Modify Choreographer's phase offset
5078 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005079 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005080 return NO_ERROR;
5081 }
5082 case 1019: { // Modify SurfaceFlinger's phase offset
5083 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005084 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005085 return NO_ERROR;
5086 }
Irvel468051e2016-06-13 16:44:44 -07005087 case 1020: { // Layer updates interceptor
5088 n = data.readInt32();
5089 if (n) {
5090 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005091 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005092 }
5093 else{
5094 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005095 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005096 }
5097 return NO_ERROR;
5098 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005099 case 1021: { // Disable HWC virtual displays
5100 n = data.readInt32();
5101 mUseHwcVirtualDisplays = !n;
5102 return NO_ERROR;
5103 }
Romain Guy0147a172017-06-01 13:53:56 -07005104 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005105 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005106 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005107
Chia-I Wu28f320b2018-05-03 11:02:56 -07005108 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005109 return NO_ERROR;
5110 }
Romain Guy54f154a2017-10-24 21:40:32 +01005111 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005112 int32_t colorMode;
5113
Chia-I Wu0d711262018-05-21 15:19:35 -07005114 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005115 if (data.readInt32(&colorMode) == NO_ERROR) {
5116 mForceColorMode = static_cast<ColorMode>(colorMode);
5117 }
Romain Guy54f154a2017-10-24 21:40:32 +01005118 invalidateHwcGeometry();
5119 repaintEverything();
5120 return NO_ERROR;
5121 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005122 // Deprecate, use 1030 to check whether the device is color managed.
5123 case 1024: {
5124 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005125 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005126 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005127 n = data.readInt32();
5128 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005129 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005130 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005131 reply->writeInt32(NO_ERROR);
5132 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005133 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005134 mTracingEnabledChanged = mTracing.disable();
5135 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005136 reply->writeInt32(mTracing.writeToFile());
5137 } else {
5138 reply->writeInt32(NO_ERROR);
5139 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005140 }
5141 return NO_ERROR;
5142 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005143 case 1026: { // Get layer tracing status
5144 reply->writeBool(mTracing.isEnabled());
5145 return NO_ERROR;
5146 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005147 // Is a DisplayColorSetting supported?
5148 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005149 const auto display = getDefaultDisplayDevice();
5150 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005151 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005152 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005153
5154 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5155 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005156 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005157 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005158 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005159 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005160 reply->writeBool(true);
5161 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005162 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005163 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005164 break;
5165 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005166 reply->writeBool(
5167 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005168 break;
5169 }
5170 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005171 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005172 // Is VrFlinger active?
5173 case 1028: {
5174 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005175 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005176 return NO_ERROR;
5177 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005178 // Set buffer size for SF tracing (value in KB)
5179 case 1029: {
5180 n = data.readInt32();
5181 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5182 ALOGW("Invalid buffer size: %d KB", n);
5183 reply->writeInt32(BAD_VALUE);
5184 return BAD_VALUE;
5185 }
5186
5187 ALOGD("Updating trace buffer to %d KB", n);
5188 mTracing.setBufferSize(n * 1024);
5189 reply->writeInt32(NO_ERROR);
5190 return NO_ERROR;
5191 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005192 // Is device color managed?
5193 case 1030: {
5194 reply->writeBool(useColorManagement);
5195 return NO_ERROR;
5196 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005197 // Override default composition data space
5198 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5199 // && adb shell stop zygote && adb shell start zygote
5200 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5201 // adb shell stop zygote && adb shell start zygote
5202 case 1031: {
5203 Mutex::Autolock _l(mStateLock);
5204 n = data.readInt32();
5205 if (n) {
5206 n = data.readInt32();
5207 if (n) {
5208 Dataspace dataspace = static_cast<Dataspace>(n);
5209 if (!validateCompositionDataspace(dataspace)) {
5210 return BAD_VALUE;
5211 }
5212 mDefaultCompositionDataspace = dataspace;
5213 }
5214 n = data.readInt32();
5215 if (n) {
5216 Dataspace dataspace = static_cast<Dataspace>(n);
5217 if (!validateCompositionDataspace(dataspace)) {
5218 return BAD_VALUE;
5219 }
5220 mWideColorGamutCompositionDataspace = dataspace;
5221 }
5222 } else {
5223 // restore composition data space.
5224 mDefaultCompositionDataspace = defaultCompositionDataspace;
5225 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5226 }
5227 return NO_ERROR;
5228 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005229 // Set trace flags
5230 case 1033: {
5231 n = data.readUint32();
5232 ALOGD("Updating trace flags to 0x%x", n);
5233 mTracing.setTraceFlags(n);
5234 reply->writeInt32(NO_ERROR);
5235 return NO_ERROR;
5236 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005237 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005238 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005239 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005240 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005241 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005242 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005243 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005244 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005245 } else {
5246 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005247 }
5248 return NO_ERROR;
5249 }
Ady Abraham34392f72019-04-10 11:29:27 -07005250 case 1035: {
5251 n = data.readInt32();
5252 mDebugDisplayConfigSetByBackdoor = false;
5253 if (n >= 0) {
5254 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005255 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005256 if (result != NO_ERROR) {
5257 return result;
5258 }
5259 mDebugDisplayConfigSetByBackdoor = true;
5260 }
5261 return NO_ERROR;
5262 }
Ady Abraham07e54702020-04-16 15:05:37 -07005263 case 1036: {
5264 if (data.readInt32() > 0) {
5265 status_t result =
5266 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5267 if (result != NO_ERROR) {
5268 return result;
5269 }
5270 } else {
5271 mDebugFrameRateFlexibilityToken = nullptr;
5272 }
5273 return NO_ERROR;
5274 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005275 }
5276 }
5277 return err;
5278}
5279
Steven Thomas6d8110b2017-08-31 18:24:21 -07005280void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005281 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005282 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005283}
5284
Ana Krulec7d1d6832018-12-27 11:10:09 -08005285void SurfaceFlinger::repaintEverythingForHWC() {
5286 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005287 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005288 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005289}
5290
Ady Abrahama09852a2020-02-20 14:23:42 -08005291void SurfaceFlinger::kernelTimerChanged(bool expired) {
5292 static bool updateOverlay =
5293 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5294 if (!updateOverlay || !mRefreshRateOverlay) return;
5295
5296 // Update the overlay on the main thread to avoid race conditions with
5297 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005298 static_cast<void>(schedule([=]() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahama09852a2020-02-20 14:23:42 -08005299 if (mRefreshRateOverlay) {
5300 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5301 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005302 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005303 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5304 if (mDesiredActiveConfigChanged) {
5305 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5306 mDesiredActiveConfig.configId);
5307 }
5308
5309 return mRefreshRateConfigs->getCurrentRefreshRate();
5310 }();
5311 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5312
5313 if (current != min) {
5314 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5315 mEventQueue->invalidate();
5316 }
5317 }
5318 }));
5319}
5320
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005321// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5322class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005323public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005324 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5325 ~WindowDisconnector() {
5326 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005327 }
5328
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005329private:
5330 ANativeWindow* mWindow;
5331 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005332};
5333
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005334status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005335 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005336 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5337 const Rect& sourceCrop, uint32_t reqWidth,
5338 uint32_t reqHeight, bool useIdentityTransform,
5339 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005340 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005341
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005342 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005343
Dominik Laskowski718f9602019-11-09 20:01:35 -08005344 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5345 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5346 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5347 renderAreaRotation = ui::Transform::ROT_0;
5348 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005349
Chia-I Wu20261cb2018-08-23 12:55:44 -07005350 sp<DisplayDevice> display;
5351 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005352 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005353
Chia-I Wu20261cb2018-08-23 12:55:44 -07005354 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005355 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005356
Chia-I Wucb023152018-08-28 12:57:23 -07005357 // set the requested width/height to the logical display viewport size
5358 // by default
5359 if (reqWidth == 0 || reqHeight == 0) {
5360 reqWidth = uint32_t(display->getViewport().width());
5361 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005362 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005363 }
5364
Peiyong Lin0e003c92018-09-17 11:09:51 -07005365 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005366 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005367 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5368 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005369 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005370 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005371}
5372
chaviw93df2ea2019-04-30 16:45:12 -07005373static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5374 switch (colorMode) {
5375 case ColorMode::DISPLAY_P3:
5376 case ColorMode::BT2100_PQ:
5377 case ColorMode::BT2100_HLG:
5378 case ColorMode::DISPLAY_BT2020:
5379 return Dataspace::DISPLAY_P3;
5380 default:
5381 return Dataspace::V0_SRGB;
5382 }
5383}
5384
Martin Liu4a322352020-03-24 21:30:38 +08005385status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5386 static constexpr int kFifoPriority = 2;
5387 static constexpr int kOtherPriority = 0;
5388
5389 struct sched_param param = {0};
5390 int sched_policy;
5391 if (enabled) {
5392 sched_policy = SCHED_FIFO;
5393 param.sched_priority = kFifoPriority;
5394 } else {
5395 sched_policy = SCHED_OTHER;
5396 param.sched_priority = kOtherPriority;
5397 }
5398
5399 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5400 return -errno;
5401 }
5402 return NO_ERROR;
5403}
5404
chaviw93df2ea2019-04-30 16:45:12 -07005405const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5406 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5407 if (displayToken) {
5408 return getDisplayDeviceLocked(displayToken);
5409 }
5410 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5411 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005412 return getDisplayByLayerStack(displayOrLayerStack);
5413}
5414
5415const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005416 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005417 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005418 return display;
5419 }
5420 }
5421 return nullptr;
5422}
5423
5424status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5425 sp<GraphicBuffer>* outBuffer) {
5426 sp<DisplayDevice> display;
5427 uint32_t width;
5428 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005429 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005430 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005431 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005432 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5433 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005434 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005435 }
5436
5437 width = uint32_t(display->getViewport().width());
5438 height = uint32_t(display->getViewport().height());
5439
Dominik Laskowski718f9602019-11-09 20:01:35 -08005440 const auto orientation = display->getOrientation();
5441 captureOrientation = ui::Transform::toRotationFlags(orientation);
5442
5443 switch (captureOrientation) {
5444 case ui::Transform::ROT_90:
5445 captureOrientation = ui::Transform::ROT_270;
5446 break;
5447
5448 case ui::Transform::ROT_270:
5449 captureOrientation = ui::Transform::ROT_90;
5450 break;
5451
5452 case ui::Transform::ROT_INVALID:
5453 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5454 captureOrientation = ui::Transform::ROT_0;
5455 break;
5456
5457 default:
5458 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005459 }
chaviw93df2ea2019-04-30 16:45:12 -07005460 *outDataspace =
5461 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5462 }
5463
5464 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5465 false /* captureSecureLayers */);
5466
5467 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5468 std::placeholders::_1);
5469 bool ignored = false;
5470 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5471 false /* useIdentityTransform */,
5472 ignored /* outCapturedSecureLayers */);
5473}
5474
Robert Carr866455f2019-04-02 16:28:26 -07005475status_t SurfaceFlinger::captureLayers(
5476 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5477 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5478 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5479 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005480 ATRACE_CALL();
5481
5482 class LayerRenderArea : public RenderArea {
5483 public:
Robert Carr578038f2018-03-09 12:25:24 -08005484 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005485 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005486 bool childrenOnly, const Rect& displayViewport)
5487 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005488 mLayer(layer),
5489 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005490 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005491 mFlinger(flinger),
5492 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005493 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005494 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005495 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005496 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005497 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005498 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005499 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005500 }
chaviwa76b2712017-09-20 12:02:26 -07005501 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005502 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005503 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005504 Rect getSourceCrop() const override {
5505 if (mCrop.isEmpty()) {
5506 return getBounds();
5507 } else {
5508 return mCrop;
5509 }
5510 }
Robert Carr578038f2018-03-09 12:25:24 -08005511 class ReparentForDrawing {
5512 public:
5513 const sp<Layer>& oldParent;
5514 const sp<Layer>& newParent;
5515
Vishnu Nair4351ad52019-02-11 14:13:02 -08005516 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5517 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005518 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005519 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005520 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5521 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005522 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005523 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005524 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005525 };
5526
5527 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005528 const Rect sourceCrop = getSourceCrop();
5529 // no need to check rotation because there is none
5530 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5531 sourceCrop.height() != getReqHeight();
5532
Robert Carr578038f2018-03-09 12:25:24 -08005533 if (!mChildrenOnly) {
5534 mTransform = mLayer->getTransform().inverse();
5535 drawLayers();
5536 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005537 uint32_t w = static_cast<uint32_t>(getWidth());
5538 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005539 // In the "childrenOnly" case we reparent the children to a screenshot
5540 // layer which has no properties set and which does not draw.
5541 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005542 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5543 "Screenshot Parent"s, w, h, 0,
5544 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005545
Vishnu Nair4351ad52019-02-11 14:13:02 -08005546 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005547 drawLayers();
5548 }
5549 }
chaviwa76b2712017-09-20 12:02:26 -07005550
chaviwa76b2712017-09-20 12:02:26 -07005551 private:
chaviw7206d492017-11-10 16:16:12 -08005552 const sp<Layer> mLayer;
5553 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005554
Peiyong Linefefaac2018-08-17 12:27:51 -07005555 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005556 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005557
5558 SurfaceFlinger* mFlinger;
5559 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005560 };
5561
Robert Carrc0df3122019-04-11 13:18:21 -07005562 int reqWidth = 0;
5563 int reqHeight = 0;
5564 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005565 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005566 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005567 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005568 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005569 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005570
Alec Mouri9a02eda2020-04-21 17:39:34 -07005571 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005572 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5573 ALOGE("captureLayers called with an invalid or removed parent");
5574 return NAME_NOT_FOUND;
5575 }
5576
5577 const int uid = IPCThreadState::self()->getCallingUid();
5578 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5579 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5580 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5581 return PERMISSION_DENIED;
5582 }
5583
Vishnu Nairefc42e22019-12-03 17:36:12 -08005584 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005585 if (sourceCrop.width() <= 0) {
5586 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005587 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005588 }
5589
5590 if (sourceCrop.height() <= 0) {
5591 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005592 crop.bottom = parentSourceBounds.getHeight();
5593 }
5594
5595 if (crop.isEmpty() || frameScale <= 0.0f) {
5596 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5597 // crop was not specified, or an invalid frame scale was provided.
5598 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005599 }
5600 reqWidth = crop.width() * frameScale;
5601 reqHeight = crop.height() * frameScale;
5602
5603 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005604 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005605 if (excludeLayer != nullptr) {
5606 excludeLayers.emplace(excludeLayer);
5607 } else {
5608 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5609 return NAME_NOT_FOUND;
5610 }
5611 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005612
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005613 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005614 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005615 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005616 }
5617
5618 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005619 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005620
Chia-I Wu20261cb2018-08-23 12:55:44 -07005621 // really small crop or frameScale
5622 if (reqWidth <= 0) {
5623 reqWidth = 1;
5624 }
5625 if (reqHeight <= 0) {
5626 reqHeight = 1;
5627 }
5628
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005629 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5630 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005631 auto traverseLayers = [parent, childrenOnly,
5632 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005633 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5634 if (!layer->isVisible()) {
5635 return;
Robert Carr578038f2018-03-09 12:25:24 -08005636 } else if (childrenOnly && layer == parent.get()) {
5637 return;
chaviwa76b2712017-09-20 12:02:26 -07005638 }
Robert Carr866455f2019-04-02 16:28:26 -07005639
5640 sp<Layer> p = layer;
5641 while (p != nullptr) {
5642 if (excludeLayers.count(p) != 0) {
5643 return;
5644 }
5645 p = p->getParent();
5646 }
5647
chaviwa76b2712017-09-20 12:02:26 -07005648 visitor(layer);
5649 });
5650 };
Robert Carr108b2c72019-04-02 16:32:58 -07005651
5652 bool outCapturedSecureLayers = false;
5653 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5654 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005655}
5656
5657status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5658 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005659 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005660 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005661 bool useIdentityTransform,
5662 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005663 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005664
Peiyong Lin0e003c92018-09-17 11:09:51 -07005665 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005666 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5667 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005668 *outBuffer =
5669 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5670 static_cast<android_pixel_format>(reqPixelFormat), 1,
5671 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005672
Robert Carr108b2c72019-04-02 16:32:58 -07005673 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005674 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005675}
5676
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005677status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5678 TraverseLayersFunction traverseLayers,
5679 const sp<GraphicBuffer>& buffer,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005680 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005681 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005682 const int uid = IPCThreadState::self()->getCallingUid();
5683 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5684
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005685 status_t result;
5686 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005687
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005688 do {
5689 std::tie(result, syncFd) =
5690 schedule([&] {
5691 if (mRefreshPending) {
5692 ATRACE_NAME("Skipping screenshot for now");
5693 return std::make_pair(EAGAIN, -1);
5694 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005695
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005696 status_t result = NO_ERROR;
5697 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005698
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005699 Mutex::Autolock lock(mStateLock);
5700 renderArea.render([&] {
5701 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5702 useIdentityTransform, forSystem, &fd,
5703 regionSampling, outCapturedSecureLayers);
5704 });
5705
5706 return std::make_pair(result, fd);
5707 }).get();
5708 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005709
5710 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005711 sync_wait(syncFd, -1);
5712 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005713 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005714
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005715 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005716}
5717
chaviwa76b2712017-09-20 12:02:26 -07005718void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005719 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005720 const sp<GraphicBuffer>& buffer,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005721 bool useIdentityTransform, bool regionSampling,
5722 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005723 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005724
chaviwa76b2712017-09-20 12:02:26 -07005725 const auto reqWidth = renderArea.getReqWidth();
5726 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005727 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005728 const auto transform = renderArea.getTransform();
5729 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005730 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005731
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005732 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005733 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005734
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005735 // assume that bounds are never offset, and that they are the same as the
5736 // buffer bounds.
5737 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005738 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005739 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005740
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005741 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5742 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005743
chaviw50da5042018-04-09 13:49:37 -07005744 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005745
Vishnu Nair9b079a22020-01-21 14:36:08 -08005746 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005747 fillLayer.source.buffer.buffer = nullptr;
5748 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005749 fillLayer.geometry.boundaries =
5750 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005751 fillLayer.alpha = half(alpha);
5752 clientCompositionLayers.push_back(fillLayer);
5753
Yichi Chen40773d92020-04-01 10:10:18 +08005754 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005755 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005756 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005757 const bool supportProtectedContent = false;
5758 Region clip(renderArea.getBounds());
5759 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5760 clip,
5761 useIdentityTransform,
Alec Mouri5a6d8572020-03-23 23:56:15 -07005762 layer->needsFilteringForScreenshots(renderArea.getDisplayDevice(), transform) ||
5763 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005764 renderArea.isSecure(),
5765 supportProtectedContent,
5766 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005767 displayViewport,
5768 clientCompositionDisplay.outputDataspace,
5769 true, /* realContentIsVisible */
5770 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005771 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005772 std::vector<compositionengine::LayerFE::LayerSettings> results =
5773 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005774 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005775 for (auto& settings : results) {
5776 settings.geometry.positionTransform =
5777 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07005778 // There's no need to process blurs when we're executing region sampling,
5779 // we're just trying to understand what we're drawing, and doing so without
5780 // blurs is already a pretty good approximation.
5781 if (regionSampling) {
5782 settings.backgroundBlurRadius = 0;
5783 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005784 }
Yichi Chen40773d92020-04-01 10:10:18 +08005785 clientCompositionLayers.insert(clientCompositionLayers.end(),
5786 std::make_move_iterator(results.begin()),
5787 std::make_move_iterator(results.end()));
5788 renderedLayers.push_back(layer);
5789 }
chaviwa76b2712017-09-20 12:02:26 -07005790 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005791
Yichi Chen40773d92020-04-01 10:10:18 +08005792 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5793 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005794 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005795 clientCompositionLayerPointers.begin(),
5796 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005797
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005798 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005799 // Use an empty fence for the buffer fence, since we just created the buffer so
5800 // there is no need for synchronization with the GPU.
5801 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005802 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005803 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005804 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005805 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005806
5807 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005808
5809 if (*outSyncFd >= 0) {
5810 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5811 for (auto* layer : renderedLayers) {
5812 layer->onLayerDisplayed(releaseFence);
5813 }
5814 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005815}
5816
chaviwa76b2712017-09-20 12:02:26 -07005817status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5818 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005819 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005820 bool useIdentityTransform, bool forSystem,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005821 int* outSyncFd, bool regionSampling,
5822 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005823 ATRACE_CALL();
5824
chaviwa76b2712017-09-20 12:02:26 -07005825 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005826 outCapturedSecureLayers =
5827 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005828 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005829
Robert Carr03480e22018-01-04 16:02:06 -08005830 // We allow the system server to take screenshots of secure layers for
5831 // use in situations like the Screen-rotation animation and place
5832 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005833 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005834 ALOGW("FB is protected: PERMISSION_DENIED");
5835 return PERMISSION_DENIED;
5836 }
Lucas Dupin9d763b72020-04-20 18:42:31 -07005837 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5838 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005839 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005840}
5841
chaviw95ef3c42019-02-14 10:55:09 -08005842void SurfaceFlinger::setInputWindowsFinished() {
5843 Mutex::Autolock _l(mStateLock);
5844
5845 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005846
chaviw95ef3c42019-02-14 10:55:09 -08005847 mTransactionCV.broadcast();
5848}
chaviw5f21a5e2019-02-14 10:00:34 -08005849
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005850// ---------------------------------------------------------------------------
5851
Edgar Arriaga844fa672020-01-16 14:21:42 -08005852void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5853 layersSortedByZ.traverse(visitor);
5854}
5855
Dan Stoza412903f2017-04-27 13:42:17 -07005856void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5857 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005858}
5859
Dan Stoza412903f2017-04-27 13:42:17 -07005860void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5861 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005862}
5863
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005864void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005865 const LayerVector::Visitor& visitor) {
5866 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005867 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005868 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005869 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005870 continue;
5871 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005872 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005873 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005874 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005875 return;
5876 }
chaviwa76b2712017-09-20 12:02:26 -07005877 if (!layer->isVisible()) {
5878 return;
5879 }
5880 visitor(layer);
5881 });
5882 }
5883}
5884
Steven Thomasd4071902020-03-24 16:02:53 -07005885status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5886 const sp<DisplayDevice>& display,
5887 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005888 Mutex::Autolock lock(mStateLock);
5889
Steven Thomasd4071902020-03-24 16:02:53 -07005890 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5891 "Can only set override policy on the primary display");
5892 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5893
Dominik Laskowski22488f62019-03-28 09:53:04 -07005894 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005895 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5896 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5897 // it should go thru setDesiredActiveConfig, similar to primary display.
5898 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5899 const auto displayId = display->getId();
5900 LOG_ALWAYS_FATAL_IF(!displayId);
5901
Peiyong Line9d809e2020-04-14 13:10:48 -07005902 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005903 constraints.desiredTimeNanos = systemTime();
5904 constraints.seamlessRequired = false;
5905
Peiyong Line9d809e2020-04-14 13:10:48 -07005906 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005907 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5908 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005909 constraints, &timeline) < 0) {
5910 return BAD_VALUE;
5911 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005912 if (timeline.refreshRequired) {
5913 repaintEverythingForHWC();
5914 }
5915
Steven Thomasd4071902020-03-24 16:02:53 -07005916 display->setActiveConfig(policy->defaultConfig);
5917 const nsecs_t vsyncPeriod = getHwComposer()
5918 .getConfigs(*displayId)[policy->defaultConfig.value()]
5919 ->getVsyncPeriod();
5920 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5921 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005922 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005923 }
5924
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005925 if (mDebugDisplayConfigSetByBackdoor) {
5926 // ignore this request as config is overridden by backdoor
5927 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005928 }
5929
Steven Thomasd4071902020-03-24 16:02:53 -07005930 status_t setPolicyResult = overridePolicy
5931 ? mRefreshRateConfigs->setOverridePolicy(policy)
5932 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5933 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005934 return BAD_VALUE;
5935 }
Steven Thomasd4071902020-03-24 16:02:53 -07005936 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005937 return NO_ERROR;
5938 }
Steven Thomasd4071902020-03-24 16:02:53 -07005939 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005940
5941 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
Steven Thomasd4071902020-03-24 16:02:53 -07005942 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
5943 currentPolicy.maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005944
5945 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5946 // that listeners that care about a change in allowed configs can get the notification.
5947 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005948 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005949 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5950 .getVsyncPeriod();
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005951 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005952 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005953
Ana Krulec3f6a2062020-01-23 15:48:01 -08005954 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005955 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005956 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5957 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005958 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005959 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005960 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005961
Ady Abrahamabc27602020-04-08 17:20:29 -07005962 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5963 ALOGV("switching to Scheduler preferred config %d",
5964 preferredRefreshRate.getConfigId().value());
5965 setDesiredActiveConfig(
5966 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005967 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005968 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5969 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005970 }
5971
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005972 return NO_ERROR;
5973}
5974
Ana Krulec0782b882019-10-15 17:34:54 -07005975status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005976 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005977 float maxRefreshRate) {
5978 ATRACE_CALL();
5979
5980 if (!displayToken) {
5981 return BAD_VALUE;
5982 }
5983
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005984 auto future = schedule([=]() -> status_t {
Ana Krulec234bb162019-11-10 22:55:55 +01005985 const auto display = getDisplayDeviceLocked(displayToken);
5986 if (!display) {
5987 ALOGE("Attempt to set desired display configs for invalid display token %p",
5988 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005989 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01005990 } else if (display->isVirtual()) {
5991 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005992 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01005993 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005994 using Policy = scheduler::RefreshRateConfigs::Policy;
5995 const Policy policy{HwcConfigIndexType(defaultConfig), minRefreshRate, maxRefreshRate};
5996 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005997
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005998 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
5999 }
6000 });
6001
6002 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006003}
6004
6005status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006006 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01006007 float* outMinRefreshRate,
6008 float* outMaxRefreshRate) {
6009 ATRACE_CALL();
6010
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006011 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01006012 return BAD_VALUE;
6013 }
6014
6015 Mutex::Autolock lock(mStateLock);
6016 const auto display = getDisplayDeviceLocked(displayToken);
6017 if (!display) {
6018 return NAME_NOT_FOUND;
6019 }
6020
6021 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006022 scheduler::RefreshRateConfigs::Policy policy =
6023 mRefreshRateConfigs->getDisplayManagerPolicy();
6024 *outDefaultConfig = policy.defaultConfig.value();
6025 *outMinRefreshRate = policy.minRefreshRate;
6026 *outMaxRefreshRate = policy.maxRefreshRate;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006027 return NO_ERROR;
6028 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006029 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006030 } else {
6031 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006032 LOG_FATAL_IF(!displayId);
6033
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006034 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6035 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6036 *outMinRefreshRate = 1e9f / vsyncPeriod;
6037 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6038 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006039 }
Ana Krulec0782b882019-10-15 17:34:54 -07006040}
6041
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006042void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006043 mFlinger->setInputWindowsFinished();
6044}
6045
Alec Mouri9a02eda2020-04-21 17:39:34 -07006046wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6047 Mutex::Autolock _l(mStateLock);
6048 return fromHandleLocked(handle);
6049}
6050
6051wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006052 BBinder* b = nullptr;
6053 if (handle) {
6054 b = handle->localBinder();
6055 }
Robert Carrc0df3122019-04-11 13:18:21 -07006056 if (b == nullptr) {
6057 return nullptr;
6058 }
6059 auto it = mLayersByLocalBinderToken.find(b);
6060 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006061 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006062 }
6063 return nullptr;
6064}
6065
Dominik Laskowski75848362019-11-11 17:57:20 -08006066void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006067 mNumLayers++;
6068 mScheduler->registerLayer(layer);
6069}
6070
6071void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6072 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006073 removeFromOffscreenLayers(layer);
6074}
6075
6076// WARNING: ONLY CALL THIS FROM LAYER DTOR
6077// Here we add children in the current state to offscreen layers and remove the
6078// layer itself from the offscreen layer list. Since
6079// this is the dtor, it is safe to access the current state. This keeps us
6080// from dangling children layers such that they are not reachable from the
6081// Drawing state nor the offscreen layer list
6082// See b/141111965
6083void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6084 for (auto& child : layer->getCurrentChildren()) {
6085 mOffscreenLayers.emplace(child.get());
6086 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006087 mOffscreenLayers.erase(layer);
6088}
6089
Alec Mouri4545a8a2019-08-08 20:05:32 -07006090void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6091 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6092}
6093
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006094status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6095 float lightPosY, float lightPosZ,
6096 float lightRadius) {
6097 Mutex::Autolock _l(mStateLock);
6098 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6099 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6100 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6101 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6102 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6103
6104 // these values are overridden when calculating the shadow settings for a layer.
6105 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6106 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006107 return NO_ERROR;
6108}
6109
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006110const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6111 const {
6112 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6113 // on the work to remove the table in that bug rather than adding more to
6114 // it.
6115 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6116 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6117 // supported, and exposed via the
6118 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6119 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6120 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6121 };
6122 return genericLayerMetadataKeyMap;
6123}
6124
Steven Thomas62a4cf82020-01-31 12:04:03 -08006125status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6126 int8_t compatibility) {
6127 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6128 return BAD_VALUE;
6129 }
6130
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006131 static_cast<void>(schedule([=]() NO_THREAD_SAFETY_ANALYSIS {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006132 Mutex::Autolock lock(mStateLock);
6133 if (authenticateSurfaceTextureLocked(surface)) {
6134 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6135 if (layer->setFrameRate(
6136 Layer::FrameRate(frameRate,
6137 Layer::FrameRate::convertCompatibility(compatibility)))) {
6138 setTransactionFlags(eTraversalNeeded);
6139 }
6140 } else {
6141 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6142 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006143 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006144 return NO_ERROR;
6145 }));
6146
Steven Thomas62a4cf82020-01-31 12:04:03 -08006147 return NO_ERROR;
6148}
6149
Steven Thomasd4071902020-03-24 16:02:53 -07006150status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6151 if (!outToken) {
6152 return BAD_VALUE;
6153 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006154
6155 auto future = schedule([this] {
6156 status_t result = NO_ERROR;
6157 sp<IBinder> token;
6158
Steven Thomasd4071902020-03-24 16:02:53 -07006159 if (mFrameRateFlexibilityTokenCount == 0) {
6160 // |mStateLock| not needed as we are on the main thread
6161 const auto display = getDefaultDisplayDeviceLocked();
6162
6163 // This is a little racy, but not in a way that hurts anything. As we grab the
6164 // defaultConfig from the display manager policy, we could be setting a new display
6165 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6166 // matter for the override policy though, since we set allowGroupSwitching to true, so
6167 // it's not a problem.
6168 scheduler::RefreshRateConfigs::Policy overridePolicy;
6169 overridePolicy.defaultConfig =
6170 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6171 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006172 constexpr bool kOverridePolicy = true;
6173 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006174 }
6175
6176 if (result == NO_ERROR) {
6177 mFrameRateFlexibilityTokenCount++;
6178 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6179 // below, is something to consider carefully. The lifetime of the
6180 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6181 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6182 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6183 // in this case, for two reasons:
6184 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6185 // the program exits is via a crash. So we won't have a situation where the
6186 // SurfaceFlinger object is dead but the process is still up.
6187 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6188 // if condition 1 were changed, the problem would only show up when running CTS tests,
6189 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006190 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006191 [this]() { onFrameRateFlexibilityTokenReleased(); });
6192 ALOGD("Frame rate flexibility token acquired. count=%d",
6193 mFrameRateFlexibilityTokenCount);
6194 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006195
6196 return std::make_pair(result, token);
6197 });
6198
6199 status_t result;
6200 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006201 return result;
6202}
6203
6204void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006205 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006206 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6207 "Failed tracking frame rate flexibility tokens");
6208 mFrameRateFlexibilityTokenCount--;
6209 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6210 if (mFrameRateFlexibilityTokenCount == 0) {
6211 // |mStateLock| not needed as we are on the main thread
6212 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006213 constexpr bool kOverridePolicy = true;
6214 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006215 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6216 }
6217 }));
6218}
6219
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006220} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006221
Mathias Agopian3f844832013-08-07 21:24:32 -07006222#if defined(__gl_h_)
6223#error "don't include gl/gl.h in this file"
6224#endif
6225
6226#if defined(__gl2_h_)
6227#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006228#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006229
6230// TODO(b/129481165): remove the #pragma below and fix conversion issues
6231#pragma clang diagnostic pop // ignored "-Wconversion"