blob: 89853e31c1c999cc41f6b260c4319bd7fcaa8445 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri5f487d42020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri5f487d42020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri5f487d42020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Steven Thomasb02664d2017-07-26 18:48:28 -0700143namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700144
145#pragma clang diagnostic push
146#pragma clang diagnostic error "-Wswitch-enum"
147
148bool isWideColorMode(const ColorMode colorMode) {
149 switch (colorMode) {
150 case ColorMode::DISPLAY_P3:
151 case ColorMode::ADOBE_RGB:
152 case ColorMode::DCI_P3:
153 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700154 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700155 case ColorMode::BT2100_PQ:
156 case ColorMode::BT2100_HLG:
157 return true;
158 case ColorMode::NATIVE:
159 case ColorMode::STANDARD_BT601_625:
160 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
161 case ColorMode::STANDARD_BT601_525:
162 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
163 case ColorMode::STANDARD_BT709:
164 case ColorMode::SRGB:
165 return false;
166 }
167 return false;
168}
169
170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800185// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
186constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
187
188float getDensityFromProperty(const char* property, bool required) {
189 char value[PROPERTY_VALUE_MAX];
190 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
191 if (!density && required) {
192 ALOGE("%s must be defined as a build property", property);
193 return FALLBACK_DENSITY;
194 }
195 return density / 160.f;
196}
197
Peiyong Lin9d846a52018-11-05 13:18:20 -0800198// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
199bool validateCompositionDataspace(Dataspace dataspace) {
200 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
201}
202
Steven Thomasd4071902020-03-24 16:02:53 -0700203class FrameRateFlexibilityToken : public BBinder {
204public:
205 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
206 virtual ~FrameRateFlexibilityToken() { mCallback(); }
207
208private:
209 std::function<void()> mCallback;
210};
211
Steven Thomasb02664d2017-07-26 18:48:28 -0700212} // namespace anonymous
213
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214// ---------------------------------------------------------------------------
215
Mathias Agopian99b49842011-06-27 16:05:52 -0700216const String16 sHardwareTest("android.permission.HARDWARE_TEST");
217const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
218const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
219const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800220const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700221
222// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700223int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700224bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800225uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800226bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800227bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800228int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100229uint32_t SurfaceFlinger::maxGraphicsWidth;
230uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600231bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800232ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700233bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700234bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700235Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
236ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
237Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
238ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800239bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700240
Kalle Raitaa099a242017-01-11 11:17:29 -0800241std::string getHwcServiceName() {
242 char value[PROPERTY_VALUE_MAX] = {};
243 property_get("debug.sf.hwc_service_name", value, "default");
244 ALOGI("Using HWComposer service: '%s'", value);
245 return std::string(value);
246}
247
248bool useTrebleTestingOverride() {
249 char value[PROPERTY_VALUE_MAX] = {};
250 property_get("debug.sf.treble_testing_override", value, "false");
251 ALOGI("Treble testing override: '%s'", value);
252 return std::string(value) == "true";
253}
254
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800255std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
256 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800257 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700258 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800259 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700260 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800261 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700262 return std::string("Enhanced");
263 default:
264 return std::string("Unknown ") +
265 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800266 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800267}
268
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700269SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800270
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700271SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
272 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700273 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700274 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700275 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700276 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700277 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800278 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
279 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800280
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700281SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800282 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800291
Steven Thomas050b2c82017-03-06 11:45:16 -0800292 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800296
Brian Lindahla13f2d52020-03-05 11:54:17 +0100297 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
298 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 mDefaultCompositionDataspace =
305 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700306 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
307 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 defaultCompositionDataspace = mDefaultCompositionDataspace;
309 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
310 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
311 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
312 wideColorGamutCompositionPixelFormat =
313 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700314
Yichi Chenda901bf2019-06-28 14:58:27 +0800315 mColorSpaceAgnosticDataspace =
316 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
317
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900318 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800319
Dominik Laskowski718f9602019-11-09 20:01:35 -0800320 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
321 switch (primary_display_orientation(Values::ORIENTATION_0)) {
322 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800323 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800324 case Values::ORIENTATION_90:
325 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800326 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800327 case Values::ORIENTATION_180:
328 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800329 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800330 case Values::ORIENTATION_270:
331 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800332 break;
333 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800334 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800335
Sundong Ahn85131bd2019-02-18 15:51:53 +0900336 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 // debugging stuff...
339 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700340
Mathias Agopianb4b17302013-03-20 18:36:41 -0700341 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700342 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700343
Alec Mouri5f487d42020-02-06 09:26:19 -0800344 property_get("ro.build.type", value, "user");
345 mIsUserBuild = strcmp(value, "user") == 0;
346
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347 property_get("debug.sf.showupdates", value, "0");
348 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700349
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700350 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000351
352 // DDMS debugging deprecated (b/120782499)
353 property_get("debug.sf.ddms", value, "0");
354 int debugDdms = atoi(value);
355 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700356
357 property_get("debug.sf.disable_backpressure", value, "0");
358 mPropagateBackpressure = !atoi(value);
359 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700360
Ady Abrahamadb9a992019-09-19 21:21:55 +0000361 property_get("debug.sf.enable_gl_backpressure", value, "0");
362 mPropagateBackpressureClientComposition = atoi(value);
363 ALOGI_IF(mPropagateBackpressureClientComposition,
364 "Enabling backpressure propagation for Client Composition");
365
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800366 property_get("debug.sf.enable_hwc_vds", value, "0");
367 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800368 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800370 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800371 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800372 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700373
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800374 property_get("ro.surface_flinger.supports_background_blur", value, "0");
375 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700376 mSupportsBlur = supportsBlurs;
377 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800378 property_get("ro.sf.blurs_are_expensive", value, "0");
379 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800380
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800381 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700382 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
383 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800384 mGraphicBufferProducerListSizeLogThreshold =
385 std::max(static_cast<int>(0.95 *
386 static_cast<double>(mMaxGraphicBufferProducerListSize)),
387 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700388
Dan Stozaec460082018-12-17 15:35:09 -0800389 property_get("debug.sf.luma_sampling", value, "1");
390 mLumaSampling = atoi(value);
391
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800392 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800393 mDisableClientCompositionCache = atoi(value);
394
Romain Guy11d63f42017-07-20 12:47:14 -0700395 // We should be reading 'persist.sys.sf.color_saturation' here
396 // but since /data may be encrypted, we need to wait until after vold
397 // comes online to attempt to read the property. The property is
398 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800399
400 if (useTrebleTestingOverride()) {
401 // Without the override SurfaceFlinger cannot connect to HIDL
402 // services that are not listed in the manifests. Considered
403 // deriving the setting from the set service name, but it
404 // would be brittle if the name that's not 'default' is used
405 // for production purposes later on.
406 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
407 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800408
409 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800410}
411
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800412void SurfaceFlinger::onFirstRef()
413{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800414 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415}
416
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700417SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418
Dan Stozac7014012014-02-14 15:03:43 -0800419void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420{
421 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700422 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423
Andy McFadden13a082e2012-08-24 10:16:42 -0700424 // restore initial conditions (default device unblank, etc)
425 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426
427 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700428 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429}
430
Robert Carr1db73f62016-12-21 12:58:51 -0800431static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700432 status_t err = client->initCheck();
433 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800434 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800435 }
Robert Carr1db73f62016-12-21 12:58:51 -0800436 return nullptr;
437}
438
439sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
440 return initClient(new Client(this));
441}
442
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700443sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
444 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700445{
446 class DisplayToken : public BBinder {
447 sp<SurfaceFlinger> flinger;
448 virtual ~DisplayToken() {
449 // no more references, this display must be terminated
450 Mutex::Autolock _l(flinger->mStateLock);
451 flinger->mCurrentState.displays.removeItem(this);
452 flinger->setTransactionFlags(eDisplayTransactionNeeded);
453 }
454 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700455 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700456 : flinger(flinger) {
457 }
458 };
459
460 sp<BBinder> token = new DisplayToken(this);
461
462 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463 // Display ID is assigned when virtual display is allocated by HWC.
464 DisplayDeviceState state;
465 state.isSecure = secure;
466 state.displayName = displayName;
467 mCurrentState.displays.add(token, state);
468 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700469 return token;
470}
471
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700472void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700473 Mutex::Autolock _l(mStateLock);
474
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
476 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700477 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700478 return;
479 }
480
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
482 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700483 ALOGE("destroyDisplay called for non-virtual display");
484 return;
485 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700486 mInterceptor->saveDisplayDeletion(state.sequenceId);
487 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700488 setTransactionFlags(eDisplayTransactionNeeded);
489}
490
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800491std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
492 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700493
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800494 const auto internalDisplayId = getInternalDisplayIdLocked();
495 if (!internalDisplayId) {
496 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700497 }
498
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800499 std::vector<PhysicalDisplayId> displayIds;
500 displayIds.reserve(mPhysicalDisplayTokens.size());
501 displayIds.push_back(internalDisplayId->value);
502
503 for (const auto& [id, token] : mPhysicalDisplayTokens) {
504 if (id != *internalDisplayId) {
505 displayIds.push_back(id.value);
506 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700508
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800509 return displayIds;
510}
511
512sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
513 Mutex::Autolock lock(mStateLock);
514 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700515}
516
Ady Abraham37965d42018-11-01 13:43:32 -0700517status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
518 if (!outGetColorManagement) {
519 return BAD_VALUE;
520 }
521 *outGetColorManagement = useColorManagement;
522 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700523}
524
Lloyd Pique441d5042018-10-18 16:49:51 -0700525HWComposer& SurfaceFlinger::getHwComposer() const {
526 return mCompositionEngine->getHwComposer();
527}
528
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700529renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
530 return mCompositionEngine->getRenderEngine();
531}
532
Lloyd Pique70d91362018-10-18 16:02:55 -0700533compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
534 return *mCompositionEngine.get();
535}
536
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800537void SurfaceFlinger::bootFinished()
538{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700539 if (mBootFinished == true) {
540 ALOGE("Extra call to bootFinished");
541 return;
542 }
543 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700544 if (mStartPropertySetThread->join() != NO_ERROR) {
545 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800546 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800547 const nsecs_t now = systemTime();
548 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000549 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700550
Mikael Pessa90092f42019-08-26 17:22:04 -0700551 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000552 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700553
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554 // wait patiently for the window manager death
555 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700556 mWindowManager = defaultServiceManager()->getService(name);
557 if (mWindowManager != 0) {
558 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 }
Robert Carr720e5062018-07-30 17:45:14 -0700560 sp<IBinder> input(defaultServiceManager()->getService(
561 String16("inputflinger")));
562 if (input == nullptr) {
563 ALOGE("Failed to link to input service");
564 } else {
565 mInputFlinger = interface_cast<IInputFlinger>(input);
566 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700567
Steven Thomas050b2c82017-03-06 11:45:16 -0800568 if (mVrFlinger) {
569 mVrFlinger->OnBootFinished();
570 }
571
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700572 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700573 // formerly we would just kill the process, but we now ask it to exit so it
574 // can choose where to stop the animation.
575 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700576
577 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
578 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
579 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700580
Ana Krulecbd6654b2019-02-15 15:18:15 -0800581 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800582 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700583 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800584 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800585
Ady Abraham8a82ba62020-01-17 12:43:17 -0800586 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
587 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
588 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
589 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800590 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800591}
592
Dan Stoza436ccf32018-06-21 12:10:12 -0700593uint32_t SurfaceFlinger::getNewTexture() {
594 {
595 std::lock_guard lock(mTexturePoolMutex);
596 if (!mTexturePool.empty()) {
597 uint32_t name = mTexturePool.back();
598 mTexturePool.pop_back();
599 ATRACE_INT("TexturePoolSize", mTexturePool.size());
600 return name;
601 }
602
603 // The pool was too small, so increase it for the future
604 ++mTexturePoolSize;
605 }
606
607 // The pool was empty, so we need to get a new texture name directly using a
608 // blocking call to the main thread
609 uint32_t name = 0;
610 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
611 return name;
612}
613
Mathias Agopian3f844832013-08-07 21:24:32 -0700614void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700615 std::lock_guard lock(mTexturePoolMutex);
616 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
617 // to actually delete this or not based on mTexturePoolSize
618 mTexturePool.push_back(texture);
619 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700620}
621
Wei Wangf9b05ee2017-07-19 20:59:39 -0700622// Do not call property_set on main thread which will be blocked by init
623// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700624void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700625 ALOGI( "SurfaceFlinger's main thread ready to run. "
626 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700627 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800628
Steven Thomasb02664d2017-07-26 18:48:28 -0700629 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700630 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800631 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700632 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
633 renderengine::RenderEngineCreationArgs::Builder()
634 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
635 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
636 .setUseColorManagerment(useColorManagement)
637 .setEnableProtectedContext(enable_protected_contents(false))
638 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700639 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700640 .setContextPriority(useContextPriority
641 ? renderengine::RenderEngine::ContextPriority::HIGH
642 : renderengine::RenderEngine::ContextPriority::MEDIUM)
643 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800644 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700645
646 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
647 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700648 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800649 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800650 // Process any initial hotplug and resulting display changes.
651 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700652 const auto display = getDefaultDisplayDeviceLocked();
653 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700654 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700655 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800656
Steven Thomas050b2c82017-03-06 11:45:16 -0800657 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700658 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700659 // This callback is called from the vr flinger dispatch thread. We
660 // need to call signalTransaction(), which requires holding
661 // mStateLock when we're not on the main thread. Acquiring
662 // mStateLock from the vr flinger dispatch thread might trigger a
663 // deadlock in surface flinger (see b/66916578), so post a message
664 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700665 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700666 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
667 mVrFlingerRequestsDisplay = requestDisplay;
668 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700669 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800670 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
672 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700673 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 .value_or(0),
675 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 if (!mVrFlinger) {
677 ALOGE("Failed to start vrflinger");
678 }
679 }
680
Mathias Agopian92a979a2012-08-02 18:32:23 -0700681 // initialize our drawing state
682 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700683
Andy McFadden13a082e2012-08-24 10:16:42 -0700684 // set initial conditions (e.g. unblank default device)
685 initializeDisplays();
686
Steven Thomas137d4bc2019-07-25 16:55:14 -0700687 char primeShaderCache[PROPERTY_VALUE_MAX];
688 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
689 if (atoi(primeShaderCache)) {
690 getRenderEngine().primeCache();
691 }
Dan Stoza4e637772016-07-28 13:31:51 -0700692
Wei Wangf9b05ee2017-07-19 20:59:39 -0700693 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700694
695 const bool presentFenceReliable =
696 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
697 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698
699 if (mStartPropertySetThread->Start() != NO_ERROR) {
700 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800701 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800702
Dan Stoza9e56aa02015-11-02 13:00:03 -0800703 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700704}
705
Romain Guy11d63f42017-07-20 12:47:14 -0700706void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700707 Mutex::Autolock _l(mStateLock);
708
Romain Guy11d63f42017-07-20 12:47:14 -0700709 char value[PROPERTY_VALUE_MAX];
710
711 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800712 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700713 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800714 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100715
716 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700717 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800718
719 property_get("persist.sys.sf.color_mode", value, "0");
720 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700721
722 property_get("persist.sys.sf.disable_blurs", value, "0");
723 bool disableBlurs = atoi(value);
724 mDisableBlurs = disableBlurs;
725 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700726}
727
Mathias Agopiana67e4182012-06-19 17:26:12 -0700728void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800729 // Start boot animation service by setting a property mailbox
730 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700731 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800732 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700733 if (mStartPropertySetThread->join() != NO_ERROR) {
734 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800735 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700736}
737
Mathias Agopian875d8e12013-06-07 15:35:48 -0700738size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700739 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700740}
741
Mathias Agopian875d8e12013-06-07 15:35:48 -0700742size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700743 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700744}
745
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800746// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800747
Jamie Gennis582270d2011-08-17 18:19:00 -0700748bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800749 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800750 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800751 return authenticateSurfaceTextureLocked(bufferProducer);
752}
753
754bool SurfaceFlinger::authenticateSurfaceTextureLocked(
755 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800756 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800757 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800758}
759
Brian Anderson6b376712017-04-04 10:51:39 -0700760status_t SurfaceFlinger::getSupportedFrameTimestamps(
761 std::vector<FrameEvent>* outSupported) const {
762 *outSupported = {
763 FrameEvent::REQUESTED_PRESENT,
764 FrameEvent::ACQUIRE,
765 FrameEvent::LATCH,
766 FrameEvent::FIRST_REFRESH_START,
767 FrameEvent::LAST_REFRESH_START,
768 FrameEvent::GPU_COMPOSITION_DONE,
769 FrameEvent::DEQUEUE_READY,
770 FrameEvent::RELEASE,
771 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700772 ConditionalLock _l(mStateLock,
773 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700774 if (!getHwComposer().hasCapability(
775 HWC2::Capability::PresentFenceIsNotReliable)) {
776 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
777 }
778 return NO_ERROR;
779}
780
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800781status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
782 if (!displayToken || !state) {
783 return BAD_VALUE;
784 }
785
786 Mutex::Autolock lock(mStateLock);
787
788 const auto display = getDisplayDeviceLocked(displayToken);
789 if (!display) {
790 return NAME_NOT_FOUND;
791 }
792
793 state->layerStack = display->getLayerStack();
794 state->orientation = display->getOrientation();
795
796 const Rect viewport = display->getViewport();
797 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
798
799 return NO_ERROR;
800}
801
802status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
803 if (!displayToken || !info) {
804 return BAD_VALUE;
805 }
806
807 Mutex::Autolock lock(mStateLock);
808
809 const auto display = getDisplayDeviceLocked(displayToken);
810 if (!display) {
811 return NAME_NOT_FOUND;
812 }
813
Dominik Laskowski55c85402020-01-21 16:25:47 -0800814 if (const auto connectionType = display->getConnectionType())
815 info->connectionType = *connectionType;
816 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800817 return INVALID_OPERATION;
818 }
819
820 if (mEmulatedDisplayDensity) {
821 info->density = mEmulatedDisplayDensity;
822 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800823 info->density = info->connectionType == DisplayConnectionType::Internal
824 ? mInternalDisplayDensity
825 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800826 }
827
828 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200829 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800830
831 return NO_ERROR;
832}
833
Dominik Laskowski22488f62019-03-28 09:53:04 -0700834status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800835 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700836 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 return BAD_VALUE;
838 }
839
Dominik Laskowski22488f62019-03-28 09:53:04 -0700840 Mutex::Autolock lock(mStateLock);
841
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800842 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700843 if (!displayId) {
844 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700845 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800847 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700848
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700850
Dominik Laskowski075d3172018-05-24 15:50:06 -0700851 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800852 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700853
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800854 auto width = hwConfig->getWidth();
855 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700856
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800857 auto xDpi = hwConfig->getDpiX();
858 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700859
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800860 if (isInternal &&
861 (internalDisplayOrientation == ui::ROTATION_90 ||
862 internalDisplayOrientation == ui::ROTATION_270)) {
863 std::swap(width, height);
864 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 }
866
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800867 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800868
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800869 if (mEmulatedDisplayDensity) {
870 config.xDpi = mEmulatedDisplayDensity;
871 config.yDpi = mEmulatedDisplayDensity;
872 } else {
873 config.xDpi = xDpi;
874 config.yDpi = yDpi;
875 }
876
877 const nsecs_t period = hwConfig->getVsyncPeriod();
878 config.refreshRate = 1e9f / period;
879
880 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
881 config.appVsyncOffset = offsets.late.app;
882 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800883 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884
Andy McFadden91b2ca82014-06-13 14:04:23 -0700885 // This is how far in advance a buffer must be queued for
886 // presentation at a given time. If you want a buffer to appear
887 // on the screen at time N, you must submit the buffer before
888 // (N - presentationDeadline).
889 //
890 // Normally it's one full refresh period (to give SF a chance to
891 // latch the buffer), but this can be reduced by configuring a
892 // DispSync offset. Any additional delays introduced by the hardware
893 // composer or panel must be accounted for here.
894 //
895 // We add an additional 1ms to allow for processing time and
896 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800897 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700898
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800899 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700900 }
901
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 return NO_ERROR;
903}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700904
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700905status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
906 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700907 return BAD_VALUE;
908 }
909
Ana Krulecc2870422019-01-29 19:00:58 -0800910 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700911 return NO_ERROR;
912}
913
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
915 const auto display = getDisplayDevice(displayToken);
916 if (!display) {
917 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800918 return BAD_VALUE;
919 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700920
Steven Thomasc9098452019-09-30 17:15:05 -0700921 if (display->isPrimary()) {
922 std::lock_guard<std::mutex> lock(mActiveConfigLock);
923 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800924 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700925 }
Steven Thomasc9098452019-09-30 17:15:05 -0700926 }
Ady Abraham2139f732019-11-13 18:56:40 -0800927
928 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700929}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700930
Ady Abraham03b02dd2019-03-21 15:40:11 -0700931void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800932 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800933 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700934 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800935
Ady Abrahamb838aed2019-02-12 15:30:16 -0800936 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800937 if (mDesiredActiveConfigChanged) {
938 // If a config change is pending, just cache the latest request in
939 // mDesiredActiveConfig
940 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
941 mDesiredActiveConfig = info;
942 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
943 } else {
944 // Check is we are already at the desired config
945 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700946 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800947 return;
948 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800949
Ady Abraham59db0a32020-03-02 18:04:20 -0800950 // Initiate a config change.
951 mDesiredActiveConfigChanged = true;
952 mDesiredActiveConfig = info;
953
Ady Abrahamb838aed2019-02-12 15:30:16 -0800954 // This will trigger HWC refresh without resetting the idle timer.
955 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700956 // Start receiving vsync samples now, so that we can detect a period
957 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700958 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700959 // As we called to set period, we will call to onRefreshRateChangeCompleted once
960 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700961 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800962
Ady Abrahamabc27602020-04-08 17:20:29 -0700963 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800964 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700966
967 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800968 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700969 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970}
971
972status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
973 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800974
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100975 if (!displayToken) {
976 return BAD_VALUE;
977 }
Ady Abraham838de062019-02-04 10:24:03 -0800978
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100979 status_t result = NO_ERROR;
980
981 postMessageSync(new LambdaMessage([&]() {
982 const auto display = getDisplayDeviceLocked(displayToken);
983 if (!display) {
984 ALOGE("Attempt to set allowed display configs for invalid display token %p",
985 displayToken.get());
986 result = BAD_VALUE;
987 } else if (display->isVirtual()) {
988 ALOGW("Attempt to set allowed display configs for virtual display");
989 result = BAD_VALUE;
990 } else {
991 HwcConfigIndexType config(mode);
992 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
Steven Thomasd4071902020-03-24 16:02:53 -0700993 result = setDesiredDisplayConfigSpecsInternal(display,
994 scheduler::RefreshRateConfigs::
Ady Abrahamabc27602020-04-08 17:20:29 -0700995 Policy{config,
996 refreshRate.getFps(),
997 refreshRate.getFps()},
Steven Thomasd4071902020-03-24 16:02:53 -0700998 /*overridePolicy=*/false);
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100999 }
1000 }));
1001
1002 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001003}
1004
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001005void SurfaceFlinger::setActiveConfigInternal() {
1006 ATRACE_CALL();
1007
Dominik Laskowski22488f62019-03-28 09:53:04 -07001008 const auto display = getDefaultDisplayDeviceLocked();
1009 if (!display) {
1010 return;
1011 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001012
Alec Mouri8de697e2020-03-19 10:52:01 -07001013 auto& oldRefreshRate =
1014 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1015
Dominik Laskowski22488f62019-03-28 09:53:04 -07001016 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001017 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001018 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001019 display->setActiveConfig(mUpcomingActiveConfig.configId);
1020
Ady Abraham2e1dd892020-03-05 13:48:36 -08001021 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001022 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001023 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001024 mTimeStats->incrementRefreshRateSwitches();
1025 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001026 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001027 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001028 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001029
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001030 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001031 const nsecs_t vsyncPeriod =
1032 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001033 .getVsyncPeriod();
Ady Abraham447052e2019-02-13 16:07:27 -08001034 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001035 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001036 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001037}
1038
Ady Abraham53852a52019-05-28 18:07:44 -07001039void SurfaceFlinger::desiredActiveConfigChangeDone() {
1040 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1041 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1042 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001043
Ady Abraham2e1dd892020-03-05 13:48:36 -08001044 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001045 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001046 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1047 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001048 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001049}
1050
Ady Abraham27cbed72020-04-10 12:56:59 -07001051void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001052 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001053 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001054 // Store the local variable to release the lock.
Ady Abraham27cbed72020-04-10 12:56:59 -07001055 const auto desiredActiveConfig = [&]() -> std::optional<ActiveConfigInfo> {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001056 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham27cbed72020-04-10 12:56:59 -07001057 if (mDesiredActiveConfigChanged) {
1058 return mDesiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001059 }
Ady Abraham27cbed72020-04-10 12:56:59 -07001060 return std::nullopt;
1061 }();
1062
1063 if (!desiredActiveConfig) {
1064 // No desired active config pending to be applied
1065 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001066 }
1067
Ady Abraham2e1dd892020-03-05 13:48:36 -08001068 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001069 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001070 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1071 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001072 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001073 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001074 // display is not valid or we are already in the requested mode
1075 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001076 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001077 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001078 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001079
Ady Abraham838de062019-02-04 10:24:03 -08001080 // Desired active config was set, it is different than the config currently in use, however
1081 // allowed configs might have change by the time we process the refresh.
1082 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001083 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001084 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001085 return;
Ady Abraham838de062019-02-04 10:24:03 -08001086 }
Alec Mouri7f015182019-07-11 13:56:22 -07001087
Ady Abraham27cbed72020-04-10 12:56:59 -07001088 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001089 const auto displayId = display->getId();
1090 LOG_ALWAYS_FATAL_IF(!displayId);
1091
Ady Abrahamabc27602020-04-08 17:20:29 -07001092 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001093
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001094 // TODO(b/142753666) use constrains
1095 HWC2::VsyncPeriodChangeConstraints constraints;
1096 constraints.desiredTimeNanos = systemTime();
1097 constraints.seamlessRequired = false;
1098
1099 HWC2::VsyncPeriodChangeTimeline outTimeline;
1100 auto status =
1101 getHwComposer().setActiveConfigWithConstraints(*displayId,
1102 mUpcomingActiveConfig.configId.value(),
1103 constraints, &outTimeline);
1104 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001105 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1106 // to be sent. We just log the error in this case.
1107 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001108 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001109 }
1110
1111 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1112 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001113 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001114}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001115
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001116status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1117 Vector<ColorMode>* outColorModes) {
1118 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001119 return BAD_VALUE;
1120 }
1121
Peiyong Lina52f0292018-03-14 17:26:31 -07001122 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001123 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001124 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001125 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1126
1127 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1128 if (!displayId) {
1129 return NAME_NOT_FOUND;
1130 }
1131
Dominik Laskowski075d3172018-05-24 15:50:06 -07001132 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001133 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001134 }
Michael Wright28f24d02016-07-12 13:30:53 -07001135 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001136
1137 // If it's built-in display and the configuration claims it's not wide color capable,
1138 // filter out all wide color modes. The typical reason why this happens is that the
1139 // hardware is not good enough to support GPU composition of wide color, and thus the
1140 // OEMs choose to disable this capability.
1141 if (isInternalDisplay && !hasWideColorDisplay) {
1142 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1143 isWideColorMode);
1144 } else {
1145 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1146 }
Michael Wright28f24d02016-07-12 13:30:53 -07001147
1148 return NO_ERROR;
1149}
1150
Daniel Solomon42d04562019-01-20 21:03:19 -08001151status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1152 ui::DisplayPrimaries &primaries) {
1153 if (!displayToken) {
1154 return BAD_VALUE;
1155 }
1156
1157 // Currently we only support this API for a single internal display.
1158 if (getInternalDisplayToken() != displayToken) {
1159 return BAD_VALUE;
1160 }
1161
1162 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1163 return NO_ERROR;
1164}
1165
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001166ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1167 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001168 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001169 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001170 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001171}
1172
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001173status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001174 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001175 Vector<ColorMode> modes;
1176 getDisplayColorModes(displayToken, &modes);
1177 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1178 if (mode < ColorMode::NATIVE || !exists) {
1179 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1180 decodeColorMode(mode).c_str(), mode, displayToken.get());
1181 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001182 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001183 const auto display = getDisplayDevice(displayToken);
1184 if (!display) {
1185 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1186 decodeColorMode(mode).c_str(), mode, displayToken.get());
1187 } else if (display->isVirtual()) {
1188 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1189 decodeColorMode(mode).c_str(), mode);
1190 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001191 display->getCompositionDisplay()->setColorProfile(
1192 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1193 RenderIntent::COLORIMETRIC,
1194 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001195 }
1196 }));
1197
Michael Wright28f24d02016-07-12 13:30:53 -07001198 return NO_ERROR;
1199}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001200
Galia Peycheva5492cb52019-10-30 14:13:16 +01001201status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1202 bool* outSupport) const {
1203 Mutex::Autolock _l(mStateLock);
1204
1205 if (!displayToken) {
1206 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1207 return BAD_VALUE;
1208 }
1209 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1210 if (!displayId) {
1211 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1212 displayToken.get());
1213 return NAME_NOT_FOUND;
1214 }
Dominik Laskowski1162e472020-04-02 19:02:47 -07001215 *outSupport = getHwComposer().hasDisplayCapability(*displayId,
Galia Peycheva5492cb52019-10-30 14:13:16 +01001216 HWC2::DisplayCapability::AutoLowLatencyMode);
1217 return NO_ERROR;
1218}
1219
1220void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1221 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1222}
1223
1224void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1225 if (!displayToken) {
1226 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1227 return;
1228 }
1229 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1230 if (!displayId) {
1231 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1232 displayToken.get());
1233 return;
1234 }
1235
1236 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1237}
1238
1239status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1240 bool* outSupport) const {
1241 Mutex::Autolock _l(mStateLock);
1242
1243 if (!displayToken) {
1244 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1245 return BAD_VALUE;
1246 }
1247 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1248 if (!displayId) {
1249 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1250 displayToken.get());
1251 return NAME_NOT_FOUND;
1252 }
1253
1254 std::vector<HWC2::ContentType> outSupportedContentTypes;
1255 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1256 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1257 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1258 return NO_ERROR;
1259}
1260
1261void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1262 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1263}
1264
1265void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1266 if (!displayToken) {
1267 ALOGE("setGameContentType() failed. Missing display token.");
1268 return;
1269 }
1270 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1271 if (!displayId) {
1272 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1273 displayToken.get());
1274 return;
1275 }
1276
1277 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1278 getHwComposer().setContentType(*displayId, type);
1279}
1280
Svetoslavd85084b2014-03-20 10:28:31 -07001281status_t SurfaceFlinger::clearAnimationFrameStats() {
1282 Mutex::Autolock _l(mStateLock);
1283 mAnimFrameTracker.clearStats();
1284 return NO_ERROR;
1285}
1286
1287status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1288 Mutex::Autolock _l(mStateLock);
1289 mAnimFrameTracker.getStats(outStats);
1290 return NO_ERROR;
1291}
1292
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001293status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1294 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001295 Mutex::Autolock _l(mStateLock);
1296
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001297 const auto display = getDisplayDeviceLocked(displayToken);
1298 if (!display) {
1299 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001300 return BAD_VALUE;
1301 }
1302
Peiyong Linfb069302018-04-25 14:34:31 -07001303 // At this point the DisplayDeivce should already be set up,
1304 // meaning the luminance information is already queried from
1305 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001306 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001307 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1308 capabilities.getDesiredMaxLuminance(),
1309 capabilities.getDesiredMaxAverageLuminance(),
1310 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001311
1312 return NO_ERROR;
1313}
1314
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001315std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1316 const DisplayDevice& display) const {
1317 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1318 // avoid repetitive HAL IPC and EDID parsing.
1319 const auto displayId = display.getId();
1320 LOG_FATAL_IF(!displayId);
1321
1322 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1323 LOG_FATAL_IF(!hwcDisplayId);
1324
1325 uint8_t port;
1326 DisplayIdentificationData data;
1327 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1328 ALOGV("%s: No identification data.", __FUNCTION__);
1329 return {};
1330 }
1331
1332 const auto info = parseDisplayIdentificationData(port, data);
1333 if (!info) {
1334 return {};
1335 }
1336 return info->deviceProductInfo;
1337}
1338
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001339status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1340 ui::PixelFormat* outFormat,
1341 ui::Dataspace* outDataspace,
1342 uint8_t* outComponentMask) const {
1343 if (!outFormat || !outDataspace || !outComponentMask) {
1344 return BAD_VALUE;
1345 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001346 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001347 if (!display || !display->getId()) {
1348 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1349 return BAD_VALUE;
1350 }
1351 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1352 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,
1357 uint64_t maxFrames) const {
1358 const auto display = getDisplayDevice(displayToken);
1359 if (!display || !display->getId()) {
1360 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1361 return BAD_VALUE;
1362 }
1363
1364 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1365 componentMask, maxFrames);
1366}
1367
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001368status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1369 uint64_t maxFrames, uint64_t timestamp,
1370 DisplayedFrameStats* outStats) const {
1371 const auto display = getDisplayDevice(displayToken);
1372 if (!display || !display->getId()) {
1373 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1374 return BAD_VALUE;
1375 }
1376
1377 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1378 outStats);
1379}
1380
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001381status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1382 if (!outSupported) {
1383 return BAD_VALUE;
1384 }
1385 *outSupported = getRenderEngine().supportsProtectedContent();
1386 return NO_ERROR;
1387}
1388
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001389status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1390 bool* outIsWideColorDisplay) const {
1391 if (!displayToken || !outIsWideColorDisplay) {
1392 return BAD_VALUE;
1393 }
1394 Mutex::Autolock _l(mStateLock);
1395 const auto display = getDisplayDeviceLocked(displayToken);
1396 if (!display) {
1397 return BAD_VALUE;
1398 }
Peiyong Linff84a152019-05-17 18:36:19 -07001399
1400 // Use hasWideColorDisplay to override built-in display.
1401 const auto displayId = display->getId();
1402 if (displayId && displayId == getInternalDisplayIdLocked()) {
1403 *outIsWideColorDisplay = hasWideColorDisplay;
1404 return NO_ERROR;
1405 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001406 *outIsWideColorDisplay = display->hasWideColorGamut();
1407 return NO_ERROR;
1408}
1409
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001410status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001411 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001412 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001413
Dominik Laskowski6505f792019-09-18 11:10:05 -07001414 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1415 mEventQueue->setEventConnection(
1416 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001417 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001418 }));
1419
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001420 return NO_ERROR;
1421}
1422
1423status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001424 Mutex::Autolock lock(mStateLock);
1425 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001426}
1427
Lloyd Pique755e3192018-01-31 16:46:15 -08001428status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1429 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001430 // Try to acquire a lock for 1s, fail gracefully
1431 const status_t err = mStateLock.timedLock(s2ns(1));
1432 const bool locked = (err == NO_ERROR);
1433 if (!locked) {
1434 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1435 return TIMED_OUT;
1436 }
1437
1438 outLayers->clear();
1439 mCurrentState.traverseInZOrder([&](Layer* layer) {
1440 outLayers->push_back(layer->getLayerDebugInfo());
1441 });
1442
1443 mStateLock.unlock();
1444 return NO_ERROR;
1445}
1446
Peiyong Linc6780972018-10-28 15:24:08 -07001447status_t SurfaceFlinger::getCompositionPreference(
1448 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1449 Dataspace* outWideColorGamutDataspace,
1450 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001451 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001452 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001453 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001454 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001455 return NO_ERROR;
1456}
1457
Dan Stozaec460082018-12-17 15:35:09 -08001458status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1459 const sp<IBinder>& stopLayerHandle,
1460 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001461 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001462 return BAD_VALUE;
1463 }
1464 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001465 return NO_ERROR;
1466}
1467
Dan Stozaec460082018-12-17 15:35:09 -08001468status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001469 if (!listener) {
1470 return BAD_VALUE;
1471 }
Dan Stozaec460082018-12-17 15:35:09 -08001472 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001473 return NO_ERROR;
1474}
Dan Gittik57e63c52019-01-18 16:37:54 +00001475
1476status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1477 bool* outSupport) const {
1478 if (!displayToken || !outSupport) {
1479 return BAD_VALUE;
1480 }
1481 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1482 if (!displayId) {
1483 return NAME_NOT_FOUND;
1484 }
1485 *outSupport =
Dominik Laskowski1162e472020-04-02 19:02:47 -07001486 getHwComposer().hasDisplayCapability(*displayId, HWC2::DisplayCapability::Brightness);
Dan Gittik57e63c52019-01-18 16:37:54 +00001487 return NO_ERROR;
1488}
1489
1490status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1491 float brightness) const {
1492 if (!displayToken) {
1493 return BAD_VALUE;
1494 }
1495 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1496 if (!displayId) {
1497 return NAME_NOT_FOUND;
1498 }
1499 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1500}
1501
Ady Abraham8532d012019-05-08 14:50:56 -07001502status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1503 PowerHint powerHint = static_cast<PowerHint>(hintId);
1504
1505 if (powerHint == PowerHint::INTERACTION) {
1506 mScheduler->notifyTouchEvent();
1507 }
1508
1509 return NO_ERROR;
1510}
1511
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001512// ----------------------------------------------------------------------------
1513
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001514sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001515 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001516 const auto& handle =
1517 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001518
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001519 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001520}
1521
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001522// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001523
1524void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001525 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001526}
1527
1528void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001529 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001530 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001531 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001532}
1533
1534void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001535 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001536 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001537 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001538}
1539
1540void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001541 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001542 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001543}
1544
1545status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001546 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001547 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001548}
1549
1550status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001551 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001552 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001553 if (res == NO_ERROR) {
1554 msg->wait();
1555 }
1556 return res;
1557}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001558
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001559void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001560 do {
1561 waitForEvent();
1562 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001563}
1564
Dominik Laskowski83b88212018-12-11 13:34:06 -08001565nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001566 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001567 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1568 return 0;
1569 }
1570
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001571 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001572}
1573
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001574void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001575 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001576 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001577 ATRACE_NAME("SF onVsync");
1578
Steven Thomas3cfac282017-02-06 12:29:30 -08001579 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001580 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001581 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001582 return;
1583 }
1584
Dominik Laskowski075d3172018-05-24 15:50:06 -07001585 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001586 return;
1587 }
1588
Dominik Laskowski075d3172018-05-24 15:50:06 -07001589 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001590 // For now, we don't do anything with external display vsyncs.
1591 return;
1592 }
1593
Alec Mourif8e689c2019-05-20 18:32:22 -07001594 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001595 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001596 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001597 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001598 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001599}
1600
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001601void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001602 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1603 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001604}
1605
Ady Abraham2139f732019-11-13 18:56:40 -08001606bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001607 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001608}
1609
Ady Abraham2139f732019-11-13 18:56:40 -08001610void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1611 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001612 const auto display = getDefaultDisplayDeviceLocked();
1613 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001614 return;
1615 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001616 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001617
Ana Krulec7d1d6832018-12-27 11:10:09 -08001618 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001619 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001620 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001621 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001622 return;
1623 }
1624
Ady Abrahamabc27602020-04-08 17:20:29 -07001625 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001626}
1627
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001628void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001629 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001630 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001631 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001632
Lloyd Piqueba04e622017-12-14 17:11:26 -08001633 // Ignore events that do not have the right sequenceId.
1634 if (sequenceId != getBE().mComposerSequenceId) {
1635 return;
1636 }
1637
Steven Thomasb02664d2017-07-26 18:48:28 -07001638 // Only lock if we're not on the main thread. This function is normally
1639 // called on a hwbinder thread, but for the primary display it's called on
1640 // the main thread with the state lock already held, so don't attempt to
1641 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001642 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001643
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001644 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001645
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001646 if (std::this_thread::get_id() == mMainThreadId) {
1647 // Process all pending hot plug events immediately if we are on the main thread.
1648 processDisplayHotplugEventsLocked();
1649 }
1650
Lloyd Piqueba04e622017-12-14 17:11:26 -08001651 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001652}
1653
Ady Abraham7159f572019-10-11 11:10:18 -07001654void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001655 int32_t sequenceId, hwc2_display_t /*display*/,
1656 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1657 Mutex::Autolock lock(mStateLock);
1658 if (sequenceId != getBE().mComposerSequenceId) {
1659 return;
1660 }
1661 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001662}
1663
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001664void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1665 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1666 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1667}
1668
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001669void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001670 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001671 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001672 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001673 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001674 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001675}
1676
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001677void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001678 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001679
1680 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1681 // display power state.
1682 postMessageAsync(new LambdaMessage(
1683 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1684}
1685
1686void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1687 ATRACE_CALL();
1688
Ady Abraham27c70212019-06-11 10:52:26 -07001689 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1690
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001691 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001692 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1693 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001694 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001695 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001696 }
Mathias Agopian86303202012-07-24 22:46:10 -07001697}
1698
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001699// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001700void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001701 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001702 // Clear the drawing state so that the logic inside of
1703 // handleTransactionLocked will fire. It will determine the delta between
1704 // mCurrentState and mDrawingState and re-apply all changes when we make the
1705 // transition.
1706 mDrawingState.displays.clear();
1707 mDisplays.clear();
1708}
1709
Steven Thomas050b2c82017-03-06 11:45:16 -08001710void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001711 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001712 if (!mVrFlinger)
1713 return;
1714 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001715 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001716 return;
1717 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001718
Lloyd Pique441d5042018-10-18 16:49:51 -07001719 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001720 ALOGE("Vr flinger is only supported for remote hardware composer"
1721 " service connections. Ignoring request to transition to vr"
1722 " flinger.");
1723 mVrFlingerRequestsDisplay = false;
1724 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001725 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001726
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001727 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001728
Steven Thomas0123ac62018-07-12 11:32:34 -07001729 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001730 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001731
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001732 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001733
1734 // Clear out all the output layers from the composition engine for all
1735 // displays before destroying the hardware composer interface. This ensures
1736 // any HWC layers are destroyed through that interface before it becomes
1737 // invalid.
1738 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001739 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001740 }
1741
Steven Thomas0123ac62018-07-12 11:32:34 -07001742 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1743 // called below. Clear the reference now so we don't accidentally use it
1744 // later.
1745 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001746
Steven Thomasb02664d2017-07-26 18:48:28 -07001747 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001748 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001749 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001750
Steven Thomasb02664d2017-07-26 18:48:28 -07001751 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001752 // Delete the current instance before creating the new one
1753 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1754 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1755 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001756 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001757
Lloyd Pique441d5042018-10-18 16:49:51 -07001758 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001759 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001760
1761 if (vrFlingerRequestsDisplay) {
1762 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001763 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001764
1765 mVisibleRegionsDirty = true;
1766 invalidateHwcGeometry();
1767
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001768 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001769 display = getDefaultDisplayDeviceLocked();
1770 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001771 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001772
Steven Thomasb02664d2017-07-26 18:48:28 -07001773 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001774 const nsecs_t vsyncPeriod = getVsyncPeriod();
1775 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001776
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001777 // The present fences returned from vr_hwc are not an accurate
1778 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001779 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001780
Steven Thomasb02664d2017-07-26 18:48:28 -07001781 // Use phase of 0 since phase is not known.
1782 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001783 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001784 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001785
Ana Krulecc2870422019-01-29 19:00:58 -08001786 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001787
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001788 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001789 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001790}
1791
Alec Mouri6d414b52020-03-17 11:18:05 -07001792sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001793 // We are storing the last 2 present fences. If sf's phase offset is to be
1794 // woken up before the actual vsync but targeting the next vsync, we need to check
1795 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001796 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1797 : mPreviousPresentFences[1];
1798}
1799
1800bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1801 ATRACE_CALL();
1802 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001803
Ady Abraham11579302019-09-19 12:35:58 -07001804 if (fence == Fence::NO_FENCE) {
1805 return false;
1806 }
1807
1808 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1809 fence->wait(graceTimeMs);
1810 }
1811
1812 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001813}
1814
Alec Mouri6d414b52020-03-17 11:18:05 -07001815nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1816 const sp<Fence>& fence = previousFrameFence();
1817
1818 if (fence == Fence::NO_FENCE) {
1819 return Fence::SIGNAL_TIME_INVALID;
1820 }
1821
1822 return fence->getSignalTime();
1823}
1824
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001825void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001826 DisplayStatInfo stats;
1827 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001828 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001829 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001830 mExpectedPresentTime.store(
1831 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001832}
1833
Dominik Laskowski22488f62019-03-28 09:53:04 -07001834void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001835 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001836 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001837 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001838 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001839 // calculate the expected present time once and use the cached
1840 // value throughout this frame to make sure all layers are
1841 // seeing this same value.
Alec Mouri6d414b52020-03-17 11:18:05 -07001842 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001843 populateExpectedPresentTime();
1844
Ady Abraham11579302019-09-19 12:35:58 -07001845 // When Backpressure propagation is enabled we want to give a small grace period
1846 // for the present fence to fire instead of just giving up on this frame to handle cases
1847 // where present fence is just about to get signaled.
1848 const int graceTimeForPresentFenceMs =
1849 (mPropagateBackpressure &&
1850 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1851 ? 1
1852 : 0;
Alec Mouri6d414b52020-03-17 11:18:05 -07001853
1854 // Pending frames may trigger backpressure propagation.
1855 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1856 previousFramePending(
1857 graceTimeForPresentFenceMs)};
1858
1859 // Frame missed counts for metrics tracking.
1860 // A frame is missed if the prior frame is still pending. If no longer pending,
1861 // then we still count the frame as missed if the predicted present time
1862 // was further in the past than when the fence actually fired.
1863
1864 // Add some slop to correct for drift. This should generally be
1865 // smaller than a typical frame duration, but should not be so small
1866 // that it reports reasonable drift as a missed frame.
1867 DisplayStatInfo stats;
1868 mScheduler->getDisplayStatInfo(&stats);
1869 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1870 const nsecs_t previousPresentTime = previousFramePresentTime();
1871 const TracedOrdinal<bool> frameMissed =
1872 {"PrevFrameMissed",
1873 framePending ||
1874 (previousPresentTime >= 0 &&
1875 (lastExpectedPresentTime < previousPresentTime - frameMissedSlop))};
1876 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001877 mHadDeviceComposition && frameMissed};
Alec Mouri6d414b52020-03-17 11:18:05 -07001878 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001879 mHadClientComposition && frameMissed};
1880
Alec Mouricc0fc602019-02-26 21:45:19 -08001881 if (frameMissed) {
1882 mFrameMissedCount++;
1883 mTimeStats->incrementMissedFrames();
Alec Mouri5f487d42020-02-06 09:26:19 -08001884 if (mMissedFrameJankCount == 0) {
1885 mMissedFrameJankStart = systemTime();
1886 }
1887 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001888 }
1889
Alec Mouri40189b02019-03-05 15:07:54 -08001890 if (hwcFrameMissed) {
1891 mHwcFrameMissedCount++;
1892 }
1893
1894 if (gpuFrameMissed) {
1895 mGpuFrameMissedCount++;
1896 }
1897
Ady Abraham27cbed72020-04-10 12:56:59 -07001898 // If we are in the middle of a config change and the fence hasn't
1899 // fired yet just wait for the next invalidate
1900 if (mSetActiveConfigPending) {
1901 if (framePending) {
1902 mEventQueue->invalidate();
1903 break;
1904 }
1905
1906 // We received the present fence from the HWC, so we assume it successfully updated
1907 // the config, hence we update SF.
1908 mSetActiveConfigPending = false;
1909 setActiveConfigInternal();
1910 }
1911
Alec Mouri6d414b52020-03-17 11:18:05 -07001912 if (framePending && mPropagateBackpressure) {
Ady Abrahamadb9a992019-09-19 21:21:55 +00001913 if ((hwcFrameMissed && !gpuFrameMissed) ||
1914 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001915 signalLayerUpdate();
1916 break;
1917 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001918 }
Dan Stoza50182882016-07-08 12:02:20 -07001919
Alec Mouri5f487d42020-02-06 09:26:19 -08001920 // Our jank window is always at least 100ms since we missed a
1921 // frame...
1922 static constexpr nsecs_t kMinJankyDuration =
1923 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1924 // ...but if it's larger than 1s then we missed the trace cutoff.
1925 static constexpr nsecs_t kMaxJankyDuration =
1926 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1927 // If we're in a user build then don't push any atoms
1928 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1929 const auto displayDevice = getDefaultDisplayDeviceLocked();
1930 // Only report jank when the display is on, as displays in DOZE
1931 // power mode may operate at a different frame rate than is
1932 // reported in their config, which causes noticeable (but less
1933 // severe) jank.
1934 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1935 const nsecs_t currentTime = systemTime();
1936 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1937 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1938 ATRACE_NAME("Jank detected");
1939 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1940 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1941 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1942 jankyDurationMillis, mMissedFrameJankCount);
1943 }
1944
1945 // We either reported a jank event or we missed the trace
1946 // window, so clear counters here.
1947 if (jankDuration > kMinJankyDuration) {
1948 mMissedFrameJankCount = 0;
1949 mMissedFrameJankStart = 0;
1950 }
1951 }
1952 }
1953
Steven Thomas050b2c82017-03-06 11:45:16 -08001954 // Now that we're going to make it to the handleMessageTransaction()
1955 // call below it's safe to call updateVrFlinger(), which will
1956 // potentially trigger a display handoff.
1957 updateVrFlinger();
1958
Vishnu Nair60db8c02020-04-02 11:55:16 -07001959 bool refreshNeeded;
1960 withTracingLock([&]() {
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 });
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001971
Ana Krulecc84d09b2019-11-02 23:10:29 +01001972 // Layers need to get updated (in the previous line) before we can use them for
1973 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001974 // 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
Ady Abraham27cbed72020-04-10 12:56:59 -07001981 performSetActiveConfig();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001982
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001983 updateCursorAsync();
1984 updateInputFlinger();
1985
Dan Stoza58784442014-12-02 16:58:17 -08001986 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001987 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001988 // 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
Alec Mouri9519bf12019-11-15 16:54:44 -08001991 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 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001998 signalRefresh();
1999 }
2000 break;
2001 }
2002 case MessageQueue::REFRESH: {
2003 handleMessageRefresh();
2004 break;
2005 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002006 }
2007}
2008
Dan Stoza6b9454d2014-11-07 16:00:59 -08002009bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08002010 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002011 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002012
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002013 bool flushedATransaction = flushTransactionQueues();
2014
2015 bool runHandleTransaction = transactionFlags &&
2016 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
2017
2018 if (runHandleTransaction) {
2019 handleTransaction(eTransactionMask);
2020 } else {
2021 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002022 }
2023
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002024 if (transactionFlushNeeded()) {
2025 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002026 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002027
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002028 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002029}
2030
Mathias Agopian4fec8732012-06-29 14:12:52 -07002031void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002032 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002033
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002034 mRefreshPending = false;
2035
Lloyd Piqueab039b52019-02-13 14:22:42 -08002036 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002037 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002038 for (const auto& [_, display] : mDisplays) {
2039 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2040 }
2041 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002042 if (auto layerFE = layer->getCompositionEngineLayerFE())
2043 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002044 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002045 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2046 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002047 if (auto layerFE = layer->getCompositionEngineLayerFE())
2048 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002049 }
2050
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002051 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002052 refreshArgs.outputColorSetting = useColorManagement
2053 ? mDisplayColorSetting
2054 : compositionengine::OutputColorSetting::kUnmanaged;
2055 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2056 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002057
2058 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2059 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002060 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002061
2062 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2063 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2064 mDrawingState.colorMatrixChanged = false;
2065 }
2066
2067 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2068
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002069 if (mDebugRegion != 0) {
2070 refreshArgs.devOptFlashDirtyRegionsDelay =
2071 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2072 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002073
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002074 mGeometryInvalid = false;
2075
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002076 // Store the present time just before calling to the composition engine so we could notify
2077 // the scheduler.
2078 const auto presentTime = systemTime();
2079
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002080 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002081 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2082 // Reset the frame start time now that we've recorded this frame.
2083 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002084
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002085 mScheduler->onDisplayRefreshed(presentTime);
2086
David Sodmanfa9b2af2017-12-24 13:28:59 -08002087 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002088 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002089
Lloyd Pique66d68602019-02-13 14:23:31 -08002090 mHadClientComposition =
2091 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2092 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002093 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2094 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002095 });
2096 mHadDeviceComposition =
2097 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2098 auto& displayDevice = tokenDisplayPair.second;
2099 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2100 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002101 mReusedClientComposition =
2102 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2103 auto& displayDevice = tokenDisplayPair.second;
2104 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2105 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002106
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 -08002122
2123bool SurfaceFlinger::handleMessageInvalidate() {
2124 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002125 bool refreshNeeded = handlePageFlip();
2126
Vishnu Nair4351ad52019-02-11 14:13:02 -08002127 if (mVisibleRegionsDirty) {
2128 computeLayerBounds();
2129 }
2130
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002131 for (auto& layer : mLayersPendingRefresh) {
2132 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002133 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002134 invalidateLayerStack(layer, visibleReg);
2135 }
2136 mLayersPendingRefresh.clear();
2137 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002138}
2139
Ana Krulece588e312018-09-18 12:32:24 -07002140void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2141 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002142 // Update queue of past composite+present times and determine the
2143 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002144 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002145 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002146 while (!getBE().mCompositePresentTimes.empty()) {
2147 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002148 // Cached values should have been updated before calling this method,
2149 // which helps avoid duplicate syscalls.
2150 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2151 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2152 break;
2153 }
2154 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002155 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002156 }
2157
2158 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002159 while (getBE().mCompositePresentTimes.size() > 16) {
2160 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002161 }
2162
Ana Krulece588e312018-09-18 12:32:24 -07002163 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002164}
2165
Ana Krulece588e312018-09-18 12:32:24 -07002166void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2167 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002168 // Integer division and modulo round toward 0 not -inf, so we need to
2169 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002170 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2171 ? (stats.vsyncPeriod -
2172 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2173 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002174
Ady Abraham9e16a482019-12-03 17:19:41 -08002175 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002176 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002177 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002178 }
2179
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002180 // Snap the latency to a value that removes scheduling jitter from the
2181 // composition and present times, which often have >1ms of jitter.
2182 // Reducing jitter is important if an app attempts to extrapolate
2183 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002184 // Snapping also allows an app to precisely calculate
2185 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002186 nsecs_t bias = stats.vsyncPeriod / 2;
2187 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2188 nsecs_t snappedCompositeToPresentLatency =
2189 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002190
David Sodman99974d22017-11-28 12:04:33 -08002191 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002192 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2193 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002194 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002195}
2196
David Sodman2b406362017-12-15 13:33:47 -08002197void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002198{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002199 ATRACE_CALL();
2200 ALOGV("postComposition");
2201
Brian Andersonf6386862016-10-31 16:34:13 -07002202 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002203 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002204 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002205 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002206 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002207 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002208
David Sodman73beded2017-11-15 11:56:06 -08002209 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002210 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002211 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002212 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002213 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2214 ->getRenderSurface()
2215 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002216 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002217 } else {
2218 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2219 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002220
David Sodman73beded2017-11-15 11:56:06 -08002221 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002222 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2223 mPreviousPresentFences[0] = displayDevice
2224 ? getHwComposer().getPresentFence(*displayDevice->getId())
2225 : Fence::NO_FENCE;
2226 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002227 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002228
Ana Krulece588e312018-09-18 12:32:24 -07002229 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002230 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002231
Lloyd Piqueab039b52019-02-13 14:22:42 -08002232 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2233 // be sampled a little later than when we started doing work for this frame,
2234 // but that should be okay since updateCompositorTiming has snapping logic.
2235 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2236 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002237 CompositorTiming compositorTiming;
2238 {
David Sodman99974d22017-11-28 12:04:33 -08002239 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2240 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002241 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002242
Edgar Arriaga844fa672020-01-16 14:21:42 -08002243 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002244 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2245 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002246 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002247 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002248 }
Robert Carr2047fae2016-11-28 14:09:09 -08002249 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002250
Ady Abraham92fa2f42020-02-11 15:33:56 -08002251 if (displayDevice && displayDevice->isPrimary() &&
2252 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002253 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002254 }
2255
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002256 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002257 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2258 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002259 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002260 }
2261 }
2262
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002263 if (mAnimCompositionPending) {
2264 mAnimCompositionPending = false;
2265
Brian Anderson4e606e32017-03-16 15:34:57 -07002266 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002267 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002268 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002269 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002270 // The HWC doesn't support present fences, so use the refresh
2271 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002272 const nsecs_t presentTime =
2273 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002274 mAnimFrameTracker.setActualPresentTime(presentTime);
2275 }
2276 mAnimFrameTracker.advanceFrame();
2277 }
Dan Stozab90cf072015-03-05 11:05:59 -08002278
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002279 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002280 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002281 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002282 }
2283
Vishnu Nair9b079a22020-01-21 14:36:08 -08002284 if (mReusedClientComposition) {
2285 mTimeStats->incrementClientCompositionReusedFrames();
2286 }
2287
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002288 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002289
Alec Mouri717bcb62020-02-10 17:07:19 -08002290 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2291 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2292 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2293
Lloyd Pique32cbe282018-10-19 13:09:22 -07002294 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2295 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002296 return;
2297 }
2298
2299 nsecs_t currentTime = systemTime();
2300 if (mHasPoweredOff) {
2301 mHasPoweredOff = false;
2302 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002303 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002304 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002305 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2306 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002307 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002308 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002309 }
David Sodman4a36e932017-11-07 14:29:47 -08002310 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002311 }
David Sodman4a36e932017-11-07 14:29:47 -08002312 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002313
Alec Mourid9c71752019-09-30 17:27:13 -07002314 // Cleanup any outstanding resources due to rendering a prior frame.
2315 getRenderEngine().cleanupPostRender();
2316
Dan Stoza436ccf32018-06-21 12:10:12 -07002317 {
2318 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002319 if (mTexturePool.size() < mTexturePoolSize) {
2320 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002321 const size_t offset = mTexturePool.size();
2322 mTexturePool.resize(mTexturePoolSize);
2323 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2324 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002325 } else if (mTexturePool.size() > mTexturePoolSize) {
2326 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2327 const size_t offset = mTexturePoolSize;
2328 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2329 mTexturePool.resize(mTexturePoolSize);
2330 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002331 }
2332 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002333
Ady Abrahambe0f9482019-04-24 15:41:53 -07002334 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002335 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002336
Kevin DuBois413287f2019-02-25 08:46:47 -08002337 if (mLumaSampling && mRegionSamplingThread) {
2338 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002339 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002340
2341 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2342 // side-effect of getTotalSize(), so we check that again here
2343 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002344 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002345 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2346 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002347}
2348
Vishnu Nair4351ad52019-02-11 14:13:02 -08002349void SurfaceFlinger::computeLayerBounds() {
2350 for (const auto& pair : mDisplays) {
2351 const auto& displayDevice = pair.second;
2352 const auto display = displayDevice->getCompositionDisplay();
2353 for (const auto& layer : mDrawingState.layersSortedByZ) {
2354 // only consider the layers on the given layer stack
2355 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002356 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002357 }
2358
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002359 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2360 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002361 }
2362 }
2363}
2364
David Sodmanfa9b2af2017-12-24 13:28:59 -08002365void SurfaceFlinger::postFrame()
2366{
2367 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002368 const auto display = getDefaultDisplayDeviceLocked();
2369 if (display && getHwComposer().isConnected(*display->getId())) {
2370 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002371 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2372 logFrameStats();
2373 }
2374 }
2375}
2376
Mathias Agopian87baae12012-07-31 12:38:26 -07002377void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002378{
Mathias Agopian841cde52012-03-01 15:44:37 -08002379 ATRACE_CALL();
2380
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002381 // here we keep a copy of the drawing state (that is the state that's
2382 // going to be overwritten by handleTransactionLocked()) outside of
2383 // mStateLock so that the side-effects of the State assignment
2384 // don't happen with mStateLock held (which can cause deadlocks).
2385 State drawingState(mDrawingState);
2386
Mathias Agopianca4d3602011-05-19 15:38:14 -07002387 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002388 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002389
Mathias Agopianca4d3602011-05-19 15:38:14 -07002390 // Here we're guaranteed that some transaction flags are set
2391 // so we can call handleTransactionLocked() unconditionally.
2392 // We call getTransactionFlags(), which will also clear the flags,
2393 // with mStateLock held to guarantee that mCurrentState won't change
2394 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002395
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002396 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002397 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002398 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002399
Mathias Agopianca4d3602011-05-19 15:38:14 -07002400 mDebugInTransaction = 0;
2401 invalidateHwcGeometry();
2402 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002403}
2404
Lloyd Piqueba04e622017-12-14 17:11:26 -08002405void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2406 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002407 const std::optional<DisplayIdentificationInfo> info =
2408 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002409
Dominik Laskowski075d3172018-05-24 15:50:06 -07002410 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002411 continue;
2412 }
2413
Dominik Laskowski55c85402020-01-21 16:25:47 -08002414 const DisplayId displayId = info->id;
2415 const auto it = mPhysicalDisplayTokens.find(displayId);
2416
Lloyd Piqueba04e622017-12-14 17:11:26 -08002417 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002418 if (it == mPhysicalDisplayTokens.end()) {
2419 ALOGV("Creating display %s", to_string(displayId).c_str());
2420
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002421 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002422 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002423 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002424
Dominik Laskowski075d3172018-05-24 15:50:06 -07002425 DisplayDeviceState state;
Marin Shalamanov700e6392020-02-12 20:22:26 +01002426 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2427 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 state.isSecure = true; // All physical displays are currently considered secure.
2429 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002430
2431 sp<IBinder> token = new BBinder();
2432 mCurrentState.displays.add(token, state);
2433 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2434
Dominik Laskowski075d3172018-05-24 15:50:06 -07002435 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002436 } else {
2437 ALOGV("Recreating display %s", to_string(displayId).c_str());
2438
2439 const auto token = it->second;
2440 auto& state = mCurrentState.displays.editValueFor(token);
2441 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002442 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002443 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002444 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002445
Dominik Laskowski55c85402020-01-21 16:25:47 -08002446 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002447 if (index >= 0) {
2448 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2449 mInterceptor->saveDisplayDeletion(state.sequenceId);
2450 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002451 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002452 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002453 }
2454
2455 processDisplayChangesLocked();
2456 }
2457
2458 mPendingHotplugEvents.clear();
2459}
2460
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002461void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002462 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2463 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002464}
2465
Lloyd Pique99d3da52018-01-22 17:48:03 -08002466sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002467 const wp<IBinder>& displayToken,
2468 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002469 const DisplayDeviceState& state,
2470 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002471 const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique9370a482019-10-03 17:58:30 -07002472 auto displayId = compositionDisplay->getDisplayId();
2473 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002474 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002475 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002476 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002477 creationArgs.hasWideColorGamut = false;
2478 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002479
Dominik Laskowski55c85402020-01-21 16:25:47 -08002480 if (const auto& physical = state.physical) {
2481 creationArgs.connectionType = physical->type;
2482 }
2483
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002484 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002485 creationArgs.isPrimary = isInternalDisplay;
2486
2487 if (useColorManagement && displayId) {
2488 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002489 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002490 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002491 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002492 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002493
Dominik Laskowski7e045462018-05-30 13:02:02 -07002494 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002495 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002496 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002497 }
tangrobin6753a022018-08-10 10:58:54 +08002498 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002499
Dominik Laskowski075d3172018-05-24 15:50:06 -07002500 if (displayId) {
2501 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002502 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002503 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002504 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002505
Lloyd Pique90c115d2018-09-18 21:39:42 -07002506 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002507 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002508 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002509
Lloyd Pique99d3da52018-01-22 17:48:03 -08002510 // Make sure that composition can never be stalled by a virtual display
2511 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002512 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002513 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002514 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2515 }
2516
Dominik Laskowski718f9602019-11-09 20:01:35 -08002517 creationArgs.physicalOrientation =
2518 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002519
Lloyd Pique99d3da52018-01-22 17:48:03 -08002520 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002521 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522
Lloyd Pique9370a482019-10-03 17:58:30 -07002523 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002524
2525 if (maxFrameBufferAcquiredBuffers >= 3) {
2526 nativeWindowSurface->preallocateBuffers();
2527 }
2528
2529 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002530 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002531 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002532 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002533 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002534 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002535 display->getCompositionDisplay()->setColorProfile(
2536 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2537 RenderIntent::COLORIMETRIC,
2538 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002539 if (!state.isVirtual()) {
2540 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002541 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2542 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002543 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002544
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002545 display->setLayerStack(state.layerStack);
2546 display->setProjection(state.orientation, state.viewport, state.frame);
2547 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002548
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002549 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002550}
2551
Marin Shalamanovae685592020-02-12 17:12:22 +01002552void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2553 const DisplayDeviceState& state) {
2554 int width = 0;
2555 int height = 0;
2556 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2557 if (state.physical) {
2558 const auto& activeConfig =
2559 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2560 width = activeConfig->getWidth();
2561 height = activeConfig->getHeight();
2562 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2563 } else if (state.surface != nullptr) {
2564 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2565 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2566 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2567 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2568 int intPixelFormat;
2569 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2570 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2571 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2572 } else {
2573 // Virtual displays without a surface are dormant:
2574 // they have external state (layer stack, projection,
2575 // etc.) but no internal state (i.e. a DisplayDevice).
2576 return;
2577 }
2578
2579 compositionengine::DisplayCreationArgsBuilder builder;
2580 if (const auto& physical = state.physical) {
2581 builder.setPhysical({physical->id, physical->type});
2582 }
2583 builder.setPixels(ui::Size(width, height));
2584 builder.setPixelFormat(pixelFormat);
2585 builder.setIsSecure(state.isSecure);
2586 builder.setLayerStackId(state.layerStack);
2587 builder.setPowerAdvisor(&mPowerAdvisor);
2588 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2589 builder.setName(state.displayName);
2590 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2591
2592 sp<compositionengine::DisplaySurface> displaySurface;
2593 sp<IGraphicBufferProducer> producer;
2594 sp<IGraphicBufferProducer> bqProducer;
2595 sp<IGraphicBufferConsumer> bqConsumer;
2596 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2597
2598 std::optional<DisplayId> displayId = compositionDisplay->getId();
2599
2600 if (state.isVirtual()) {
2601 sp<VirtualDisplaySurface> vds =
2602 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2603 bqConsumer, state.displayName);
2604
2605 displaySurface = vds;
2606 producer = vds;
2607 } else {
2608 ALOGE_IF(state.surface != nullptr,
2609 "adding a supported display, but rendering "
2610 "surface is provided (%p), ignoring it",
2611 state.surface.get());
2612
2613 LOG_ALWAYS_FATAL_IF(!displayId);
2614 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2615 maxGraphicsWidth, maxGraphicsHeight);
2616 producer = bqProducer;
2617 }
2618
Marin Shalamanov700e6392020-02-12 20:22:26 +01002619 LOG_FATAL_IF(!displaySurface);
2620 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2621 displaySurface, producer);
2622 mDisplays.emplace(displayToken, display);
2623 if (!state.isVirtual()) {
2624 LOG_FATAL_IF(!displayId);
2625 dispatchDisplayHotplugEvent(displayId->value, true);
2626 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002627
Marin Shalamanov700e6392020-02-12 20:22:26 +01002628 if (display->isPrimary()) {
2629 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanovae685592020-02-12 17:12:22 +01002630 }
2631}
2632
2633void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2634 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2635 // Save display ID before disconnecting.
2636 const auto displayId = display->getId();
2637 display->disconnect();
2638
2639 if (!display->isVirtual()) {
Marin Shalamanov700e6392020-02-12 20:22:26 +01002640 LOG_FATAL_IF(!displayId);
Marin Shalamanovae685592020-02-12 17:12:22 +01002641 dispatchDisplayHotplugEvent(displayId->value, false);
2642 }
2643 }
2644
2645 mDisplays.erase(displayToken);
2646}
2647
2648void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2649 const DisplayDeviceState& currentState,
2650 const DisplayDeviceState& drawingState) {
2651 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2652 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002653 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002654 // changing the surface is like destroying and recreating the DisplayDevice
2655 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2656 display->disconnect();
2657 }
2658 mDisplays.erase(displayToken);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002659 if (const auto& physical = currentState.physical) {
2660 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2661 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002662 processDisplayAdded(displayToken, currentState);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002663 if (currentState.physical) {
2664 initializeDisplays();
2665 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002666 return;
2667 }
2668
2669 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2670 if (currentState.layerStack != drawingState.layerStack) {
2671 display->setLayerStack(currentState.layerStack);
2672 }
2673 if ((currentState.orientation != drawingState.orientation) ||
2674 (currentState.viewport != drawingState.viewport) ||
2675 (currentState.frame != drawingState.frame)) {
2676 display->setProjection(currentState.orientation, currentState.viewport,
2677 currentState.frame);
2678 }
2679 if (currentState.width != drawingState.width ||
2680 currentState.height != drawingState.height) {
2681 display->setDisplaySize(currentState.width, currentState.height);
2682 if (display->isPrimary()) {
2683 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2684 }
2685 }
2686 }
2687}
2688
Lloyd Pique347200f2017-12-14 17:00:15 -08002689void SurfaceFlinger::processDisplayChangesLocked() {
2690 // here we take advantage of Vector's copy-on-write semantics to
2691 // improve performance by skipping the transaction entirely when
2692 // know that the lists are identical
2693 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2694 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2695 if (!curr.isIdenticalTo(draw)) {
2696 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002697
2698 // find the displays that were removed
2699 // (ie: in drawing state but not in current state)
2700 // also handle displays that changed
2701 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01002702 for (size_t i = 0; i < draw.size(); i++) {
2703 const wp<IBinder>& displayToken = draw.keyAt(i);
2704 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002705 if (j < 0) {
2706 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01002707 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 } else {
2709 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01002710 const DisplayDeviceState& currentState = curr[j];
2711 const DisplayDeviceState& drawingState = draw[i];
2712 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002713 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002714 }
2715
2716 // find displays that were added
2717 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01002718 for (size_t i = 0; i < curr.size(); i++) {
2719 const wp<IBinder>& displayToken = curr.keyAt(i);
2720 if (draw.indexOfKey(displayToken) < 0) {
2721 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 }
2723 }
2724 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002725
2726 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002727}
2728
Mathias Agopian87baae12012-07-31 12:38:26 -07002729void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002730{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002731 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2732
Dan Stoza7dde5992015-05-22 09:51:44 -07002733 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002734 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002735 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002736 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002737
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 /*
2739 * Traversal of the children
2740 * (perform the transaction for each of them if needed)
2741 */
2742
Marissa Wall06255332019-03-27 13:48:27 -07002743 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002744 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002746 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747
2748 const uint32_t flags = layer->doTransaction(0);
2749 if (flags & Layer::eVisibleRegion)
2750 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002751
2752 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002753 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002754 }
Robert Carr2047fae2016-11-28 14:09:09 -08002755 });
Marissa Wall06255332019-03-27 13:48:27 -07002756 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757 }
2758
2759 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002760 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 */
2762
Mathias Agopiane57f2922012-08-09 16:29:12 -07002763 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002764 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002765 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002766 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002768 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002769 // The transform hint might have changed for some layers
2770 // (either because a display has changed, or because a layer
2771 // as changed).
2772 //
2773 // Walk through all the layers in currentLayers,
2774 // and update their transform hint.
2775 //
2776 // If a layer is visible only on a single display, then that
2777 // display is used to calculate the hint, otherwise we use the
2778 // default display.
2779 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002780 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002781 // the hint is set before we acquire a buffer from the surface texture.
2782 //
2783 // NOTE: layer transactions have taken place already, so we use their
2784 // drawing state. However, SurfaceFlinger's own transaction has not
2785 // happened yet, so we must use the current state layer list
2786 // (soon to become the drawing state list).
2787 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002788 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002789 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002790 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002791 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002792 // NOTE: we rely on the fact that layers are sorted by
2793 // layerStack first (so we don't have to traverse the list
2794 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002795 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002796 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002797 currentlayerStack = layerStack;
2798 // figure out if this layerstack is mirrored
2799 // (more than one display) if so, pick the default display,
2800 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002801 hintDisplay = nullptr;
2802 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002803 if (display->getCompositionDisplay()
2804 ->belongsInOutput(layer->getLayerStack(),
2805 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002806 if (hintDisplay) {
2807 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002808 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002809 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002810 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002811 }
2812 }
2813 }
2814 }
Chet Haase91d25932013-04-11 15:24:55 -07002815
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002816 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002817 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2818 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002819
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002820 // could be null when this layer is using a layerStack
2821 // that is not visible on any display. Also can occur at
2822 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002823 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002824 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002825
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002826 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002827 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002828 if (hintDisplay) {
2829 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002830 }
Robert Carr2047fae2016-11-28 14:09:09 -08002831
2832 first = false;
2833 });
Mathias Agopian84300952012-11-21 16:02:13 -08002834 }
2835
2836
Mathias Agopian3559b072012-08-15 13:46:03 -07002837 /*
2838 * Perform our own transaction if needed
2839 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002840
2841 if (mLayersAdded) {
2842 mLayersAdded = false;
2843 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002844 mVisibleRegionsDirty = true;
2845 }
2846
2847 // some layers might have been removed, so
2848 // we need to update the regions they're exposing.
2849 if (mLayersRemoved) {
2850 mLayersRemoved = false;
2851 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002852 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002853 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002854 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002855 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002856 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002857 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002858 }
Robert Carr2047fae2016-11-28 14:09:09 -08002859 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860 }
2861
Vishnu Nairec0ab382019-02-13 15:32:56 -08002862 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002864}
2865
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002866void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002867 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002868 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002869 return;
2870 }
2871
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002872 if (mVisibleRegionsDirty || mInputInfoChanged) {
2873 mInputInfoChanged = false;
2874 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002875 } else if (mInputWindowCommands.syncInputWindows) {
2876 // If the caller requested to sync input windows, but there are no
2877 // changes to input windows, notify immediately.
2878 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002879 }
2880
Arthur Hung6cbb9752019-09-05 16:38:18 +08002881 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002882}
2883
2884void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002885 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002886
Robert Carra1257842020-01-31 13:48:28 -08002887 // We use a simple caching algorithm here. mInputDirty begins as true,
2888 // after we call setInputWindows we set it to false, so
2889 // in the future we wont call it again.. We set input dirty to true again
2890 // when any layer that hasInput() has a transaction performed on it
2891 // or when any parent or relative parent of such a layer has a transaction
2892 // performed on it. Not all of these transactions will really result in
2893 // input changes but all input changes will spring from these transactions
2894 // so the cache is safe but not optimal. It seems like it might be annoyingly
2895 // costly to cache and comapre the actual InputWindowHandle vector though.
Robert Carr0854b992020-03-11 12:09:42 -07002896 if (!mInputDirty && !mInputWindowCommands.syncInputWindows) {
Robert Carra1257842020-01-31 13:48:28 -08002897 return;
2898 }
2899
Robert Carr720e5062018-07-30 17:45:14 -07002900 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2901 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002902 // When calculating the screen bounds we ignore the transparent region since it may
2903 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002904 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002905 }
2906 });
chaviw291d88a2019-02-14 10:33:58 -08002907
2908 mInputFlinger->setInputWindows(inputHandles,
2909 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2910 : nullptr);
Robert Carra1257842020-01-31 13:48:28 -08002911
2912 mInputDirty = false;
Robert Carr720e5062018-07-30 17:45:14 -07002913}
2914
Vishnu Nairec0ab382019-02-13 15:32:56 -08002915void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002916 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002917 mPendingInputWindowCommands.clear();
2918}
2919
Riley Andrews03414a12014-07-01 14:22:59 -07002920void SurfaceFlinger::updateCursorAsync()
2921{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002922 compositionengine::CompositionRefreshArgs refreshArgs;
2923 for (const auto& [_, display] : mDisplays) {
2924 if (display->getId()) {
2925 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002926 }
2927 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002928
2929 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002930}
2931
Ady Abraham2139f732019-11-13 18:56:40 -08002932void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002933 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2934 // If this is called from the main thread mStateLock must be locked before
2935 // Currently the only way to call this function from the main thread is from
2936 // Sheduler::chooseRefreshRateForContent
2937
2938 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002939 changeRefreshRateLocked(refreshRate, event);
2940}
2941
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002942void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2943 if (mScheduler) {
2944 // In practice it's not allowed to hotplug in/out the primary display once it's been
2945 // connected during startup, but some tests do it, so just warn and return.
2946 ALOGW("Can't re-init scheduler");
2947 return;
2948 }
2949
Ady Abraham2139f732019-11-13 18:56:40 -08002950 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002951 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002952 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002953 primaryDisplayId),
2954 currentConfig);
2955 mRefreshRateStats =
2956 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2957 currentConfig, HWC_POWER_MODE_OFF);
2958 mRefreshRateStats->setConfigMode(currentConfig);
2959
Ady Abraham9e16a482019-12-03 17:19:41 -08002960 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2961
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002962 // start the EventThread
2963 mScheduler =
2964 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002965 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002966 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002967 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002968 impl::EventThread::InterceptVSyncsCallback());
2969 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002970 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002971 [this](nsecs_t timestamp) {
2972 mInterceptor->saveVSyncEvent(timestamp);
2973 });
2974
2975 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2976 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002977 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002978
2979 mRegionSamplingThread =
2980 new RegionSamplingThread(*this, *mScheduler,
2981 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002982 // Dispatch a config change request for the primary display on scheduler
2983 // initialization, so that the EventThreads always contain a reference to a
2984 // prior configuration.
2985 //
2986 // This is a bit hacky, but this avoids a back-pointer into the main SF
2987 // classes from EventThread, and there should be no run-time binder cost
2988 // anyway since there are no connected apps at this point.
2989 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002990 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Alec Mouri60aee1c2019-10-28 16:18:59 -07002991 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2992 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002993}
2994
Mathias Agopian4fec8732012-06-29 14:12:52 -07002995void SurfaceFlinger::commitTransaction()
2996{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002997 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002998 mTransactionPending = false;
2999 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003001}
3002
Lloyd Pique58e24a32019-08-01 15:50:14 -07003003void SurfaceFlinger::commitTransactionLocked() {
3004 if (!mLayersPendingRemoval.isEmpty()) {
3005 // Notify removed layers now that they can't be drawn from
3006 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003007 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003008
3009 // Ensure any buffers set to display on any children are released.
3010 if (l->isRemovedFromCurrentState()) {
3011 l->latchAndReleaseBuffer();
3012 }
3013
3014 // If the layer has been removed and has no parent, then it will not be reachable
3015 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3016 // ensure we can copy its current to drawing state.
3017 if (!l->getParent()) {
3018 mOffscreenLayers.emplace(l.get());
3019 }
3020 }
3021 mLayersPendingRemoval.clear();
3022 }
3023
3024 // If this transaction is part of a window animation then the next frame
3025 // we composite should be considered an animation as well.
3026 mAnimCompositionPending = mAnimTransactionPending;
3027
3028 mDrawingState = mCurrentState;
3029 // clear the "changed" flags in current state
3030 mCurrentState.colorMatrixChanged = false;
3031
Edgar Arriaga844fa672020-01-16 14:21:42 -08003032 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003033 layer->commitChildList();
3034
3035 // If the layer can be reached when traversing mDrawingState, then the layer is no
3036 // longer offscreen. Remove the layer from the offscreenLayer set.
3037 if (mOffscreenLayers.count(layer)) {
3038 mOffscreenLayers.erase(layer);
3039 }
3040 });
3041
3042 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003043 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003044}
3045
Nataniel Borges2b796da2019-02-15 13:32:18 -08003046void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3047 if (mTracingEnabledChanged) {
3048 mTracingEnabled = mTracing.isEnabled();
3049 mTracingEnabledChanged = false;
3050 }
3051
3052 // Synchronize with Tracing thread
3053 std::unique_lock<std::mutex> lock;
3054 if (mTracingEnabled) {
3055 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3056 }
3057
3058 lockedOperation();
3059
3060 // Synchronize with Tracing thread
3061 if (mTracingEnabled) {
3062 lock.unlock();
3063 }
3064}
3065
chaviw74d90ad2019-04-26 14:45:26 -07003066void SurfaceFlinger::commitOffscreenLayers() {
3067 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003068 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003069 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3070 if (!trFlags) return;
3071
3072 layer->doTransaction(0);
3073 layer->commitChildList();
3074 });
3075 }
3076}
3077
Chia-I Wuab0c3192017-08-01 11:29:00 -07003078void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003079 for (const auto& [token, displayDevice] : mDisplays) {
3080 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003081 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003082 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003083 }
3084 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003085}
3086
Dan Stoza6b9454d2014-11-07 16:00:59 -08003087bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088{
Ady Abraham09bd3922019-04-08 10:44:56 -07003089 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003090 ALOGV("handlePageFlip");
3091
Brian Andersond6927fb2016-07-23 23:37:30 -07003092 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093
Mathias Agopian4fec8732012-06-29 14:12:52 -07003094 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003095 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003096 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003097
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003098 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3099
Eric Penner51c59cd2014-07-28 19:51:58 -07003100 // Store the set of layers that need updates. This set must not change as
3101 // buffers are being latched, as this could result in a deadlock.
3102 // Example: Two producers share the same command stream and:
3103 // 1.) Layer 0 is latched
3104 // 2.) Layer 0 gets a new frame
3105 // 2.) Layer 1 gets a new frame
3106 // 3.) Layer 1 is latched.
3107 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3108 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003109 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003110 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003111 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003112 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003113 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003114 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003115 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003116 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003117 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003118 } else {
3119 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003120 }
Robert Carr2047fae2016-11-28 14:09:09 -08003121 });
3122
chaviw49a108c2019-08-12 11:23:06 -07003123 // The client can continue submitting buffers for offscreen layers, but they will not
3124 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3125 // layers to ensure dequeueBuffer doesn't block indefinitely.
3126 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003127 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003128 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3129 }
3130
Lloyd Piquef2c79392018-12-20 16:23:33 -08003131 if (!mLayersWithQueuedFrames.empty()) {
3132 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3133 // writes to Layer current state. See also b/119481871
3134 Mutex::Autolock lock(mStateLock);
3135
3136 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003137 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003138 mLayersPendingRefresh.push_back(layer);
3139 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003140 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003141 if (layer->isBufferLatched()) {
3142 newDataLatched = true;
3143 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003144 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003145 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003146
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003147 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003148
3149 // If we will need to wake up at some time in the future to deal with a
3150 // queued frame that shouldn't be displayed during this vsync period, wake
3151 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003152 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003153 signalLayerUpdate();
3154 }
3155
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003156 // enter boot animation on first buffer latch
3157 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3158 ALOGI("Enter boot animation");
3159 mBootStage = BootStage::BOOTANIMATION;
3160 }
3161
Edgar Arriaga844fa672020-01-16 14:21:42 -08003162 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003163
Dan Stoza6b9454d2014-11-07 16:00:59 -08003164 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003165 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166}
3167
Mathias Agopianad456f92011-01-13 17:53:01 -08003168void SurfaceFlinger::invalidateHwcGeometry()
3169{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003170 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003171}
3172
Robert Carrc0df3122019-04-11 13:18:21 -07003173status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3174 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3175 const sp<IBinder>& parentHandle,
3176 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003177 // add this layer to the current state list
3178 {
3179 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003180 sp<Layer> parent;
3181 if (parentHandle != nullptr) {
3182 parent = fromHandle(parentHandle);
3183 if (parent == nullptr) {
3184 return NAME_NOT_FOUND;
3185 }
3186 } else {
3187 parent = parentLayer;
3188 }
3189
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003190 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003191 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003192 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003193 return NO_MEMORY;
3194 }
Robert Carrc0df3122019-04-11 13:18:21 -07003195
3196 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3197
Robert Carrb89ea9d2018-12-10 13:01:14 -08003198 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003199 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003200 } else if (parent == nullptr) {
3201 lbc->onRemovedFromCurrentState();
3202 } else if (parent->isRemovedFromCurrentState()) {
3203 parent->addChild(lbc);
3204 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003205 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003206 parent->addChild(lbc);
3207 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003208
Yiwei Zhang243b3782018-05-15 17:40:04 -07003209 if (gbc != nullptr) {
3210 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3211 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3212 mMaxGraphicBufferProducerListSize,
3213 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3214 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003215 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003216 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3217 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3218 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3219 mNumLayers.load());
3220 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003221 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003222 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003223 }
3224
Mathias Agopian96f08192010-06-02 23:28:45 -07003225 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003226 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003227
Dan Stoza7d89d062015-04-30 13:29:25 -07003228 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003229}
3230
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003231uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003232 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003233}
3234
Mathias Agopian3f844832013-08-07 21:24:32 -07003235uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003236 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237}
3238
Mathias Agopian3f844832013-08-07 21:24:32 -07003239uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003240 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003241}
3242
3243uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003244 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003245 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003246 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003248 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003249 }
3250 return old;
3251}
3252
Marissa Wall713b63f2018-10-17 15:42:43 -07003253bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003254 // to prevent onHandleDestroyed from being called while the lock is held,
3255 // we must keep a copy of the transactions (specifically the composer
3256 // states) around outside the scope of the lock
3257 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003258 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003259 {
3260 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003261
Valerie Haufce31b82019-04-30 16:41:14 -07003262 auto it = mTransactionQueues.begin();
3263 while (it != mTransactionQueues.end()) {
3264 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003265
Valerie Haufce31b82019-04-30 16:41:14 -07003266 while (!transactionQueue.empty()) {
3267 const auto& transaction = transactionQueue.front();
3268 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003269 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003270 transaction.states)) {
3271 setTransactionFlags(eTransactionFlushNeeded);
3272 break;
3273 }
3274 transactions.push_back(transaction);
3275 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3276 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003277 transaction.buffer, transaction.postTime,
3278 transaction.privileged, transaction.hasListenerCallbacks,
3279 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003280 transactionQueue.pop();
3281 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003282 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003283
Valerie Haufce31b82019-04-30 16:41:14 -07003284 if (transactionQueue.empty()) {
3285 it = mTransactionQueues.erase(it);
3286 mTransactionCV.broadcast();
3287 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003288 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003289 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003290 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003291 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003292 return flushedATransaction;
3293}
3294
3295bool SurfaceFlinger::transactionFlushNeeded() {
3296 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003297}
3298
chaviwca27f252018-02-06 16:46:39 -08003299
Marissa Wall17b4e452018-12-26 16:32:34 -08003300bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003301 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003302 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003303 if (!useCachedExpectedPresentTime)
3304 populateExpectedPresentTime();
3305
3306 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003307 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3308 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3309 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3310 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3311 return false;
3312 }
3313
Marissa Wall713b63f2018-10-17 15:42:43 -07003314 for (const ComposerState& state : states) {
3315 const layer_state_t& s = state.state;
3316 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3317 continue;
3318 }
3319 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003320 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003321 }
3322 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003323 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003324}
3325
Valerie Hau9dab9732019-08-20 09:29:25 -07003326void SurfaceFlinger::setTransactionState(
3327 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3328 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3329 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3330 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003331 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003332
Valerie Haubc6ddb12019-03-08 11:10:15 -08003333 const int64_t postTime = systemTime();
3334
Robert Carr14167e02019-02-13 13:50:55 -08003335 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3336
Mathias Agopian698c0872011-06-28 19:09:31 -07003337 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003338
Marissa Wall713b63f2018-10-17 15:42:43 -07003339 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003340 auto itr = mTransactionQueues.find(applyToken);
3341 // if this is an animation frame, wait until prior animation frame has
3342 // been applied by SF
3343 if (flags & eAnimation) {
3344 while (itr != mTransactionQueues.end()) {
3345 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3346 if (CC_UNLIKELY(err != NO_ERROR)) {
3347 ALOGW_IF(err == TIMED_OUT,
3348 "setTransactionState timed out "
3349 "waiting for animation frame to apply");
3350 break;
3351 }
3352 itr = mTransactionQueues.find(applyToken);
3353 }
3354 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003355
3356 // Expected present time is computed and cached on invalidate, so it may be stale.
3357 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3358 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003359 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003360 uncacheBuffer, postTime, privileged,
3361 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003362 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003363 return;
3364 }
3365
Valerie Haubc6ddb12019-03-08 11:10:15 -08003366 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003367 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3368 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003369}
3370
Valerie Hau9dab9732019-08-20 09:29:25 -07003371void SurfaceFlinger::applyTransactionState(
3372 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3373 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3374 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3375 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3376 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003377 uint32_t transactionFlags = 0;
3378
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003379 if (flags & eAnimation) {
3380 // For window updates that are part of an animation we must wait for
3381 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003382 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003383 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003384 if (CC_UNLIKELY(err != NO_ERROR)) {
3385 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003386 // caller after a few seconds.
3387 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3388 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003389 mAnimTransactionPending = false;
3390 break;
3391 }
3392 }
3393 }
3394
chaviwca27f252018-02-06 16:46:39 -08003395 for (const DisplayState& display : displays) {
3396 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003397 }
3398
Valerie Hau9dab9732019-08-20 09:29:25 -07003399 // start and end registration for listeners w/ no surface so they can get their callback. Note
3400 // that listeners with SurfaceControls will start registration during setClientStateLocked
3401 // below.
3402 for (const auto& listener : listenerCallbacks) {
3403 mTransactionCompletedThread.startRegistration(listener);
3404 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003405 }
3406
Valerie Hau9dab9732019-08-20 09:29:25 -07003407 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003408 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003409 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003410 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3411 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003412 }
3413
Valerie Hau9dab9732019-08-20 09:29:25 -07003414 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003415 mTransactionCompletedThread.endRegistration(listenerCallback);
3416 }
3417
Marissa Walle2ffb422018-10-12 11:33:52 -07003418 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003419 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003420 mTransactionCompletedThread.sendCallbacks();
3421 }
3422 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003423
chaviw273171b2018-12-26 11:46:30 -08003424 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3425
Marissa Wall947d34e2019-03-29 14:03:53 -07003426 if (uncacheBuffer.isValid()) {
3427 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003428 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003429 }
3430
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003431 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3432 // anyway. This can be used as a flush mechanism for previous async transactions.
3433 // Empty animation transaction can be used to simulate back-pressure, so also force a
3434 // transaction for empty animation transactions.
3435 if (transactionFlags == 0 &&
3436 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003437 transactionFlags = eTransactionNeeded;
3438 }
3439
Marissa Wall06255332019-03-27 13:48:27 -07003440 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3441 // so we don't have to wake up again next frame to preform an uneeded traversal.
3442 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3443 transactionFlags = transactionFlags & (~eTraversalNeeded);
3444 mTraversalNeededMainThread = true;
3445 }
3446
Mathias Agopian386aa982011-11-07 21:58:03 -08003447 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003448 if (mInterceptor->isEnabled()) {
3449 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003450 }
Irvel468051e2016-06-13 16:44:44 -07003451
Mathias Agopian386aa982011-11-07 21:58:03 -08003452 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003453 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3454 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003455 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003456
3457 // if this is a synchronous transaction, wait for it to take effect
3458 // before returning.
3459 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003460 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003461 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003462 if (flags & eAnimation) {
3463 mAnimTransactionPending = true;
3464 }
chaviw4fe36852019-04-15 16:25:49 -07003465 if (mPendingInputWindowCommands.syncInputWindows) {
3466 mPendingSyncInputWindows = true;
3467 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003468
3469 // applyTransactionState can be called by either the main SF thread or by
3470 // another process through setTransactionState. While a given process may wish
3471 // to wait on synchronous transactions, the main SF thread should never
3472 // be blocked. Therefore, we only wait if isMainThread is false.
3473 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003474 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3475 if (CC_UNLIKELY(err != NO_ERROR)) {
3476 // just in case something goes wrong in SF, return to the
3477 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003478 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3479 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003480 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003481 break;
3482 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003483 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003484 }
3485}
3486
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003487uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3488 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3489 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003490
Mathias Agopiane57f2922012-08-09 16:29:12 -07003491 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003492 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3493
3494 const uint32_t what = s.what;
3495 if (what & DisplayState::eSurfaceChanged) {
3496 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3497 state.surface = s.surface;
3498 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003499 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003500 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003501 if (what & DisplayState::eLayerStackChanged) {
3502 if (state.layerStack != s.layerStack) {
3503 state.layerStack = s.layerStack;
3504 flags |= eDisplayTransactionNeeded;
3505 }
3506 }
3507 if (what & DisplayState::eDisplayProjectionChanged) {
3508 if (state.orientation != s.orientation) {
3509 state.orientation = s.orientation;
3510 flags |= eDisplayTransactionNeeded;
3511 }
3512 if (state.frame != s.frame) {
3513 state.frame = s.frame;
3514 flags |= eDisplayTransactionNeeded;
3515 }
3516 if (state.viewport != s.viewport) {
3517 state.viewport = s.viewport;
3518 flags |= eDisplayTransactionNeeded;
3519 }
3520 }
3521 if (what & DisplayState::eDisplaySizeChanged) {
3522 if (state.width != s.width) {
3523 state.width = s.width;
3524 flags |= eDisplayTransactionNeeded;
3525 }
3526 if (state.height != s.height) {
3527 state.height = s.height;
3528 flags |= eDisplayTransactionNeeded;
3529 }
3530 }
3531
Mathias Agopiane57f2922012-08-09 16:29:12 -07003532 return flags;
3533}
3534
Steven Thomasd4071902020-03-24 16:02:53 -07003535bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003536 IPCThreadState* ipc = IPCThreadState::self();
3537 const int pid = ipc->getCallingPid();
3538 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003539 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003540 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3541 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003542 return false;
3543 }
3544 return true;
3545}
3546
Marissa Wall3dad52d2019-03-22 14:03:19 -07003547uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003548 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3549 bool privileged,
3550 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003551 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003552
Valerie Hau9dab9732019-08-20 09:29:25 -07003553 for (auto& listener : s.listeners) {
3554 // note that startRegistration will not re-register if the listener has
3555 // already be registered for a prior surface control
3556 mTransactionCompletedThread.startRegistration(listener);
3557 listenerCallbacks.insert(listener);
3558 }
3559
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003560 sp<Layer> layer = nullptr;
3561 if (s.surface) {
3562 layer = fromHandle(s.surface);
3563 } else {
3564 // The client may provide us a null handle. Treat it as if the layer was removed.
3565 ALOGW("Attempt to set client state with a null layer handle");
3566 }
chaviw8b3871a2017-11-01 17:41:01 -07003567 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003568 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003569 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003570 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003571 }
chaviw8b3871a2017-11-01 17:41:01 -07003572 return 0;
3573 }
3574
chaviw8b3871a2017-11-01 17:41:01 -07003575 uint32_t flags = 0;
3576
Garfield Tan8a3083e2018-12-03 13:21:07 -08003577 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003578
3579 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3580 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003581 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003582 layer->pushPendingState();
3583 }
3584
Valerie Hau871d6352020-01-29 08:44:02 -08003585 // Only set by BLAST adapter layers
3586 if (what & layer_state_t::eProducerDisconnect) {
3587 layer->onDisconnect();
3588 }
3589
chaviw8b3871a2017-11-01 17:41:01 -07003590 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003591 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003592 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003593 }
chaviw8b3871a2017-11-01 17:41:01 -07003594 }
3595 if (what & layer_state_t::eLayerChanged) {
3596 // NOTE: index needs to be calculated before we update the state
3597 const auto& p = layer->getParent();
3598 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003599 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003600 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003601 mCurrentState.layersSortedByZ.removeAt(idx);
3602 mCurrentState.layersSortedByZ.add(layer);
3603 // we need traversal (state changed)
3604 // AND transaction (list changed)
3605 flags |= eTransactionNeeded|eTraversalNeeded;
3606 }
chaviw8b3871a2017-11-01 17:41:01 -07003607 } else {
3608 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003609 flags |= eTransactionNeeded|eTraversalNeeded;
3610 }
3611 }
chaviw8b3871a2017-11-01 17:41:01 -07003612 }
3613 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003614 // NOTE: index needs to be calculated before we update the state
3615 const auto& p = layer->getParent();
3616 if (p == nullptr) {
3617 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3618 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3619 mCurrentState.layersSortedByZ.removeAt(idx);
3620 mCurrentState.layersSortedByZ.add(layer);
3621 // we need traversal (state changed)
3622 // AND transaction (list changed)
3623 flags |= eTransactionNeeded|eTraversalNeeded;
3624 }
3625 } else {
3626 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3627 flags |= eTransactionNeeded|eTraversalNeeded;
3628 }
chaviw8b3871a2017-11-01 17:41:01 -07003629 }
3630 }
3631 if (what & layer_state_t::eSizeChanged) {
3632 if (layer->setSize(s.w, s.h)) {
3633 flags |= eTraversalNeeded;
3634 }
3635 }
3636 if (what & layer_state_t::eAlphaChanged) {
3637 if (layer->setAlpha(s.alpha))
3638 flags |= eTraversalNeeded;
3639 }
3640 if (what & layer_state_t::eColorChanged) {
3641 if (layer->setColor(s.color))
3642 flags |= eTraversalNeeded;
3643 }
Peiyong Lind3788632018-09-18 16:01:31 -07003644 if (what & layer_state_t::eColorTransformChanged) {
3645 if (layer->setColorTransform(s.colorTransform)) {
3646 flags |= eTraversalNeeded;
3647 }
3648 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003649 if (what & layer_state_t::eBackgroundColorChanged) {
3650 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3651 flags |= eTraversalNeeded;
3652 }
3653 }
chaviw8b3871a2017-11-01 17:41:01 -07003654 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003655 // TODO: b/109894387
3656 //
3657 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3658 // rotation. To see the problem observe that if we have a square parent, and a child
3659 // of the same size, then we rotate the child 45 degrees around it's center, the child
3660 // must now be cropped to a non rectangular 8 sided region.
3661 //
3662 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3663 // private API, and the WindowManager only uses rotation in one case, which is on a top
3664 // level layer in which cropping is not an issue.
3665 //
3666 // However given that abuse of rotation matrices could lead to surfaces extending outside
3667 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3668 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3669 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003670 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003671 flags |= eTraversalNeeded;
3672 }
3673 if (what & layer_state_t::eTransparentRegionChanged) {
3674 if (layer->setTransparentRegionHint(s.transparentRegion))
3675 flags |= eTraversalNeeded;
3676 }
3677 if (what & layer_state_t::eFlagsChanged) {
3678 if (layer->setFlags(s.flags, s.mask))
3679 flags |= eTraversalNeeded;
3680 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003681 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003682 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003683 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003684 if (what & layer_state_t::eCornerRadiusChanged) {
3685 if (layer->setCornerRadius(s.cornerRadius))
3686 flags |= eTraversalNeeded;
3687 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003688 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003689 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3690 }
chaviw8b3871a2017-11-01 17:41:01 -07003691 if (what & layer_state_t::eLayerStackChanged) {
3692 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3693 // We only allow setting layer stacks for top level layers,
3694 // everything else inherits layer stack from its parent.
3695 if (layer->hasParent()) {
3696 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003697 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003698 } else if (idx < 0) {
3699 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003700 "that also does not appear in the top level layer list. Something"
3701 " has gone wrong.",
3702 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003703 } else if (layer->setLayerStack(s.layerStack)) {
3704 mCurrentState.layersSortedByZ.removeAt(idx);
3705 mCurrentState.layersSortedByZ.add(layer);
3706 // we need traversal (state changed)
3707 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003708 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003709 }
3710 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003711 if (what & layer_state_t::eDeferTransaction_legacy) {
3712 if (s.barrierHandle_legacy != nullptr) {
3713 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3714 } else if (s.barrierGbp_legacy != nullptr) {
3715 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003716 if (authenticateSurfaceTextureLocked(gbp)) {
3717 const auto& otherLayer =
3718 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003719 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003720 } else {
3721 ALOGE("Attempt to defer transaction to to an"
3722 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003723 }
3724 }
chaviw8b3871a2017-11-01 17:41:01 -07003725 // We don't trigger a traversal here because if no other state is
3726 // changed, we don't want this to cause any more work
3727 }
chaviw8b3871a2017-11-01 17:41:01 -07003728 if (what & layer_state_t::eReparentChildren) {
3729 if (layer->reparentChildren(s.reparentHandle)) {
3730 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003731 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003732 }
chaviw8b3871a2017-11-01 17:41:01 -07003733 if (what & layer_state_t::eDetachChildren) {
3734 layer->detachChildren();
3735 }
3736 if (what & layer_state_t::eOverrideScalingModeChanged) {
3737 layer->setOverrideScalingMode(s.overrideScalingMode);
3738 // We don't trigger a traversal here because if no other state is
3739 // changed, we don't want this to cause any more work
3740 }
Marissa Wall61c58622018-07-18 10:12:20 -07003741 if (what & layer_state_t::eTransformChanged) {
3742 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3743 }
3744 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3745 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3746 flags |= eTraversalNeeded;
3747 }
3748 if (what & layer_state_t::eCropChanged) {
3749 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3750 }
Marissa Wall861616d2018-10-22 12:52:23 -07003751 if (what & layer_state_t::eFrameChanged) {
3752 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3753 }
Marissa Wall61c58622018-07-18 10:12:20 -07003754 if (what & layer_state_t::eAcquireFenceChanged) {
3755 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3756 }
3757 if (what & layer_state_t::eDataspaceChanged) {
3758 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3759 }
3760 if (what & layer_state_t::eHdrMetadataChanged) {
3761 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3762 }
3763 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3764 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3765 }
3766 if (what & layer_state_t::eApiChanged) {
3767 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3768 }
3769 if (what & layer_state_t::eSidebandStreamChanged) {
3770 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3771 }
Robert Carr720e5062018-07-30 17:45:14 -07003772 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003773 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003774 layer->setInputInfo(s.inputInfo);
3775 flags |= eTraversalNeeded;
3776 } else {
3777 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3778 }
Robert Carr720e5062018-07-30 17:45:14 -07003779 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003780 if (what & layer_state_t::eMetadataChanged) {
3781 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3782 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003783 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3784 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3785 flags |= eTraversalNeeded;
3786 }
3787 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003788 if (what & layer_state_t::eShadowRadiusChanged) {
3789 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3790 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003791 if (what & layer_state_t::eFrameRateSelectionPriority) {
3792 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3793 flags |= eTraversalNeeded;
3794 }
3795 }
Steven Thomas3172e202020-01-06 19:25:30 -08003796 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003797 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3798 "SurfaceFlinger::setClientStateLocked") &&
3799 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3800 Layer::FrameRate::convertCompatibility(
3801 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003802 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003803 }
Steven Thomas3172e202020-01-06 19:25:30 -08003804 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003805 // This has to happen after we reparent children because when we reparent to null we remove
3806 // child layers from current state and remove its relative z. If the children are reparented in
3807 // the same transaction, then we have to make sure we reparent the children first so we do not
3808 // lose its relative z order.
3809 if (what & layer_state_t::eReparent) {
3810 bool hadParent = layer->hasParent();
3811 if (layer->reparent(s.parentHandleForChild)) {
3812 if (!hadParent) {
3813 mCurrentState.layersSortedByZ.remove(layer);
3814 }
3815 flags |= eTransactionNeeded | eTraversalNeeded;
3816 }
3817 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003818 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003819 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3820 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003821 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3822 }
3823 }
Marissa Wall78b72202019-03-15 14:58:34 -07003824 bool bufferChanged = what & layer_state_t::eBufferChanged;
3825 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3826 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003827 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003828 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003829 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3830 if (success) {
3831 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3832 success = ClientCache::getInstance()
3833 .registerErasedRecipient(s.cachedBuffer,
3834 wp<ClientCache::ErasedRecipient>(this));
3835 if (!success) {
3836 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3837 }
3838 }
Marissa Wall78b72202019-03-15 14:58:34 -07003839 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003840 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003841 } else if (bufferChanged) {
3842 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003843 }
Marissa Wall78b72202019-03-15 14:58:34 -07003844 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003845 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3846 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003847 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003848 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003849 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003850 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3851 // Do not put anything that updates layer state or modifies flags after
3852 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003853 return flags;
3854}
3855
chaviw273171b2018-12-26 11:46:30 -08003856uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3857 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003858 if (inputWindowCommands.syncInputWindows) {
3859 flags |= eTraversalNeeded;
3860 }
3861
Vishnu Nairec0ab382019-02-13 15:32:56 -08003862 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003863 return flags;
3864}
3865
chaviwfe94a222019-08-21 13:52:59 -07003866status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3867 sp<IBinder>* outHandle) {
3868 if (!mirrorFromHandle) {
3869 return NAME_NOT_FOUND;
3870 }
3871
3872 sp<Layer> mirrorLayer;
3873 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003874 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003875
3876 {
3877 Mutex::Autolock _l(mStateLock);
3878 mirrorFrom = fromHandle(mirrorFromHandle);
3879 if (!mirrorFrom) {
3880 return NAME_NOT_FOUND;
3881 }
3882
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003883 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3884 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003885 if (result != NO_ERROR) {
3886 return result;
3887 }
3888
3889 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3890 }
3891
3892 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3893}
3894
Marissa Wall2d814fb2019-04-09 18:52:57 +00003895status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3896 uint32_t h, PixelFormat format, uint32_t flags,
3897 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003898 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003899 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3900 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003901 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003902 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003903 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003904 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003905 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003906
Robert Carrc0df3122019-04-11 13:18:21 -07003907 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3908 "Expected only one of parentLayer or parentHandle to be non-null. "
3909 "Programmer error?");
3910
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003911 status_t result = NO_ERROR;
3912
3913 sp<Layer> layer;
3914
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003915 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003916
Evan Roskya1f1e152019-01-24 16:17:46 -08003917 bool primaryDisplayOnly = false;
3918
3919 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3920 // TODO b/64227542
3921 if (metadata.has(METADATA_WINDOW_TYPE)) {
3922 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3923 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003924 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003925 primaryDisplayOnly = true;
3926 }
3927 }
3928
Mathias Agopian3165cc22012-08-08 19:42:09 -07003929 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003930 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003931 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3932 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003933
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003934 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003935 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003936 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003937 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003938 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003939 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003940 // check if buffer size is set for color layer.
3941 if (w > 0 || h > 0) {
3942 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3943 int(w), int(h));
3944 return BAD_VALUE;
3945 }
3946
Vishnu Nairfa247b12020-02-11 08:58:26 -08003947 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3948 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003949 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003950 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003951 // check if buffer size is set for container layer.
3952 if (w > 0 || h > 0) {
3953 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3954 int(w), int(h));
3955 return BAD_VALUE;
3956 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003957 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3958 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003959 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003960 default:
3961 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003962 break;
3963 }
3964
Dan Stoza7d89d062015-04-30 13:29:25 -07003965 if (result != NO_ERROR) {
3966 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003967 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003968
Evan Roskya1f1e152019-01-24 16:17:46 -08003969 if (primaryDisplayOnly) {
3970 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003971 }
3972
Robert Carrb89ea9d2018-12-10 13:01:14 -08003973 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003974 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3975 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003976 if (result != NO_ERROR) {
3977 return result;
3978 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003979 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003980
3981 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003982 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003983}
3984
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003985std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3986 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003987
3988 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003989 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003990
Dan Stoza436ccf32018-06-21 12:10:12 -07003991 // Grab the state lock since we're accessing mCurrentState
3992 Mutex::Autolock lock(mStateLock);
3993
Cody Northropbc755282017-03-31 12:00:08 -06003994 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003995 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003996 while (matchFound) {
3997 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003998 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003999 if (layer->getName() == uniqueName) {
4000 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004001 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004002 }
4003 });
4004 }
4005
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004006 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004007 return uniqueName;
4008}
4009
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004010status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07004011 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004012 LayerMetadata metadata, PixelFormat& format,
4013 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004014 sp<IGraphicBufferProducer>* gbp,
4015 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004016 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004017 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018 case PIXEL_FORMAT_TRANSPARENT:
4019 case PIXEL_FORMAT_TRANSLUCENT:
4020 format = PIXEL_FORMAT_RGBA_8888;
4021 break;
4022 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004023 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004024 break;
4025 }
4026
chaviwb4c6e582019-08-16 14:35:07 -07004027 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004028 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004029 args.textureName = getNewTexture();
4030 {
4031 // Grab the SF state lock during this since it's the only safe way to access
4032 // RenderEngine when creating a BufferLayerConsumer
4033 // TODO: Check if this lock is still needed here
4034 Mutex::Autolock lock(mStateLock);
4035 layer = getFactory().createBufferQueueLayer(args);
4036 }
4037
Marissa Wallfd668622018-05-10 10:21:13 -07004038 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004039 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004040 *handle = layer->getHandle();
4041 *gbp = layer->getProducer();
4042 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004043 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004044
Marissa Wallfd668622018-05-10 10:21:13 -07004045 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004046 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004047}
4048
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004049status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004050 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004051 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004052 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004053 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004054 args.displayDevice = getDefaultDisplayDevice();
4055 args.textureName = getNewTexture();
4056 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004057 if (outTransformHint) {
4058 *outTransformHint = layer->getTransformHint();
4059 }
Marissa Wall61c58622018-07-18 10:12:20 -07004060 *handle = layer->getHandle();
4061 *outLayer = layer;
4062
4063 return NO_ERROR;
4064}
4065
Vishnu Nairfa247b12020-02-11 08:58:26 -08004066status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4067 uint32_t h, uint32_t flags, LayerMetadata metadata,
4068 sp<IBinder>* handle, sp<Layer>* outLayer) {
4069 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004070 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004071 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004072 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004073}
4074
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004075status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004076 uint32_t w, uint32_t h, uint32_t flags,
4077 LayerMetadata metadata, sp<IBinder>* handle,
4078 sp<Layer>* outLayer) {
4079 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004080 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004081 *handle = (*outLayer)->getHandle();
4082 return NO_ERROR;
4083}
4084
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004085void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004086 mLayersPendingRemoval.add(layer);
4087 mLayersRemoved = true;
4088 setTransactionFlags(eTransactionNeeded);
4089}
4090
Robert Carr695d5282018-12-18 15:27:58 -08004091void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004092{
Robert Carr2e102c92018-10-23 12:11:15 -07004093 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004094 // If a layer has a parent, we allow it to out-live it's handle
4095 // with the idea that the parent holds a reference and will eventually
4096 // be cleaned up. However no one cleans up the top-level so we do so
4097 // here.
4098 if (layer->getParent() == nullptr) {
4099 mCurrentState.layersSortedByZ.remove(layer);
4100 }
4101 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004102
4103 auto it = mLayersByLocalBinderToken.begin();
4104 while (it != mLayersByLocalBinderToken.end()) {
4105 if (it->second == layer) {
4106 it = mLayersByLocalBinderToken.erase(it);
4107 } else {
4108 it++;
4109 }
4110 }
4111
Robert Carr695d5282018-12-18 15:27:58 -08004112 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004113}
4114
Mathias Agopianb60314a2012-04-10 22:09:54 -07004115// ---------------------------------------------------------------------------
4116
Andy McFadden13a082e2012-08-24 10:16:42 -07004117void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004118 const auto display = getDefaultDisplayDeviceLocked();
4119 if (!display) return;
4120
4121 const sp<IBinder> token = display->getDisplayToken().promote();
4122 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004123
Jesse Hall01e29052013-02-19 16:13:35 -08004124 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004125 Vector<ComposerState> state;
4126 Vector<DisplayState> displays;
4127 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004128 d.what = DisplayState::eDisplayProjectionChanged |
4129 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004130 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004131 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004132 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004133 d.frame.makeInvalid();
4134 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004135 d.width = 0;
4136 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004137 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004138 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4139 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004140
Dominik Laskowskie9774092018-12-11 10:04:24 -08004141 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004142
Dominik Laskowski83b88212018-12-11 13:34:06 -08004143 const nsecs_t vsyncPeriod = getVsyncPeriod();
4144 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004145
Brian Andersond0010582017-03-07 13:20:31 -08004146 // Use phase of 0 since phase is not known.
4147 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004148 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004149 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004150}
4151
4152void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004153 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004154 postMessageAsync(
4155 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004156}
4157
Ady Abraham27c70212019-06-11 10:52:26 -07004158void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4159 if (mHWCVsyncState != enabled) {
4160 getHwComposer().setVsyncEnabled(displayId, enabled);
4161 mHWCVsyncState = enabled;
4162 }
4163}
4164
Dominik Laskowskie9774092018-12-11 10:04:24 -08004165void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004166 if (display->isVirtual()) {
4167 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004168 return;
4169 }
4170
Dominik Laskowski075d3172018-05-24 15:50:06 -07004171 const auto displayId = display->getId();
4172 LOG_ALWAYS_FATAL_IF(!displayId);
4173
Dominik Laskowski34157762018-10-31 13:07:19 -07004174 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004175
4176 int currentMode = display->getPowerMode();
4177 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004178 return;
4179 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004180
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004181 display->setPowerMode(mode);
4182
Lloyd Pique4dccc412018-01-22 17:21:36 -08004183 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004184 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004185 }
4186
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004187 if (currentMode == HWC_POWER_MODE_OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004188 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4189 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4190 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004191 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004192 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004193 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004194 mScheduler->onScreenAcquired(mAppConnectionHandle);
4195 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004196 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004197
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004198 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004199 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004200 repaintEverything();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004201 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004202 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004203 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4204 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004205 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004206 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004207 mScheduler->disableHardwareVsync(true);
4208 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004209 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004210
Ady Abraham27c70212019-06-11 10:52:26 -07004211 // Make sure HWVsync is disabled before turning off the display
4212 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4213
Dominik Laskowski075d3172018-05-24 15:50:06 -07004214 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004215 mVisibleRegionsDirty = true;
4216 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004217 } else if (mode == HWC_POWER_MODE_DOZE ||
4218 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004219 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004220 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004221 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004222 mScheduler->onScreenAcquired(mAppConnectionHandle);
4223 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004224 }
4225 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4226 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004227 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004228 mScheduler->disableHardwareVsync(true);
4229 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004230 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004231 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004232 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004233 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004234 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004235 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004236
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004237 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004238 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004239 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004240 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004241 }
4242
Dominik Laskowski34157762018-10-31 13:07:19 -07004243 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004244}
4245
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004246void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004247 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004248 const auto display = getDisplayDevice(displayToken);
4249 if (!display) {
4250 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4251 displayToken.get());
4252 } else if (display->isVirtual()) {
4253 ALOGW("Attempt to set power mode %d for virtual display", mode);
4254 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004255 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004256 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004257 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004258}
4259
4260// ---------------------------------------------------------------------------
4261
Dominik Laskowskic2867142019-01-21 11:33:38 -08004262status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4263 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004264 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004265
Mathias Agopianbd115332013-04-18 16:41:04 -07004266 IPCThreadState* ipc = IPCThreadState::self();
4267 const int pid = ipc->getCallingPid();
4268 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004269
Mathias Agopianbd115332013-04-18 16:41:04 -07004270 if ((uid != AID_SHELL) &&
4271 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004272 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4273 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004274 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004275 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004276 // (this would indicate SF is stuck, but we want to be able to
4277 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004278 status_t err = mStateLock.timedLock(s2ns(1));
4279 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004280 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004281 StringAppendF(&result,
4282 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4283 "(no locks held)\n",
4284 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004285 }
4286
Dominik Laskowskic2867142019-01-21 11:33:38 -08004287 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004288 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004289 {"--dispsync"s,
4290 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004291 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004292 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4293 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4294 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4295 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4296 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4297 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004298 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004299 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4300 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004301
Dominik Laskowskic2867142019-01-21 11:33:38 -08004302 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004303
Dominik Laskowski46470112019-08-02 13:13:11 -07004304 const auto it = dumpers.find(flag);
4305 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004306 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004307 } else if (!asProto) {
4308 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004309 }
4310
Mathias Agopian9795c422009-08-26 16:36:26 -07004311 if (locked) {
4312 mStateLock.unlock();
4313 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004314
Dominik Laskowski46470112019-08-02 13:13:11 -07004315 if (it == dumpers.end()) {
4316 const LayersProto layersProto = dumpProtoFromMainThread();
4317 if (asProto) {
4318 result.append(layersProto.SerializeAsString());
4319 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004320 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004321 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4322 result.append(LayerProtoParser::layerTreeToString(layerTree));
4323 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004324 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004325 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004326 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004327 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004328 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004329 return NO_ERROR;
4330}
4331
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004332status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4333 if (asProto && mTracing.isEnabled()) {
4334 mTracing.writeToFileAsync();
4335 }
4336
4337 return doDump(fd, DumpArgs(), asProto);
4338}
4339
Dominik Laskowskic2867142019-01-21 11:33:38 -08004340void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004341 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004342 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004343}
4344
Dominik Laskowskic2867142019-01-21 11:33:38 -08004345void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004346 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004347
Dominik Laskowskic2867142019-01-21 11:33:38 -08004348 if (args.size() > 1) {
4349 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004350 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004351 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004352 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004353 }
Robert Carr2047fae2016-11-28 14:09:09 -08004354 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004355 } else {
4356 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004357 }
4358}
4359
Dominik Laskowskic2867142019-01-21 11:33:38 -08004360void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004361 const bool clearAll = args.size() < 2;
4362 const auto name = clearAll ? String8() : String8(args[1]);
4363
Edgar Arriaga844fa672020-01-16 14:21:42 -08004364 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004365 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004366 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004367 }
Robert Carr2047fae2016-11-28 14:09:09 -08004368 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004369
Svetoslavd85084b2014-03-20 10:28:31 -07004370 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004371}
4372
Dominik Laskowskic2867142019-01-21 11:33:38 -08004373void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4374 mTimeStats->parseArgs(asProto, args, result);
4375}
4376
Jamie Gennis6547ff42013-07-16 20:12:42 -07004377// This should only be called from the main thread. Otherwise it would need
4378// the lock and should use mCurrentState rather than mDrawingState.
4379void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004380 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004381 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004382 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004383
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004384 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004385}
4386
Yiwei Zhang5434a782018-12-05 18:06:32 -08004387void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004388 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004389
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004390 if (isLayerTripleBufferingDisabled())
4391 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004392
Yiwei Zhang5434a782018-12-05 18:06:32 -08004393 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4394 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4395 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4396 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4397 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4398 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004399 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004400}
4401
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004402void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004403 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004404
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004405 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004406 result.append("\n");
4407
Ady Abraham9e16a482019-12-03 17:19:41 -08004408 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004409 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004410 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004411 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004412
Steven Thomasd4071902020-03-24 16:02:53 -07004413 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004414 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004415 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004416 ", min: %.2f Hz, max: %.2f Hz",
Steven Thomasd4071902020-03-24 16:02:53 -07004417 policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004418 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4419 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004420
Ana Krulecc2870422019-01-29 19:00:58 -08004421 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004422 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004423}
4424
Yiwei Zhang5434a782018-12-05 18:06:32 -08004425void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4426 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004427 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4428 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004429 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004430 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004431 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004432 }
David Sodman4a36e932017-11-07 14:29:47 -08004433 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004434 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004435 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004436 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4437 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004438}
4439
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004440void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4441 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004442 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4443 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004444 for (const auto& segment : history) {
4445 if (!segment.usedThirdBuffer) {
4446 stats.twoBufferTime += segment.totalTime;
4447 }
4448 if (segment.occupancyAverage < 1.0f) {
4449 stats.doubleBufferedTime += segment.totalTime;
4450 } else if (segment.occupancyAverage < 2.0f) {
4451 stats.tripleBufferedTime += segment.totalTime;
4452 }
4453 ++stats.numSegments;
4454 stats.totalTime += segment.totalTime;
4455 }
4456}
4457
Yiwei Zhang5434a782018-12-05 18:06:32 -08004458void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4459 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004460
4461 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4462 const size_t count = currentLayers.size();
4463 for (size_t i=0 ; i<count ; i++) {
4464 currentLayers[i]->dumpFrameEvents(result);
4465 }
4466}
4467
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004469 result.append("Buffering stats:\n");
4470 result.append(" [Layer name] <Active time> <Two buffer> "
4471 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004472 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004473 typedef std::tuple<std::string, float, float, float> BufferTuple;
4474 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004475 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004476 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004477 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004478 if (stats.numSegments == 0) {
4479 continue;
4480 }
4481 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4482 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4483 stats.totalTime;
4484 float doubleBufferRatio = static_cast<float>(
4485 stats.doubleBufferedTime) / stats.totalTime;
4486 float tripleBufferRatio = static_cast<float>(
4487 stats.tripleBufferedTime) / stats.totalTime;
4488 sorted.insert({activeTime, {name, twoBufferRatio,
4489 doubleBufferRatio, tripleBufferRatio}});
4490 }
4491 for (const auto& sortedPair : sorted) {
4492 float activeTime = sortedPair.first;
4493 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004494 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4495 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004496 }
4497 result.append("\n");
4498}
4499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004501 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004502 const auto displayId = display->getId();
4503 if (!displayId) {
4504 continue;
4505 }
4506 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004507 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004508 continue;
4509 }
4510
Yiwei Zhang5434a782018-12-05 18:06:32 -08004511 StringAppendF(&result,
4512 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4513 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004514 uint8_t port;
4515 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004516 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004517 result.append("no identification data\n");
4518 continue;
4519 }
4520
4521 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004522 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004523 continue;
4524 }
4525
4526 const auto edid = parseEdid(data);
4527 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004528 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004529 continue;
4530 }
4531
Yiwei Zhang5434a782018-12-05 18:06:32 -08004532 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004533 result.append(edid->displayName.data(), edid->displayName.length());
4534 result.append("\"\n");
4535 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004536}
4537
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004538void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4539 std::string& result) const {
4540 hwc2_display_t hwcDisplayId;
4541 uint8_t port;
4542 DisplayIdentificationData data;
4543
4544 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4545 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4546 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4547 }
4548}
4549
Yiwei Zhang5434a782018-12-05 18:06:32 -08004550void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004551 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004552 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4553 StringAppendF(&result, "DisplayColorSetting: %s\n",
4554 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004555
4556 // TODO: print out if wide-color mode is active or not
4557
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004558 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004559 const auto displayId = display->getId();
4560 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004561 continue;
4562 }
4563
Yiwei Zhang5434a782018-12-05 18:06:32 -08004564 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004565 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004566 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004567 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004568 }
4569
Lloyd Pique32cbe282018-10-19 13:09:22 -07004570 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004571 StringAppendF(&result, " Current color mode: %s (%d)\n",
4572 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004573 }
4574 result.append("\n");
4575}
4576
Alec Mouri5793c7d2020-03-10 19:55:50 -07004577LayersProto SurfaceFlinger::dumpDrawingStateProto(
4578 uint32_t traceFlags, const sp<const DisplayDevice>& displayDevice) const {
chaviw1d044282017-09-27 12:19:28 -07004579 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004580 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri5793c7d2020-03-10 19:55:50 -07004581 layer->writeToProto(layersProto, traceFlags, displayDevice);
chaviw08f3cb22020-01-13 13:17:21 -08004582 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004583
chaviw1d044282017-09-27 12:19:28 -07004584 return layersProto;
4585}
4586
Alec Mouri6b9e9912020-01-21 10:50:24 -08004587void SurfaceFlinger::dumpHwc(std::string& result) const {
4588 getHwComposer().dump(result);
4589}
4590
Vishnu Nair0f085c62019-08-30 08:49:12 -07004591void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4592 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4593 // it.
4594 LayerProto* rootProto = layersProto.add_layers();
4595 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4596 rootProto->set_id(offscreenRootLayerId);
4597 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004598 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004599
4600 for (Layer* offscreenLayer : mOffscreenLayers) {
4601 // Add layer as child of the fake root
4602 rootProto->add_children(offscreenLayer->sequence);
4603
4604 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004605 LayerProto* layerProto =
4606 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004607 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004608 }
4609}
4610
Vishnu Nair8406fd72019-07-30 11:29:31 -07004611LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4612 LayersProto layersProto;
Alec Mouri5793c7d2020-03-10 19:55:50 -07004613 postMessageSync(new LambdaMessage([&]() {
4614 const auto& displayDevice = getDefaultDisplayDeviceLocked();
4615 layersProto = dumpDrawingStateProto(traceFlags, displayDevice);
4616 }));
Vishnu Nair8406fd72019-07-30 11:29:31 -07004617 return layersProto;
4618}
4619
Vishnu Nair0f085c62019-08-30 08:49:12 -07004620void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4621 result.append("Offscreen Layers:\n");
4622 postMessageSync(new LambdaMessage([&]() {
4623 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004624 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004625 layer->dumpCallingUidPid(result);
4626 });
4627 }
4628 }));
4629}
4630
Dominik Laskowskic2867142019-01-21 11:33:38 -08004631void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4632 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004633 Colorizer colorizer(colorize);
4634
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004635 // figure out if we're stuck somewhere
4636 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004637 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004638 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4639
4640 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004641 * Dump library configuration.
4642 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004643
4644 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004645 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004646 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004647 appendSfConfigString(result);
4648 appendUiConfigString(result);
4649 appendGuiConfigString(result);
4650 result.append("\n");
4651
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004652 result.append("\nDisplay identification data:\n");
4653 dumpDisplayIdentificationData(result);
4654
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004655 result.append("\nWide-Color information:\n");
4656 dumpWideColorInfo(result);
4657
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004658 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004659 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004660 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004661 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004662 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004663
Andy McFadden41d67d72014-04-25 16:58:34 -07004664 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004665 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004666 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004667 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004668 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004669
Dan Stozab90cf072015-03-05 11:05:59 -08004670 dumpStaticScreenStats(result);
4671 result.append("\n");
4672
Alec Mouri40189b02019-03-05 15:07:54 -08004673 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4674 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4675 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004676
Dan Stozae77c7662016-05-13 11:37:28 -07004677 dumpBufferingStats(result);
4678
Andy McFadden4803b742012-09-24 19:07:20 -07004679 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004680 * Dump the visible layer list
4681 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004682 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004683 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004684 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4685 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004686 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004687
Chia-I Wu2f884132018-09-13 15:17:58 -07004688 {
Lloyd Pique207def92019-02-28 16:09:52 -08004689 StringAppendF(&result, "Composition layers\n");
4690 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004691 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08004692 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08004693
4694 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4695 layer->getDebugName() ? layer->getDebugName()
4696 : "<unknown>");
4697 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004698 });
4699 }
4700
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004701 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004702 * Dump Display state
4703 */
4704
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004705 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004706 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004707 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004708 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004709 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004710 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004711 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004712
4713 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004714 * Dump CompositionEngine state
4715 */
4716
4717 mCompositionEngine->dump(result);
4718
4719 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004720 * Dump SurfaceFlinger global state
4721 */
4722
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004723 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004724 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004725 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004726
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004727 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004728
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004729 DebugEGLImageTracker::getInstance()->dump(result);
4730
Dominik Laskowski075d3172018-05-24 15:50:06 -07004731 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004732 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4733 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004734 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4735 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004736 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004737 StringAppendF(&result,
4738 " transaction-flags : %08x\n"
4739 " gpu_to_cpu_unsupported : %d\n",
4740 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004741
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004742 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004743 displayId && getHwComposer().isConnected(*displayId)) {
4744 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004745 StringAppendF(&result,
4746 " refresh-rate : %f fps\n"
4747 " x-dpi : %f\n"
4748 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004749 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4750 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004751 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004752
Yiwei Zhang5434a782018-12-05 18:06:32 -08004753 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004754
Dan Stozae22aec72016-08-01 13:20:59 -07004755 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004756 * Tracing state
4757 */
4758 mTracing.dump(result);
4759 result.append("\n");
4760
4761 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004762 * HWC layer minidump
4763 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004764 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004765 const auto displayId = display->getId();
4766 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004767 continue;
4768 }
4769
Yiwei Zhang5434a782018-12-05 18:06:32 -08004770 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004771 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004772 const sp<DisplayDevice> displayDevice = display;
4773 mCurrentState.traverseInZOrder(
4774 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004775 result.append("\n");
4776 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004777
4778 /*
4779 * Dump HWComposer state
4780 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004781 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004782 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004783 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004784 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004785 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004786 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004787
4788 /*
4789 * Dump gralloc state
4790 */
4791 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4792 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004793
4794 /*
4795 * Dump VrFlinger state if in use.
4796 */
4797 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4798 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004799 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004800 result.append("\n");
4801 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004802
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004803 result.append(mTimeStats->miniDump());
4804 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004805}
4806
Chia-I Wu28f320b2018-05-03 11:02:56 -07004807void SurfaceFlinger::updateColorMatrixLocked() {
4808 mat4 colorMatrix;
4809 if (mGlobalSaturationFactor != 1.0f) {
4810 // Rec.709 luma coefficients
4811 float3 luminance{0.213f, 0.715f, 0.072f};
4812 luminance *= 1.0f - mGlobalSaturationFactor;
4813 mat4 saturationMatrix = mat4(
4814 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4815 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4816 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4817 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4818 );
4819 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4820 } else {
4821 colorMatrix = mClientColorMatrix * mDaltonizer();
4822 }
4823
4824 if (mCurrentState.colorMatrix != colorMatrix) {
4825 mCurrentState.colorMatrix = colorMatrix;
4826 mCurrentState.colorMatrixChanged = true;
4827 setTransactionFlags(eTransactionNeeded);
4828 }
4829}
4830
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004831status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004832#pragma clang diagnostic push
4833#pragma clang diagnostic error "-Wswitch-enum"
4834 switch (static_cast<ISurfaceComposerTag>(code)) {
4835 // These methods should at minimum make sure that the client requested
4836 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004837 case BOOT_FINISHED:
4838 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004839 case CREATE_DISPLAY:
4840 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004841 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004842 case GET_ANIMATION_FRAME_STATS:
4843 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004844 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004845 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004846 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004847 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4848 case SET_AUTO_LOW_LATENCY_MODE:
4849 case GET_GAME_CONTENT_TYPE_SUPPORT:
4850 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004851 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004852 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004853 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004854 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004855 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004856 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004857 case SET_GLOBAL_SHADOW_SETTINGS:
4858 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4859 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4860 // necessary permission dynamically. Don't use the permission cache for this check.
4861 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4862 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004863 IPCThreadState* ipc = IPCThreadState::self();
4864 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4865 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004866 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004867 }
Robert Carr1db73f62016-12-21 12:58:51 -08004868 return OK;
4869 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004870 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004871 IPCThreadState* ipc = IPCThreadState::self();
4872 const int pid = ipc->getCallingPid();
4873 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004874 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4875 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004876 return PERMISSION_DENIED;
4877 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004878 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004879 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004880 // Used by apps to hook Choreographer to SurfaceFlinger.
4881 case CREATE_DISPLAY_EVENT_CONNECTION:
4882 // The following calls are currently used by clients that do not
4883 // request necessary permissions. However, they do not expose any secret
4884 // information, so it is OK to pass them.
4885 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004886 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004887 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004888 case GET_PHYSICAL_DISPLAY_IDS:
4889 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004890 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004891 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004892 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004893 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004894 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004895 case GET_DISPLAY_STATS:
4896 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4897 // Calling setTransactionState is safe, because you need to have been
4898 // granted a reference to Client* and Handle* to do anything with it.
4899 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004900 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004901 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004902 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004903 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004904 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004905 // setFrameRate() is deliberately available for apps to call without any
4906 // special permissions.
4907 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004908 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4909 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004910 return OK;
4911 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004912 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004913 case CAPTURE_SCREEN:
4914 case ADD_REGION_SAMPLING_LISTENER:
4915 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004916 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004917 IPCThreadState* ipc = IPCThreadState::self();
4918 const int pid = ipc->getCallingPid();
4919 const int uid = ipc->getCallingUid();
4920 if ((uid != AID_GRAPHICS) &&
4921 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4922 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4923 return PERMISSION_DENIED;
4924 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004925 return OK;
4926 }
chaviw93df2ea2019-04-30 16:45:12 -07004927 case CAPTURE_SCREEN_BY_ID: {
4928 IPCThreadState* ipc = IPCThreadState::self();
4929 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004930 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004931 return OK;
4932 }
4933 return PERMISSION_DENIED;
4934 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004935 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004936
4937 // These codes are used for the IBinder protocol to either interrogate the recipient
4938 // side of the transaction for its canonical interface descriptor or to dump its state.
4939 // We let them pass by default.
4940 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4941 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4942 code == IBinder::SYSPROPS_TRANSACTION) {
4943 return OK;
4944 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004945 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004946 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004947 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004948 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4949 return OK;
4950 }
4951 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4952 return PERMISSION_DENIED;
4953#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004954}
4955
Ana Krulec13be8ad2018-08-21 02:43:56 +00004956status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4957 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004958 status_t credentialCheck = CheckTransactCodeCredentials(code);
4959 if (credentialCheck != OK) {
4960 return credentialCheck;
4961 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004962
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004963 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4964 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004965 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004966 IPCThreadState* ipc = IPCThreadState::self();
4967 const int uid = ipc->getCallingUid();
4968 if (CC_UNLIKELY(uid != AID_SYSTEM
4969 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004970 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004971 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004972 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004973 return PERMISSION_DENIED;
4974 }
4975 int n;
4976 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004977 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004978 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004979 return NO_ERROR;
4980 case 1002: // SHOW_UPDATES
4981 n = data.readInt32();
4982 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004983 invalidateHwcGeometry();
4984 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004985 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004986 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004987 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004988 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004990 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004991 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004992 setTransactionFlags(
4993 eTransactionNeeded|
4994 eDisplayTransactionNeeded|
4995 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004996 return NO_ERROR;
4997 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004998 case 1006:{ // send empty update
4999 signalRefresh();
5000 return NO_ERROR;
5001 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005002 case 1008: // toggle use of hw composer
5003 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005004 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005005 invalidateHwcGeometry();
5006 repaintEverything();
5007 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005008 case 1009: // toggle use of transform hint
5009 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005010 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005011 invalidateHwcGeometry();
5012 repaintEverything();
5013 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005014 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005015 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005016 reply->writeInt32(0);
5017 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005018 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005019 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005020 return NO_ERROR;
5021 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005022 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005023 if (!display) {
5024 return NAME_NOT_FOUND;
5025 }
5026
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005027 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005028 return NO_ERROR;
5029 }
5030 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005031 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005032 // daltonize
5033 n = data.readInt32();
5034 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005035 case 1:
5036 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5037 break;
5038 case 2:
5039 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5040 break;
5041 case 3:
5042 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5043 break;
5044 default:
5045 mDaltonizer.setType(ColorBlindnessType::None);
5046 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005047 }
5048 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005049 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005050 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005051 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005052 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005053
5054 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005055 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005056 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005057 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005058 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005059 // apply a color matrix
5060 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005061 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005062 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005063 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005064 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005065 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005066 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005067 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005068 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005069 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005070 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005071
5072 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5073 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005074 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005075 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5076 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5077 }
5078
Chia-I Wu28f320b2018-05-03 11:02:56 -07005079 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005080 return NO_ERROR;
5081 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005082 case 1016: { // Unused.
5083 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005084 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005085 case 1017: {
5086 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005087 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005088 return NO_ERROR;
5089 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005090 case 1018: { // Modify Choreographer's phase offset
5091 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005092 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005093 return NO_ERROR;
5094 }
5095 case 1019: { // Modify SurfaceFlinger's phase offset
5096 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005097 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005098 return NO_ERROR;
5099 }
Irvel468051e2016-06-13 16:44:44 -07005100 case 1020: { // Layer updates interceptor
5101 n = data.readInt32();
5102 if (n) {
5103 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005104 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005105 }
5106 else{
5107 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005108 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005109 }
5110 return NO_ERROR;
5111 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005112 case 1021: { // Disable HWC virtual displays
5113 n = data.readInt32();
5114 mUseHwcVirtualDisplays = !n;
5115 return NO_ERROR;
5116 }
Romain Guy0147a172017-06-01 13:53:56 -07005117 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005118 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005119 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005120
Chia-I Wu28f320b2018-05-03 11:02:56 -07005121 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005122 return NO_ERROR;
5123 }
Romain Guy54f154a2017-10-24 21:40:32 +01005124 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005125 int32_t colorMode;
5126
Chia-I Wu0d711262018-05-21 15:19:35 -07005127 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005128 if (data.readInt32(&colorMode) == NO_ERROR) {
5129 mForceColorMode = static_cast<ColorMode>(colorMode);
5130 }
Romain Guy54f154a2017-10-24 21:40:32 +01005131 invalidateHwcGeometry();
5132 repaintEverything();
5133 return NO_ERROR;
5134 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005135 // Deprecate, use 1030 to check whether the device is color managed.
5136 case 1024: {
5137 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005138 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005139 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005140 n = data.readInt32();
5141 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005142 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005143 Mutex::Autolock lock(mStateLock);
5144 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005145 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005146 reply->writeInt32(NO_ERROR);
5147 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005148 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005149 bool writeFile = false;
5150 {
5151 Mutex::Autolock lock(mStateLock);
5152 mTracingEnabledChanged = true;
5153 writeFile = mTracing.disable();
5154 }
5155
5156 if (writeFile) {
5157 reply->writeInt32(mTracing.writeToFile());
5158 } else {
5159 reply->writeInt32(NO_ERROR);
5160 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005161 }
5162 return NO_ERROR;
5163 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005164 case 1026: { // Get layer tracing status
5165 reply->writeBool(mTracing.isEnabled());
5166 return NO_ERROR;
5167 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005168 // Is a DisplayColorSetting supported?
5169 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005170 const auto display = getDefaultDisplayDevice();
5171 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005172 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005173 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005174
5175 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5176 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005177 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005178 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005179 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005180 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005181 reply->writeBool(true);
5182 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005183 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005184 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005185 break;
5186 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005187 reply->writeBool(
5188 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005189 break;
5190 }
5191 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005192 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005193 // Is VrFlinger active?
5194 case 1028: {
5195 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005196 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005197 return NO_ERROR;
5198 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005199 // Set buffer size for SF tracing (value in KB)
5200 case 1029: {
5201 n = data.readInt32();
5202 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5203 ALOGW("Invalid buffer size: %d KB", n);
5204 reply->writeInt32(BAD_VALUE);
5205 return BAD_VALUE;
5206 }
5207
5208 ALOGD("Updating trace buffer to %d KB", n);
5209 mTracing.setBufferSize(n * 1024);
5210 reply->writeInt32(NO_ERROR);
5211 return NO_ERROR;
5212 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005213 // Is device color managed?
5214 case 1030: {
5215 reply->writeBool(useColorManagement);
5216 return NO_ERROR;
5217 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005218 // Override default composition data space
5219 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5220 // && adb shell stop zygote && adb shell start zygote
5221 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5222 // adb shell stop zygote && adb shell start zygote
5223 case 1031: {
5224 Mutex::Autolock _l(mStateLock);
5225 n = data.readInt32();
5226 if (n) {
5227 n = data.readInt32();
5228 if (n) {
5229 Dataspace dataspace = static_cast<Dataspace>(n);
5230 if (!validateCompositionDataspace(dataspace)) {
5231 return BAD_VALUE;
5232 }
5233 mDefaultCompositionDataspace = dataspace;
5234 }
5235 n = data.readInt32();
5236 if (n) {
5237 Dataspace dataspace = static_cast<Dataspace>(n);
5238 if (!validateCompositionDataspace(dataspace)) {
5239 return BAD_VALUE;
5240 }
5241 mWideColorGamutCompositionDataspace = dataspace;
5242 }
5243 } else {
5244 // restore composition data space.
5245 mDefaultCompositionDataspace = defaultCompositionDataspace;
5246 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5247 }
5248 return NO_ERROR;
5249 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005250 // Set trace flags
5251 case 1033: {
5252 n = data.readUint32();
5253 ALOGD("Updating trace flags to 0x%x", n);
5254 mTracing.setTraceFlags(n);
5255 reply->writeInt32(NO_ERROR);
5256 return NO_ERROR;
5257 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005258 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005259 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005260 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005261 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005262 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005263 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005264 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005265 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005266 } else {
5267 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005268 }
5269 return NO_ERROR;
5270 }
Ady Abraham34392f72019-04-10 11:29:27 -07005271 case 1035: {
5272 n = data.readInt32();
5273 mDebugDisplayConfigSetByBackdoor = false;
5274 if (n >= 0) {
5275 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005276 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005277 if (result != NO_ERROR) {
5278 return result;
5279 }
5280 mDebugDisplayConfigSetByBackdoor = true;
5281 }
5282 return NO_ERROR;
5283 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005284 }
5285 }
5286 return err;
5287}
5288
Steven Thomas6d8110b2017-08-31 18:24:21 -07005289void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005290 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005291 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005292}
5293
Ana Krulec7d1d6832018-12-27 11:10:09 -08005294void SurfaceFlinger::repaintEverythingForHWC() {
5295 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005296 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005297 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005298}
5299
Ady Abrahama09852a2020-02-20 14:23:42 -08005300void SurfaceFlinger::kernelTimerChanged(bool expired) {
5301 static bool updateOverlay =
5302 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5303 if (!updateOverlay || !mRefreshRateOverlay) return;
5304
5305 // Update the overlay on the main thread to avoid race conditions with
5306 // mRefreshRateConfigs->getCurrentRefreshRate()
5307 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5308 if (mRefreshRateOverlay) {
5309 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5310 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005311 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005312 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5313 if (mDesiredActiveConfigChanged) {
5314 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5315 mDesiredActiveConfig.configId);
5316 }
5317
5318 return mRefreshRateConfigs->getCurrentRefreshRate();
5319 }();
5320 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5321
5322 if (current != min) {
5323 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5324 mEventQueue->invalidate();
5325 }
5326 }
5327 }));
5328}
5329
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005330// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5331class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005332public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005333 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5334 ~WindowDisconnector() {
5335 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005336 }
5337
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005338private:
5339 ANativeWindow* mWindow;
5340 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005341};
5342
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005343status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005344 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005345 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5346 const Rect& sourceCrop, uint32_t reqWidth,
5347 uint32_t reqHeight, bool useIdentityTransform,
5348 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005349 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005350
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005351 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005352
Dominik Laskowski718f9602019-11-09 20:01:35 -08005353 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5354 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5355 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5356 renderAreaRotation = ui::Transform::ROT_0;
5357 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005358
Chia-I Wu20261cb2018-08-23 12:55:44 -07005359 sp<DisplayDevice> display;
5360 {
5361 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005362
Chia-I Wu20261cb2018-08-23 12:55:44 -07005363 display = getDisplayDeviceLocked(displayToken);
5364 if (!display) return BAD_VALUE;
5365
Chia-I Wucb023152018-08-28 12:57:23 -07005366 // set the requested width/height to the logical display viewport size
5367 // by default
5368 if (reqWidth == 0 || reqHeight == 0) {
5369 reqWidth = uint32_t(display->getViewport().width());
5370 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005371 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005372 }
5373
Peiyong Lin0e003c92018-09-17 11:09:51 -07005374 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005375 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005376 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5377 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005378 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005379 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005380}
5381
chaviw93df2ea2019-04-30 16:45:12 -07005382static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5383 switch (colorMode) {
5384 case ColorMode::DISPLAY_P3:
5385 case ColorMode::BT2100_PQ:
5386 case ColorMode::BT2100_HLG:
5387 case ColorMode::DISPLAY_BT2020:
5388 return Dataspace::DISPLAY_P3;
5389 default:
5390 return Dataspace::V0_SRGB;
5391 }
5392}
5393
Martin Liu4a322352020-03-24 21:30:38 +08005394status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5395 static constexpr int kFifoPriority = 2;
5396 static constexpr int kOtherPriority = 0;
5397
5398 struct sched_param param = {0};
5399 int sched_policy;
5400 if (enabled) {
5401 sched_policy = SCHED_FIFO;
5402 param.sched_priority = kFifoPriority;
5403 } else {
5404 sched_policy = SCHED_OTHER;
5405 param.sched_priority = kOtherPriority;
5406 }
5407
5408 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5409 return -errno;
5410 }
5411 return NO_ERROR;
5412}
5413
chaviw93df2ea2019-04-30 16:45:12 -07005414const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5415 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5416 if (displayToken) {
5417 return getDisplayDeviceLocked(displayToken);
5418 }
5419 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5420 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005421 return getDisplayByLayerStack(displayOrLayerStack);
5422}
5423
5424const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005425 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005426 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005427 return display;
5428 }
5429 }
5430 return nullptr;
5431}
5432
5433status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5434 sp<GraphicBuffer>* outBuffer) {
5435 sp<DisplayDevice> display;
5436 uint32_t width;
5437 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005438 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005439 {
5440 Mutex::Autolock _l(mStateLock);
5441 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5442 if (!display) {
5443 return BAD_VALUE;
5444 }
5445
5446 width = uint32_t(display->getViewport().width());
5447 height = uint32_t(display->getViewport().height());
5448
Dominik Laskowski718f9602019-11-09 20:01:35 -08005449 const auto orientation = display->getOrientation();
5450 captureOrientation = ui::Transform::toRotationFlags(orientation);
5451
5452 switch (captureOrientation) {
5453 case ui::Transform::ROT_90:
5454 captureOrientation = ui::Transform::ROT_270;
5455 break;
5456
5457 case ui::Transform::ROT_270:
5458 captureOrientation = ui::Transform::ROT_90;
5459 break;
5460
5461 case ui::Transform::ROT_INVALID:
5462 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5463 captureOrientation = ui::Transform::ROT_0;
5464 break;
5465
5466 default:
5467 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005468 }
chaviw93df2ea2019-04-30 16:45:12 -07005469 *outDataspace =
5470 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5471 }
5472
5473 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5474 false /* captureSecureLayers */);
5475
5476 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5477 std::placeholders::_1);
5478 bool ignored = false;
5479 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5480 false /* useIdentityTransform */,
5481 ignored /* outCapturedSecureLayers */);
5482}
5483
Robert Carr866455f2019-04-02 16:28:26 -07005484status_t SurfaceFlinger::captureLayers(
5485 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5486 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5487 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5488 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005489 ATRACE_CALL();
5490
5491 class LayerRenderArea : public RenderArea {
5492 public:
Robert Carr578038f2018-03-09 12:25:24 -08005493 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005494 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005495 bool childrenOnly, const Rect& displayViewport)
5496 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005497 mLayer(layer),
5498 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005499 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005500 mFlinger(flinger),
5501 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005502 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005503 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005504 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005505 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005506 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005507 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005508 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005509 }
chaviwa76b2712017-09-20 12:02:26 -07005510 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005511 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005512 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005513 Rect getSourceCrop() const override {
5514 if (mCrop.isEmpty()) {
5515 return getBounds();
5516 } else {
5517 return mCrop;
5518 }
5519 }
Robert Carr578038f2018-03-09 12:25:24 -08005520 class ReparentForDrawing {
5521 public:
5522 const sp<Layer>& oldParent;
5523 const sp<Layer>& newParent;
5524
Vishnu Nair4351ad52019-02-11 14:13:02 -08005525 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5526 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005527 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005528 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005529 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5530 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005531 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005532 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005533 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005534 };
5535
5536 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005537 const Rect sourceCrop = getSourceCrop();
5538 // no need to check rotation because there is none
5539 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5540 sourceCrop.height() != getReqHeight();
5541
Robert Carr578038f2018-03-09 12:25:24 -08005542 if (!mChildrenOnly) {
5543 mTransform = mLayer->getTransform().inverse();
5544 drawLayers();
5545 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005546 uint32_t w = static_cast<uint32_t>(getWidth());
5547 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005548 // In the "childrenOnly" case we reparent the children to a screenshot
5549 // layer which has no properties set and which does not draw.
5550 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005551 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5552 "Screenshot Parent"s, w, h, 0,
5553 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005554
Vishnu Nair4351ad52019-02-11 14:13:02 -08005555 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005556 drawLayers();
5557 }
5558 }
chaviwa76b2712017-09-20 12:02:26 -07005559
chaviwa76b2712017-09-20 12:02:26 -07005560 private:
chaviw7206d492017-11-10 16:16:12 -08005561 const sp<Layer> mLayer;
5562 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005563
Peiyong Linefefaac2018-08-17 12:27:51 -07005564 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005565 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005566
5567 SurfaceFlinger* mFlinger;
5568 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005569 };
5570
Robert Carrc0df3122019-04-11 13:18:21 -07005571 int reqWidth = 0;
5572 int reqHeight = 0;
5573 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005574 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005575 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005576 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005577 {
5578 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005579
Robert Carrc0df3122019-04-11 13:18:21 -07005580 parent = fromHandle(layerHandleBinder);
5581 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5582 ALOGE("captureLayers called with an invalid or removed parent");
5583 return NAME_NOT_FOUND;
5584 }
5585
5586 const int uid = IPCThreadState::self()->getCallingUid();
5587 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5588 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5589 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5590 return PERMISSION_DENIED;
5591 }
5592
Vishnu Nairefc42e22019-12-03 17:36:12 -08005593 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005594 if (sourceCrop.width() <= 0) {
5595 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005596 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005597 }
5598
5599 if (sourceCrop.height() <= 0) {
5600 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005601 crop.bottom = parentSourceBounds.getHeight();
5602 }
5603
5604 if (crop.isEmpty() || frameScale <= 0.0f) {
5605 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5606 // crop was not specified, or an invalid frame scale was provided.
5607 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005608 }
5609 reqWidth = crop.width() * frameScale;
5610 reqHeight = crop.height() * frameScale;
5611
5612 for (const auto& handle : excludeHandles) {
5613 sp<Layer> excludeLayer = fromHandle(handle);
5614 if (excludeLayer != nullptr) {
5615 excludeLayers.emplace(excludeLayer);
5616 } else {
5617 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5618 return NAME_NOT_FOUND;
5619 }
5620 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005621
5622 auto display = getDisplayByLayerStack(parent->getLayerStack());
5623 if (!display) {
5624 return BAD_VALUE;
5625 }
5626
5627 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005628 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005629
Chia-I Wu20261cb2018-08-23 12:55:44 -07005630 // really small crop or frameScale
5631 if (reqWidth <= 0) {
5632 reqWidth = 1;
5633 }
5634 if (reqHeight <= 0) {
5635 reqHeight = 1;
5636 }
5637
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005638 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5639 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005640 auto traverseLayers = [parent, childrenOnly,
5641 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005642 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5643 if (!layer->isVisible()) {
5644 return;
Robert Carr578038f2018-03-09 12:25:24 -08005645 } else if (childrenOnly && layer == parent.get()) {
5646 return;
chaviwa76b2712017-09-20 12:02:26 -07005647 }
Robert Carr866455f2019-04-02 16:28:26 -07005648
5649 sp<Layer> p = layer;
5650 while (p != nullptr) {
5651 if (excludeLayers.count(p) != 0) {
5652 return;
5653 }
5654 p = p->getParent();
5655 }
5656
chaviwa76b2712017-09-20 12:02:26 -07005657 visitor(layer);
5658 });
5659 };
Robert Carr108b2c72019-04-02 16:32:58 -07005660
5661 bool outCapturedSecureLayers = false;
5662 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5663 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005664}
5665
5666status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5667 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005668 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005669 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005670 bool useIdentityTransform,
5671 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005672 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005673
Peiyong Lin0e003c92018-09-17 11:09:51 -07005674 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005675 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5676 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005677 *outBuffer =
5678 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5679 static_cast<android_pixel_format>(reqPixelFormat), 1,
5680 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005681
Robert Carr108b2c72019-04-02 16:32:58 -07005682 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5683 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005684}
5685
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005686status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5687 TraverseLayersFunction traverseLayers,
5688 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005689 bool useIdentityTransform,
5690 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005691 // This mutex protects syncFd and captureResult for communication of the return values from the
5692 // main thread back to this Binder thread
5693 std::mutex captureMutex;
5694 std::condition_variable captureCondition;
5695 std::unique_lock<std::mutex> captureLock(captureMutex);
5696 int syncFd = -1;
5697 std::optional<status_t> captureResult;
5698
Robert Carr03480e22018-01-04 16:02:06 -08005699 const int uid = IPCThreadState::self()->getCallingUid();
5700 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5701
Dominik Laskowski8c001672018-05-30 16:52:06 -07005702 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005703 // If there is a refresh pending, bug out early and tell the binder thread to try again
5704 // after the refresh.
5705 if (mRefreshPending) {
5706 ATRACE_NAME("Skipping screenshot for now");
5707 std::unique_lock<std::mutex> captureLock(captureMutex);
5708 captureResult = std::make_optional<status_t>(EAGAIN);
5709 captureCondition.notify_one();
5710 return;
5711 }
5712
5713 status_t result = NO_ERROR;
5714 int fd = -1;
5715 {
5716 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005717 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005718 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005719 useIdentityTransform, forSystem, &fd,
5720 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005721 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005722 }
5723
5724 {
5725 std::unique_lock<std::mutex> captureLock(captureMutex);
5726 syncFd = fd;
5727 captureResult = std::make_optional<status_t>(result);
5728 captureCondition.notify_one();
5729 }
5730 });
5731
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005732 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005733 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005734 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005735 while (*captureResult == EAGAIN) {
5736 captureResult.reset();
5737 result = postMessageAsync(message);
5738 if (result != NO_ERROR) {
5739 return result;
5740 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005741 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005742 }
5743 result = *captureResult;
5744 }
5745
5746 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005747 sync_wait(syncFd, -1);
5748 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005749 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005750
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005751 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005752}
5753
chaviwa76b2712017-09-20 12:02:26 -07005754void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005755 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005756 const sp<GraphicBuffer>& buffer,
5757 bool useIdentityTransform, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005758 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005759
chaviwa76b2712017-09-20 12:02:26 -07005760 const auto reqWidth = renderArea.getReqWidth();
5761 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005762 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005763 const auto transform = renderArea.getTransform();
5764 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005765 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005766
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005767 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005768 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005769
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005770 // assume that bounds are never offset, and that they are the same as the
5771 // buffer bounds.
5772 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005773 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005774 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005775
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005776 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5777 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005778
chaviw50da5042018-04-09 13:49:37 -07005779 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005780
Vishnu Nair9b079a22020-01-21 14:36:08 -08005781 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005782 fillLayer.source.buffer.buffer = nullptr;
5783 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005784 fillLayer.geometry.boundaries =
5785 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005786 fillLayer.alpha = half(alpha);
5787 clientCompositionLayers.push_back(fillLayer);
5788
Yichi Chen40773d92020-04-01 10:10:18 +08005789 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005790 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005791 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005792 const bool supportProtectedContent = false;
5793 Region clip(renderArea.getBounds());
5794 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5795 clip,
5796 useIdentityTransform,
Alec Mouri5a6d8572020-03-23 23:56:15 -07005797 layer->needsFilteringForScreenshots(renderArea.getDisplayDevice(), transform) ||
5798 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005799 renderArea.isSecure(),
5800 supportProtectedContent,
5801 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005802 displayViewport,
5803 clientCompositionDisplay.outputDataspace,
5804 true, /* realContentIsVisible */
5805 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005806 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005807 std::vector<compositionengine::LayerFE::LayerSettings> results =
5808 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005809 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005810 for (auto& settings : results) {
5811 settings.geometry.positionTransform =
5812 transform.asMatrix4() * settings.geometry.positionTransform;
5813 }
Yichi Chen40773d92020-04-01 10:10:18 +08005814 clientCompositionLayers.insert(clientCompositionLayers.end(),
5815 std::make_move_iterator(results.begin()),
5816 std::make_move_iterator(results.end()));
5817 renderedLayers.push_back(layer);
5818 }
chaviwa76b2712017-09-20 12:02:26 -07005819 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005820
Yichi Chen40773d92020-04-01 10:10:18 +08005821 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5822 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005823 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005824 clientCompositionLayerPointers.begin(),
5825 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005826
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005827 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005828 // Use an empty fence for the buffer fence, since we just created the buffer so
5829 // there is no need for synchronization with the GPU.
5830 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005831 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005832 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005833 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005834 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005835
5836 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005837
5838 if (*outSyncFd >= 0) {
5839 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5840 for (auto* layer : renderedLayers) {
5841 layer->onLayerDisplayed(releaseFence);
5842 }
5843 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005844}
5845
chaviwa76b2712017-09-20 12:02:26 -07005846status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5847 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005848 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005849 bool useIdentityTransform, bool forSystem,
5850 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005851 ATRACE_CALL();
5852
chaviwa76b2712017-09-20 12:02:26 -07005853 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005854 outCapturedSecureLayers =
5855 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005856 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005857
Robert Carr03480e22018-01-04 16:02:06 -08005858 // We allow the system server to take screenshots of secure layers for
5859 // use in situations like the Screen-rotation animation and place
5860 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005861 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005862 ALOGW("FB is protected: PERMISSION_DENIED");
5863 return PERMISSION_DENIED;
5864 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005865 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005866 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005867}
5868
chaviw95ef3c42019-02-14 10:55:09 -08005869void SurfaceFlinger::setInputWindowsFinished() {
5870 Mutex::Autolock _l(mStateLock);
5871
5872 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005873
chaviw95ef3c42019-02-14 10:55:09 -08005874 mTransactionCV.broadcast();
5875}
chaviw5f21a5e2019-02-14 10:00:34 -08005876
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005877// ---------------------------------------------------------------------------
5878
Edgar Arriaga844fa672020-01-16 14:21:42 -08005879void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5880 layersSortedByZ.traverse(visitor);
5881}
5882
Dan Stoza412903f2017-04-27 13:42:17 -07005883void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5884 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005885}
5886
Dan Stoza412903f2017-04-27 13:42:17 -07005887void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5888 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005889}
5890
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005891void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005892 const LayerVector::Visitor& visitor) {
5893 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005894 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005895 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005896 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005897 continue;
5898 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005899 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005900 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005901 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005902 return;
5903 }
chaviwa76b2712017-09-20 12:02:26 -07005904 if (!layer->isVisible()) {
5905 return;
5906 }
5907 visitor(layer);
5908 });
5909 }
5910}
5911
Steven Thomasd4071902020-03-24 16:02:53 -07005912status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5913 const sp<DisplayDevice>& display,
5914 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005915 Mutex::Autolock lock(mStateLock);
5916
Steven Thomasd4071902020-03-24 16:02:53 -07005917 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5918 "Can only set override policy on the primary display");
5919 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5920
Dominik Laskowski22488f62019-03-28 09:53:04 -07005921 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005922 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5923 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5924 // it should go thru setDesiredActiveConfig, similar to primary display.
5925 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5926 const auto displayId = display->getId();
5927 LOG_ALWAYS_FATAL_IF(!displayId);
5928
5929 HWC2::VsyncPeriodChangeConstraints constraints;
5930 constraints.desiredTimeNanos = systemTime();
5931 constraints.seamlessRequired = false;
5932
5933 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005934 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5935 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005936 constraints, &timeline) < 0) {
5937 return BAD_VALUE;
5938 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005939 if (timeline.refreshRequired) {
5940 repaintEverythingForHWC();
5941 }
5942
Steven Thomasd4071902020-03-24 16:02:53 -07005943 display->setActiveConfig(policy->defaultConfig);
5944 const nsecs_t vsyncPeriod = getHwComposer()
5945 .getConfigs(*displayId)[policy->defaultConfig.value()]
5946 ->getVsyncPeriod();
5947 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5948 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005949 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005950 }
5951
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005952 if (mDebugDisplayConfigSetByBackdoor) {
5953 // ignore this request as config is overridden by backdoor
5954 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005955 }
5956
Steven Thomasd4071902020-03-24 16:02:53 -07005957 status_t setPolicyResult = overridePolicy
5958 ? mRefreshRateConfigs->setOverridePolicy(policy)
5959 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5960 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005961 return BAD_VALUE;
5962 }
Steven Thomasd4071902020-03-24 16:02:53 -07005963 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005964 return NO_ERROR;
5965 }
Steven Thomasd4071902020-03-24 16:02:53 -07005966 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005967
5968 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
Steven Thomasd4071902020-03-24 16:02:53 -07005969 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
5970 currentPolicy.maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005971
5972 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5973 // that listeners that care about a change in allowed configs can get the notification.
5974 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005975 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005976 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5977 .getVsyncPeriod();
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005978 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005979 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005980
Ana Krulec3f6a2062020-01-23 15:48:01 -08005981 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005982 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005983 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5984 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005985 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005986 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005987 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005988
Ady Abrahamabc27602020-04-08 17:20:29 -07005989 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5990 ALOGV("switching to Scheduler preferred config %d",
5991 preferredRefreshRate.getConfigId().value());
5992 setDesiredActiveConfig(
5993 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005994 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005995 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5996 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005997 }
5998
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005999 return NO_ERROR;
6000}
6001
Ana Krulec0782b882019-10-15 17:34:54 -07006002status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006003 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07006004 float maxRefreshRate) {
6005 ATRACE_CALL();
6006
6007 if (!displayToken) {
6008 return BAD_VALUE;
6009 }
6010
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006011 status_t result = NO_ERROR;
6012
Ana Krulec234bb162019-11-10 22:55:55 +01006013 postMessageSync(new LambdaMessage([&]() {
6014 const auto display = getDisplayDeviceLocked(displayToken);
6015 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006016 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01006017 ALOGE("Attempt to set desired display configs for invalid display token %p",
6018 displayToken.get());
6019 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006020 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01006021 ALOGW("Attempt to set desired display configs for virtual display");
6022 } else {
Steven Thomasd4071902020-03-24 16:02:53 -07006023 result = setDesiredDisplayConfigSpecsInternal(display,
6024 scheduler::RefreshRateConfigs::
6025 Policy{HwcConfigIndexType(
6026 defaultConfig),
6027 minRefreshRate,
6028 maxRefreshRate},
6029 /*overridePolicy=*/false);
Ana Krulec234bb162019-11-10 22:55:55 +01006030 }
6031 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006032
6033 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01006034}
6035
6036status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006037 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01006038 float* outMinRefreshRate,
6039 float* outMaxRefreshRate) {
6040 ATRACE_CALL();
6041
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006042 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01006043 return BAD_VALUE;
6044 }
6045
6046 Mutex::Autolock lock(mStateLock);
6047 const auto display = getDisplayDeviceLocked(displayToken);
6048 if (!display) {
6049 return NAME_NOT_FOUND;
6050 }
6051
6052 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006053 scheduler::RefreshRateConfigs::Policy policy =
6054 mRefreshRateConfigs->getDisplayManagerPolicy();
6055 *outDefaultConfig = policy.defaultConfig.value();
6056 *outMinRefreshRate = policy.minRefreshRate;
6057 *outMaxRefreshRate = policy.maxRefreshRate;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006058 return NO_ERROR;
6059 } else if (display->isVirtual()) {
6060 return BAD_VALUE;
6061 } else {
6062 const auto displayId = display->getId();
6063 if (!displayId) {
6064 return BAD_VALUE;
6065 }
6066 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6067 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6068 *outMinRefreshRate = 1e9f / vsyncPeriod;
6069 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6070 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006071 }
Ana Krulec0782b882019-10-15 17:34:54 -07006072}
6073
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006074void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006075 mFlinger->setInputWindowsFinished();
6076}
6077
Robert Carrc0df3122019-04-11 13:18:21 -07006078sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006079 BBinder* b = nullptr;
6080 if (handle) {
6081 b = handle->localBinder();
6082 }
Robert Carrc0df3122019-04-11 13:18:21 -07006083 if (b == nullptr) {
6084 return nullptr;
6085 }
6086 auto it = mLayersByLocalBinderToken.find(b);
6087 if (it != mLayersByLocalBinderToken.end()) {
6088 return it->second.promote();
6089 }
6090 return nullptr;
6091}
6092
Dominik Laskowski75848362019-11-11 17:57:20 -08006093void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006094 mNumLayers++;
6095 mScheduler->registerLayer(layer);
6096}
6097
6098void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6099 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006100 removeFromOffscreenLayers(layer);
6101}
6102
6103// WARNING: ONLY CALL THIS FROM LAYER DTOR
6104// Here we add children in the current state to offscreen layers and remove the
6105// layer itself from the offscreen layer list. Since
6106// this is the dtor, it is safe to access the current state. This keeps us
6107// from dangling children layers such that they are not reachable from the
6108// Drawing state nor the offscreen layer list
6109// See b/141111965
6110void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6111 for (auto& child : layer->getCurrentChildren()) {
6112 mOffscreenLayers.emplace(child.get());
6113 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006114 mOffscreenLayers.erase(layer);
6115}
6116
Alec Mouri4545a8a2019-08-08 20:05:32 -07006117void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6118 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6119}
6120
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006121status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6122 float lightPosY, float lightPosZ,
6123 float lightRadius) {
6124 Mutex::Autolock _l(mStateLock);
6125 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6126 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6127 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6128 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6129 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6130
6131 // these values are overridden when calculating the shadow settings for a layer.
6132 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6133 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006134 return NO_ERROR;
6135}
6136
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006137const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6138 const {
6139 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6140 // on the work to remove the table in that bug rather than adding more to
6141 // it.
6142 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6143 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6144 // supported, and exposed via the
6145 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6146 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6147 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6148 };
6149 return genericLayerMetadataKeyMap;
6150}
6151
Steven Thomas62a4cf82020-01-31 12:04:03 -08006152status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6153 int8_t compatibility) {
6154 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6155 return BAD_VALUE;
6156 }
6157
Ady Abraham60e42ea2020-03-09 19:17:31 -07006158 postMessageAsync(new LambdaMessage([=]() NO_THREAD_SAFETY_ANALYSIS {
6159 Mutex::Autolock lock(mStateLock);
6160 if (authenticateSurfaceTextureLocked(surface)) {
6161 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6162 if (layer->setFrameRate(
6163 Layer::FrameRate(frameRate,
6164 Layer::FrameRate::convertCompatibility(compatibility)))) {
6165 setTransactionFlags(eTraversalNeeded);
6166 }
6167 } else {
6168 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6169 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006170 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006171 return NO_ERROR;
6172 }));
6173
Steven Thomas62a4cf82020-01-31 12:04:03 -08006174 return NO_ERROR;
6175}
6176
Steven Thomasd4071902020-03-24 16:02:53 -07006177status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6178 if (!outToken) {
6179 return BAD_VALUE;
6180 }
6181 status_t result = NO_ERROR;
6182 postMessageSync(new LambdaMessage([&]() {
6183 if (mFrameRateFlexibilityTokenCount == 0) {
6184 // |mStateLock| not needed as we are on the main thread
6185 const auto display = getDefaultDisplayDeviceLocked();
6186
6187 // This is a little racy, but not in a way that hurts anything. As we grab the
6188 // defaultConfig from the display manager policy, we could be setting a new display
6189 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6190 // matter for the override policy though, since we set allowGroupSwitching to true, so
6191 // it's not a problem.
6192 scheduler::RefreshRateConfigs::Policy overridePolicy;
6193 overridePolicy.defaultConfig =
6194 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6195 overridePolicy.allowGroupSwitching = true;
6196 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy,
6197 /*overridePolicy=*/true);
6198 }
6199
6200 if (result == NO_ERROR) {
6201 mFrameRateFlexibilityTokenCount++;
6202 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6203 // below, is something to consider carefully. The lifetime of the
6204 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6205 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6206 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6207 // in this case, for two reasons:
6208 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6209 // the program exits is via a crash. So we won't have a situation where the
6210 // SurfaceFlinger object is dead but the process is still up.
6211 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6212 // if condition 1 were changed, the problem would only show up when running CTS tests,
6213 // not on end user devices, so we could spot it and fix it without serious impact.
6214 *outToken = new FrameRateFlexibilityToken(
6215 [this]() { onFrameRateFlexibilityTokenReleased(); });
6216 ALOGD("Frame rate flexibility token acquired. count=%d",
6217 mFrameRateFlexibilityTokenCount);
6218 }
6219 }));
6220 return result;
6221}
6222
6223void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
6224 postMessageAsync(new LambdaMessage([&]() {
6225 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6226 "Failed tracking frame rate flexibility tokens");
6227 mFrameRateFlexibilityTokenCount--;
6228 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6229 if (mFrameRateFlexibilityTokenCount == 0) {
6230 // |mStateLock| not needed as we are on the main thread
6231 const auto display = getDefaultDisplayDeviceLocked();
6232 status_t result =
6233 setDesiredDisplayConfigSpecsInternal(display, {}, /*overridePolicy=*/true);
6234 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6235 }
6236 }));
6237}
6238
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006239} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006240
Mathias Agopian3f844832013-08-07 21:24:32 -07006241#if defined(__gl_h_)
6242#error "don't include gl/gl.h in this file"
6243#endif
6244
6245#if defined(__gl2_h_)
6246#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006247#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006248
6249// TODO(b/129481165): remove the #pragma below and fix conversion issues
6250#pragma clang diagnostic pop // ignored "-Wconversion"