blob: 29fe5d9e6e155ebfee5feced8b360403622c375f [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri989ddbe2020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri989ddbe2020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Steven Thomasb02664d2017-07-26 18:48:28 -0700143namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700144
145#pragma clang diagnostic push
146#pragma clang diagnostic error "-Wswitch-enum"
147
148bool isWideColorMode(const ColorMode colorMode) {
149 switch (colorMode) {
150 case ColorMode::DISPLAY_P3:
151 case ColorMode::ADOBE_RGB:
152 case ColorMode::DCI_P3:
153 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700154 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700155 case ColorMode::BT2100_PQ:
156 case ColorMode::BT2100_HLG:
157 return true;
158 case ColorMode::NATIVE:
159 case ColorMode::STANDARD_BT601_625:
160 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
161 case ColorMode::STANDARD_BT601_525:
162 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
163 case ColorMode::STANDARD_BT709:
164 case ColorMode::SRGB:
165 return false;
166 }
167 return false;
168}
169
170#pragma clang diagnostic pop
171
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 Thomasb02664d2017-07-26 18:48:28 -0700203} // namespace anonymous
204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205// ---------------------------------------------------------------------------
206
Mathias Agopian99b49842011-06-27 16:05:52 -0700207const String16 sHardwareTest("android.permission.HARDWARE_TEST");
208const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
209const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
210const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800211const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700212
213// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700214int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700215bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800217bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800218bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800219int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100220uint32_t SurfaceFlinger::maxGraphicsWidth;
221uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600222bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800223ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700224bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700225bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700226Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
228Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
229ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800230bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700231
Kalle Raitaa099a242017-01-11 11:17:29 -0800232std::string getHwcServiceName() {
233 char value[PROPERTY_VALUE_MAX] = {};
234 property_get("debug.sf.hwc_service_name", value, "default");
235 ALOGI("Using HWComposer service: '%s'", value);
236 return std::string(value);
237}
238
239bool useTrebleTestingOverride() {
240 char value[PROPERTY_VALUE_MAX] = {};
241 property_get("debug.sf.treble_testing_override", value, "false");
242 ALOGI("Treble testing override: '%s'", value);
243 return std::string(value) == "true";
244}
245
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800246std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
247 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800248 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800250 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700251 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800252 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700253 return std::string("Enhanced");
254 default:
255 return std::string("Unknown ") +
256 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258}
259
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700260SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800261
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700262SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
263 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700265 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700266 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700267 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700268 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800269 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
270 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800271
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700272SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700280
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800282
Steven Thomas050b2c82017-03-06 11:45:16 -0800283 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800287
Brian Lindahla13f2d52020-03-05 11:54:17 +0100288 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
289 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 mDefaultCompositionDataspace =
296 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700297 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
298 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 defaultCompositionDataspace = mDefaultCompositionDataspace;
300 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
301 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
302 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
303 wideColorGamutCompositionPixelFormat =
304 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700305
Yichi Chenda901bf2019-06-28 14:58:27 +0800306 mColorSpaceAgnosticDataspace =
307 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800310
Dominik Laskowski718f9602019-11-09 20:01:35 -0800311 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
312 switch (primary_display_orientation(Values::ORIENTATION_0)) {
313 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800314 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800315 case Values::ORIENTATION_90:
316 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800317 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800318 case Values::ORIENTATION_180:
319 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800320 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800321 case Values::ORIENTATION_270:
322 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800323 break;
324 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800325 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800326
Sundong Ahn85131bd2019-02-18 15:51:53 +0900327 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800328
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800329 // debugging stuff...
330 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700331
Mathias Agopianb4b17302013-03-20 18:36:41 -0700332 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700333 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700334
Alec Mouri989ddbe2020-02-06 09:26:19 -0800335 property_get("ro.build.type", value, "user");
336 mIsUserBuild = strcmp(value, "user") == 0;
337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 property_get("debug.sf.showupdates", value, "0");
339 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700340
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700341 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000342
343 // DDMS debugging deprecated (b/120782499)
344 property_get("debug.sf.ddms", value, "0");
345 int debugDdms = atoi(value);
346 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700347
348 property_get("debug.sf.disable_backpressure", value, "0");
349 mPropagateBackpressure = !atoi(value);
350 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700351
Ady Abrahamadb9a992019-09-19 21:21:55 +0000352 property_get("debug.sf.enable_gl_backpressure", value, "0");
353 mPropagateBackpressureClientComposition = atoi(value);
354 ALOGI_IF(mPropagateBackpressureClientComposition,
355 "Enabling backpressure propagation for Client Composition");
356
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800357 property_get("debug.sf.enable_hwc_vds", value, "0");
358 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800359 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800360
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800361 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800362 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800363 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700364
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800365 property_get("ro.surface_flinger.supports_background_blur", value, "0");
366 bool supportsBlurs = atoi(value);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800367 property_get("debug.sf.disable_blurs", value, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800368 bool disableBlurs = atoi(value);
369 mEnableBlurs = supportsBlurs && !disableBlurs;
370 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
371 disableBlurs);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800372 property_get("ro.sf.blurs_are_expensive", value, "0");
373 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800374
Ady Abraham0a525092020-03-03 12:51:24 -0800375 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700376 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
377 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
378
Dan Stozaec460082018-12-17 15:35:09 -0800379 property_get("debug.sf.luma_sampling", value, "1");
380 mLumaSampling = atoi(value);
381
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800382 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800383 mDisableClientCompositionCache = atoi(value);
384
Romain Guy11d63f42017-07-20 12:47:14 -0700385 // We should be reading 'persist.sys.sf.color_saturation' here
386 // but since /data may be encrypted, we need to wait until after vold
387 // comes online to attempt to read the property. The property is
388 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800389
390 if (useTrebleTestingOverride()) {
391 // Without the override SurfaceFlinger cannot connect to HIDL
392 // services that are not listed in the manifests. Considered
393 // deriving the setting from the set service name, but it
394 // would be brittle if the name that's not 'default' is used
395 // for production purposes later on.
396 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
397 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800398
399 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800400}
401
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402void SurfaceFlinger::onFirstRef()
403{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800404 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405}
406
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700407SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408
Dan Stozac7014012014-02-14 15:03:43 -0800409void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410{
411 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700412 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413
Andy McFadden13a082e2012-08-24 10:16:42 -0700414 // restore initial conditions (default device unblank, etc)
415 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416
417 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700418 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800419}
420
Robert Carr1db73f62016-12-21 12:58:51 -0800421static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700422 status_t err = client->initCheck();
423 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800424 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425 }
Robert Carr1db73f62016-12-21 12:58:51 -0800426 return nullptr;
427}
428
429sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
430 return initClient(new Client(this));
431}
432
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700433sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
434 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700435{
436 class DisplayToken : public BBinder {
437 sp<SurfaceFlinger> flinger;
438 virtual ~DisplayToken() {
439 // no more references, this display must be terminated
440 Mutex::Autolock _l(flinger->mStateLock);
441 flinger->mCurrentState.displays.removeItem(this);
442 flinger->setTransactionFlags(eDisplayTransactionNeeded);
443 }
444 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700445 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700446 : flinger(flinger) {
447 }
448 };
449
450 sp<BBinder> token = new DisplayToken(this);
451
452 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700453 // Display ID is assigned when virtual display is allocated by HWC.
454 DisplayDeviceState state;
455 state.isSecure = secure;
456 state.displayName = displayName;
457 mCurrentState.displays.add(token, state);
458 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459 return token;
460}
461
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700462void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700463 Mutex::Autolock _l(mStateLock);
464
Dominik Laskowski075d3172018-05-24 15:50:06 -0700465 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
466 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700467 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700468 return;
469 }
470
Dominik Laskowski075d3172018-05-24 15:50:06 -0700471 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
472 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700473 ALOGE("destroyDisplay called for non-virtual display");
474 return;
475 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700476 mInterceptor->saveDisplayDeletion(state.sequenceId);
477 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700478 setTransactionFlags(eDisplayTransactionNeeded);
479}
480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
482 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700483
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800484 const auto internalDisplayId = getInternalDisplayIdLocked();
485 if (!internalDisplayId) {
486 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 }
488
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800489 std::vector<PhysicalDisplayId> displayIds;
490 displayIds.reserve(mPhysicalDisplayTokens.size());
491 displayIds.push_back(internalDisplayId->value);
492
493 for (const auto& [id, token] : mPhysicalDisplayTokens) {
494 if (id != *internalDisplayId) {
495 displayIds.push_back(id.value);
496 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800499 return displayIds;
500}
501
502sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
503 Mutex::Autolock lock(mStateLock);
504 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505}
506
Ady Abraham37965d42018-11-01 13:43:32 -0700507status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
508 if (!outGetColorManagement) {
509 return BAD_VALUE;
510 }
511 *outGetColorManagement = useColorManagement;
512 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700513}
514
Lloyd Pique441d5042018-10-18 16:49:51 -0700515HWComposer& SurfaceFlinger::getHwComposer() const {
516 return mCompositionEngine->getHwComposer();
517}
518
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700519renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
520 return mCompositionEngine->getRenderEngine();
521}
522
Lloyd Pique70d91362018-10-18 16:02:55 -0700523compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
524 return *mCompositionEngine.get();
525}
526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800527void SurfaceFlinger::bootFinished()
528{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700529 if (mBootFinished == true) {
530 ALOGE("Extra call to bootFinished");
531 return;
532 }
533 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700534 if (mStartPropertySetThread->join() != NO_ERROR) {
535 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800536 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800537 const nsecs_t now = systemTime();
538 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000539 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700540
Mikael Pessa90092f42019-08-26 17:22:04 -0700541 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000542 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700543
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700544 // wait patiently for the window manager death
545 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700546 mWindowManager = defaultServiceManager()->getService(name);
547 if (mWindowManager != 0) {
548 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549 }
Robert Carr720e5062018-07-30 17:45:14 -0700550 sp<IBinder> input(defaultServiceManager()->getService(
551 String16("inputflinger")));
552 if (input == nullptr) {
553 ALOGE("Failed to link to input service");
554 } else {
555 mInputFlinger = interface_cast<IInputFlinger>(input);
556 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557
Steven Thomas050b2c82017-03-06 11:45:16 -0800558 if (mVrFlinger) {
559 mVrFlinger->OnBootFinished();
560 }
561
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700563 // formerly we would just kill the process, but we now ask it to exit so it
564 // can choose where to stop the animation.
565 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700566
567 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
568 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
569 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700570
Ana Krulecbd6654b2019-02-15 15:18:15 -0800571 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800572 readPersistentProperties();
573 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800574
Ady Abraham8a82ba62020-01-17 12:43:17 -0800575 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
576 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
577 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
578 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800579 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800580}
581
Dan Stoza436ccf32018-06-21 12:10:12 -0700582uint32_t SurfaceFlinger::getNewTexture() {
583 {
584 std::lock_guard lock(mTexturePoolMutex);
585 if (!mTexturePool.empty()) {
586 uint32_t name = mTexturePool.back();
587 mTexturePool.pop_back();
588 ATRACE_INT("TexturePoolSize", mTexturePool.size());
589 return name;
590 }
591
592 // The pool was too small, so increase it for the future
593 ++mTexturePoolSize;
594 }
595
596 // The pool was empty, so we need to get a new texture name directly using a
597 // blocking call to the main thread
598 uint32_t name = 0;
599 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
600 return name;
601}
602
Mathias Agopian3f844832013-08-07 21:24:32 -0700603void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700604 std::lock_guard lock(mTexturePoolMutex);
605 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
606 // to actually delete this or not based on mTexturePoolSize
607 mTexturePool.push_back(texture);
608 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700609}
610
Wei Wangf9b05ee2017-07-19 20:59:39 -0700611// Do not call property_set on main thread which will be blocked by init
612// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700613void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700614 ALOGI( "SurfaceFlinger's main thread ready to run. "
615 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700616 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800617
Steven Thomasb02664d2017-07-26 18:48:28 -0700618 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700619 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800620 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700621 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
622 renderengine::RenderEngineCreationArgs::Builder()
623 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
624 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
625 .setUseColorManagerment(useColorManagement)
626 .setEnableProtectedContext(enable_protected_contents(false))
627 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800628 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700629 .setContextPriority(useContextPriority
630 ? renderengine::RenderEngine::ContextPriority::HIGH
631 : renderengine::RenderEngine::ContextPriority::MEDIUM)
632 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800633 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700634
635 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
636 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700637 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800638 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800639 // Process any initial hotplug and resulting display changes.
640 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700641 const auto display = getDefaultDisplayDeviceLocked();
642 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700643 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700644 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800645
Steven Thomas050b2c82017-03-06 11:45:16 -0800646 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700647 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700648 // This callback is called from the vr flinger dispatch thread. We
649 // need to call signalTransaction(), which requires holding
650 // mStateLock when we're not on the main thread. Acquiring
651 // mStateLock from the vr flinger dispatch thread might trigger a
652 // deadlock in surface flinger (see b/66916578), so post a message
653 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700654 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700655 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
656 mVrFlingerRequestsDisplay = requestDisplay;
657 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700658 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800659 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700660 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
661 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700662 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700663 .value_or(0),
664 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800665 if (!mVrFlinger) {
666 ALOGE("Failed to start vrflinger");
667 }
668 }
669
Mathias Agopian92a979a2012-08-02 18:32:23 -0700670 // initialize our drawing state
671 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700672
Andy McFadden13a082e2012-08-24 10:16:42 -0700673 // set initial conditions (e.g. unblank default device)
674 initializeDisplays();
675
Steven Thomas137d4bc2019-07-25 16:55:14 -0700676 char primeShaderCache[PROPERTY_VALUE_MAX];
677 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
678 if (atoi(primeShaderCache)) {
679 getRenderEngine().primeCache();
680 }
Dan Stoza4e637772016-07-28 13:31:51 -0700681
Wei Wangf9b05ee2017-07-19 20:59:39 -0700682 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700683
684 const bool presentFenceReliable =
685 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
686 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700687
688 if (mStartPropertySetThread->Start() != NO_ERROR) {
689 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800690 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800691
Dan Stoza9e56aa02015-11-02 13:00:03 -0800692 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700693}
694
Romain Guy11d63f42017-07-20 12:47:14 -0700695void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700696 Mutex::Autolock _l(mStateLock);
697
Romain Guy11d63f42017-07-20 12:47:14 -0700698 char value[PROPERTY_VALUE_MAX];
699
700 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800701 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700702 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800703 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100704
705 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700706 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800707
708 property_get("persist.sys.sf.color_mode", value, "0");
709 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700710}
711
Mathias Agopiana67e4182012-06-19 17:26:12 -0700712void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800713 // Start boot animation service by setting a property mailbox
714 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800716 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700717 if (mStartPropertySetThread->join() != NO_ERROR) {
718 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800719 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700720}
721
Mathias Agopian875d8e12013-06-07 15:35:48 -0700722size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700723 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700724}
725
Mathias Agopian875d8e12013-06-07 15:35:48 -0700726size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700727 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700728}
729
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800730// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800731
Jamie Gennis582270d2011-08-17 18:19:00 -0700732bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800733 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800734 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800735 return authenticateSurfaceTextureLocked(bufferProducer);
736}
737
738bool SurfaceFlinger::authenticateSurfaceTextureLocked(
739 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800740 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800741 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800742}
743
Brian Anderson6b376712017-04-04 10:51:39 -0700744status_t SurfaceFlinger::getSupportedFrameTimestamps(
745 std::vector<FrameEvent>* outSupported) const {
746 *outSupported = {
747 FrameEvent::REQUESTED_PRESENT,
748 FrameEvent::ACQUIRE,
749 FrameEvent::LATCH,
750 FrameEvent::FIRST_REFRESH_START,
751 FrameEvent::LAST_REFRESH_START,
752 FrameEvent::GPU_COMPOSITION_DONE,
753 FrameEvent::DEQUEUE_READY,
754 FrameEvent::RELEASE,
755 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700756 ConditionalLock _l(mStateLock,
757 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700758 if (!getHwComposer().hasCapability(
759 HWC2::Capability::PresentFenceIsNotReliable)) {
760 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
761 }
762 return NO_ERROR;
763}
764
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800765status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
766 if (!displayToken || !state) {
767 return BAD_VALUE;
768 }
769
770 Mutex::Autolock lock(mStateLock);
771
772 const auto display = getDisplayDeviceLocked(displayToken);
773 if (!display) {
774 return NAME_NOT_FOUND;
775 }
776
777 state->layerStack = display->getLayerStack();
778 state->orientation = display->getOrientation();
779
780 const Rect viewport = display->getViewport();
781 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
782
783 return NO_ERROR;
784}
785
786status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
787 if (!displayToken || !info) {
788 return BAD_VALUE;
789 }
790
791 Mutex::Autolock lock(mStateLock);
792
793 const auto display = getDisplayDeviceLocked(displayToken);
794 if (!display) {
795 return NAME_NOT_FOUND;
796 }
797
Dominik Laskowski55c85402020-01-21 16:25:47 -0800798 if (const auto connectionType = display->getConnectionType())
799 info->connectionType = *connectionType;
800 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800801 return INVALID_OPERATION;
802 }
803
804 if (mEmulatedDisplayDensity) {
805 info->density = mEmulatedDisplayDensity;
806 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800807 info->density = info->connectionType == DisplayConnectionType::Internal
808 ? mInternalDisplayDensity
809 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800810 }
811
812 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200813 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800814
815 return NO_ERROR;
816}
817
Dominik Laskowski22488f62019-03-28 09:53:04 -0700818status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800819 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700820 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700821 return BAD_VALUE;
822 }
823
Dominik Laskowski22488f62019-03-28 09:53:04 -0700824 Mutex::Autolock lock(mStateLock);
825
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800826 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700827 if (!displayId) {
828 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700829 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800831 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700832
Dan Stoza7f7da322014-05-02 15:26:25 -0700833 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700834
Dominik Laskowski075d3172018-05-24 15:50:06 -0700835 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800836 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700837
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800838 auto width = hwConfig->getWidth();
839 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700840
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800841 auto xDpi = hwConfig->getDpiX();
842 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700843
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800844 if (isInternal &&
845 (internalDisplayOrientation == ui::ROTATION_90 ||
846 internalDisplayOrientation == ui::ROTATION_270)) {
847 std::swap(width, height);
848 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 }
850
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800851 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800852
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800853 if (mEmulatedDisplayDensity) {
854 config.xDpi = mEmulatedDisplayDensity;
855 config.yDpi = mEmulatedDisplayDensity;
856 } else {
857 config.xDpi = xDpi;
858 config.yDpi = yDpi;
859 }
860
861 const nsecs_t period = hwConfig->getVsyncPeriod();
862 config.refreshRate = 1e9f / period;
863
864 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
865 config.appVsyncOffset = offsets.late.app;
866 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800867 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800868
Andy McFadden91b2ca82014-06-13 14:04:23 -0700869 // This is how far in advance a buffer must be queued for
870 // presentation at a given time. If you want a buffer to appear
871 // on the screen at time N, you must submit the buffer before
872 // (N - presentationDeadline).
873 //
874 // Normally it's one full refresh period (to give SF a chance to
875 // latch the buffer), but this can be reduced by configuring a
876 // DispSync offset. Any additional delays introduced by the hardware
877 // composer or panel must be accounted for here.
878 //
879 // We add an additional 1ms to allow for processing time and
880 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800881 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700882
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800883 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700884 }
885
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 return NO_ERROR;
887}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700888
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700889status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
890 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700891 return BAD_VALUE;
892 }
893
Ana Krulecc2870422019-01-29 19:00:58 -0800894 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700895 return NO_ERROR;
896}
897
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700898int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
899 const auto display = getDisplayDevice(displayToken);
900 if (!display) {
901 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800902 return BAD_VALUE;
903 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700904
Steven Thomasc9098452019-09-30 17:15:05 -0700905 if (display->isPrimary()) {
906 std::lock_guard<std::mutex> lock(mActiveConfigLock);
907 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800908 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700909 }
Steven Thomasc9098452019-09-30 17:15:05 -0700910 }
Ady Abraham2139f732019-11-13 18:56:40 -0800911
912 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700913}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700914
Ady Abraham03b02dd2019-03-21 15:40:11 -0700915void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800916 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800917 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abraham2139f732019-11-13 18:56:40 -0800918 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800919
Ady Abrahamb838aed2019-02-12 15:30:16 -0800920 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800921 if (mDesiredActiveConfigChanged) {
922 // If a config change is pending, just cache the latest request in
923 // mDesiredActiveConfig
924 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
925 mDesiredActiveConfig = info;
926 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
927 } else {
928 // Check is we are already at the desired config
929 const auto display = getDefaultDisplayDeviceLocked();
930 if (!display || display->getActiveConfig() == refreshRate.configId) {
931 return;
932 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800933
Ady Abraham59db0a32020-03-02 18:04:20 -0800934 // Initiate a config change.
935 mDesiredActiveConfigChanged = true;
936 mDesiredActiveConfig = info;
937
Ady Abrahamb838aed2019-02-12 15:30:16 -0800938 // This will trigger HWC refresh without resetting the idle timer.
939 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700940 // Start receiving vsync samples now, so that we can detect a period
941 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800942 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700943 // As we called to set period, we will call to onRefreshRateChangeCompleted once
944 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700945 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800946
Ady Abraham9e16a482019-12-03 17:19:41 -0800947 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
948 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800949 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700950
951 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800952 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700953 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800954}
955
956status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
957 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800958
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100959 if (!displayToken) {
960 return BAD_VALUE;
961 }
Ady Abraham838de062019-02-04 10:24:03 -0800962
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100963 status_t result = NO_ERROR;
964
965 postMessageSync(new LambdaMessage([&]() {
966 const auto display = getDisplayDeviceLocked(displayToken);
967 if (!display) {
968 ALOGE("Attempt to set allowed display configs for invalid display token %p",
969 displayToken.get());
970 result = BAD_VALUE;
971 } else if (display->isVirtual()) {
972 ALOGW("Attempt to set allowed display configs for virtual display");
973 result = BAD_VALUE;
974 } else {
975 HwcConfigIndexType config(mode);
976 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
977 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
978 refreshRate.fps);
979 }
980 }));
981
982 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983}
984
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985void SurfaceFlinger::setActiveConfigInternal() {
986 ATRACE_CALL();
987
Dominik Laskowski22488f62019-03-28 09:53:04 -0700988 const auto display = getDefaultDisplayDeviceLocked();
989 if (!display) {
990 return;
991 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800992
Dominik Laskowski22488f62019-03-28 09:53:04 -0700993 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800994 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700995 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800996 display->setActiveConfig(mUpcomingActiveConfig.configId);
997
Ady Abraham2e1dd892020-03-05 13:48:36 -0800998 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -0800999 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -08001000 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1001 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -08001002 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001003
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001004 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001005 const nsecs_t vsyncPeriod =
1006 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
1007 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -08001008 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001009 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001010 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001011}
1012
Ady Abraham53852a52019-05-28 18:07:44 -07001013void SurfaceFlinger::desiredActiveConfigChangeDone() {
1014 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1015 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1016 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001017
Ady Abraham2e1dd892020-03-05 13:48:36 -08001018 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001019 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001020 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001021 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1022 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001023}
1024
Dominik Laskowski22488f62019-03-28 09:53:04 -07001025bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001026 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001027 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001028 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001029 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001031 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001032 return true;
1033 }
1034
1035 // We received the present fence from the HWC, so we assume it successfully updated
1036 // the config, hence we update SF.
1037 mCheckPendingFence = false;
1038 setActiveConfigInternal();
1039 }
1040
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001041 // Store the local variable to release the lock.
1042 ActiveConfigInfo desiredActiveConfig;
1043 {
1044 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001045 if (!mDesiredActiveConfigChanged) {
1046 return false;
1047 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001048 desiredActiveConfig = mDesiredActiveConfig;
1049 }
1050
Ady Abraham2e1dd892020-03-05 13:48:36 -08001051 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001052 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1053 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1054 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001055 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001056 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1057 // display is not valid or we are already in the requested mode
1058 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001059 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001060 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001061 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001062
Ady Abraham838de062019-02-04 10:24:03 -08001063 // Desired active config was set, it is different than the config currently in use, however
1064 // allowed configs might have change by the time we process the refresh.
1065 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001066 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001067 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001068 return false;
1069 }
Alec Mouri7f015182019-07-11 13:56:22 -07001070
Ady Abrahamb838aed2019-02-12 15:30:16 -08001071 mUpcomingActiveConfig = desiredActiveConfig;
1072 const auto displayId = display->getId();
1073 LOG_ALWAYS_FATAL_IF(!displayId);
1074
Ady Abraham2139f732019-11-13 18:56:40 -08001075 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001076
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001077 // TODO(b/142753666) use constrains
1078 HWC2::VsyncPeriodChangeConstraints constraints;
1079 constraints.desiredTimeNanos = systemTime();
1080 constraints.seamlessRequired = false;
1081
1082 HWC2::VsyncPeriodChangeTimeline outTimeline;
1083 auto status =
1084 getHwComposer().setActiveConfigWithConstraints(*displayId,
1085 mUpcomingActiveConfig.configId.value(),
1086 constraints, &outTimeline);
1087 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001088 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1089 // to be sent. We just log the error in this case.
1090 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001091 return false;
1092 }
1093
1094 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1095 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001096 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001097 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001098}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001099
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001100status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1101 Vector<ColorMode>* outColorModes) {
1102 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001103 return BAD_VALUE;
1104 }
1105
Peiyong Lina52f0292018-03-14 17:26:31 -07001106 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001107 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001108 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001109 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1110
1111 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1112 if (!displayId) {
1113 return NAME_NOT_FOUND;
1114 }
1115
Dominik Laskowski075d3172018-05-24 15:50:06 -07001116 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001117 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001118 }
Michael Wright28f24d02016-07-12 13:30:53 -07001119 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001120
1121 // If it's built-in display and the configuration claims it's not wide color capable,
1122 // filter out all wide color modes. The typical reason why this happens is that the
1123 // hardware is not good enough to support GPU composition of wide color, and thus the
1124 // OEMs choose to disable this capability.
1125 if (isInternalDisplay && !hasWideColorDisplay) {
1126 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1127 isWideColorMode);
1128 } else {
1129 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1130 }
Michael Wright28f24d02016-07-12 13:30:53 -07001131
1132 return NO_ERROR;
1133}
1134
Daniel Solomon42d04562019-01-20 21:03:19 -08001135status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1136 ui::DisplayPrimaries &primaries) {
1137 if (!displayToken) {
1138 return BAD_VALUE;
1139 }
1140
1141 // Currently we only support this API for a single internal display.
1142 if (getInternalDisplayToken() != displayToken) {
1143 return BAD_VALUE;
1144 }
1145
1146 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1147 return NO_ERROR;
1148}
1149
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001150ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1151 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001152 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001153 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001154 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001155}
1156
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001157status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001158 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001159 Vector<ColorMode> modes;
1160 getDisplayColorModes(displayToken, &modes);
1161 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1162 if (mode < ColorMode::NATIVE || !exists) {
1163 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1164 decodeColorMode(mode).c_str(), mode, displayToken.get());
1165 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001166 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001167 const auto display = getDisplayDevice(displayToken);
1168 if (!display) {
1169 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1170 decodeColorMode(mode).c_str(), mode, displayToken.get());
1171 } else if (display->isVirtual()) {
1172 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1173 decodeColorMode(mode).c_str(), mode);
1174 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001175 display->getCompositionDisplay()->setColorProfile(
1176 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1177 RenderIntent::COLORIMETRIC,
1178 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001179 }
1180 }));
1181
Michael Wright28f24d02016-07-12 13:30:53 -07001182 return NO_ERROR;
1183}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001184
Galia Peycheva5492cb52019-10-30 14:13:16 +01001185status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1186 bool* outSupport) const {
1187 Mutex::Autolock _l(mStateLock);
1188
1189 if (!displayToken) {
1190 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1191 return BAD_VALUE;
1192 }
1193 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1194 if (!displayId) {
1195 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1196 displayToken.get());
1197 return NAME_NOT_FOUND;
1198 }
1199 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1200 HWC2::DisplayCapability::AutoLowLatencyMode);
1201 return NO_ERROR;
1202}
1203
1204void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1205 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1206}
1207
1208void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1209 if (!displayToken) {
1210 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1211 return;
1212 }
1213 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1214 if (!displayId) {
1215 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1216 displayToken.get());
1217 return;
1218 }
1219
1220 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1221}
1222
1223status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1224 bool* outSupport) const {
1225 Mutex::Autolock _l(mStateLock);
1226
1227 if (!displayToken) {
1228 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1229 return BAD_VALUE;
1230 }
1231 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1232 if (!displayId) {
1233 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1234 displayToken.get());
1235 return NAME_NOT_FOUND;
1236 }
1237
1238 std::vector<HWC2::ContentType> outSupportedContentTypes;
1239 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1240 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1241 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1242 return NO_ERROR;
1243}
1244
1245void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1246 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1247}
1248
1249void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1250 if (!displayToken) {
1251 ALOGE("setGameContentType() failed. Missing display token.");
1252 return;
1253 }
1254 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1255 if (!displayId) {
1256 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1257 displayToken.get());
1258 return;
1259 }
1260
1261 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1262 getHwComposer().setContentType(*displayId, type);
1263}
1264
Svetoslavd85084b2014-03-20 10:28:31 -07001265status_t SurfaceFlinger::clearAnimationFrameStats() {
1266 Mutex::Autolock _l(mStateLock);
1267 mAnimFrameTracker.clearStats();
1268 return NO_ERROR;
1269}
1270
1271status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1272 Mutex::Autolock _l(mStateLock);
1273 mAnimFrameTracker.getStats(outStats);
1274 return NO_ERROR;
1275}
1276
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001277status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1278 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001279 Mutex::Autolock _l(mStateLock);
1280
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001281 const auto display = getDisplayDeviceLocked(displayToken);
1282 if (!display) {
1283 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001284 return BAD_VALUE;
1285 }
1286
Peiyong Linfb069302018-04-25 14:34:31 -07001287 // At this point the DisplayDeivce should already be set up,
1288 // meaning the luminance information is already queried from
1289 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001290 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001291 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1292 capabilities.getDesiredMaxLuminance(),
1293 capabilities.getDesiredMaxAverageLuminance(),
1294 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001295
1296 return NO_ERROR;
1297}
1298
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001299std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1300 const DisplayDevice& display) const {
1301 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1302 // avoid repetitive HAL IPC and EDID parsing.
1303 const auto displayId = display.getId();
1304 LOG_FATAL_IF(!displayId);
1305
1306 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1307 LOG_FATAL_IF(!hwcDisplayId);
1308
1309 uint8_t port;
1310 DisplayIdentificationData data;
1311 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1312 ALOGV("%s: No identification data.", __FUNCTION__);
1313 return {};
1314 }
1315
1316 const auto info = parseDisplayIdentificationData(port, data);
1317 if (!info) {
1318 return {};
1319 }
1320 return info->deviceProductInfo;
1321}
1322
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001323status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1324 ui::PixelFormat* outFormat,
1325 ui::Dataspace* outDataspace,
1326 uint8_t* outComponentMask) const {
1327 if (!outFormat || !outDataspace || !outComponentMask) {
1328 return BAD_VALUE;
1329 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001330 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001331 if (!display || !display->getId()) {
1332 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1333 return BAD_VALUE;
1334 }
1335 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1336 outDataspace, outComponentMask);
1337}
1338
Kevin DuBois74e53772018-11-19 10:52:38 -08001339status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1340 bool enable, uint8_t componentMask,
1341 uint64_t maxFrames) const {
1342 const auto display = getDisplayDevice(displayToken);
1343 if (!display || !display->getId()) {
1344 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1345 return BAD_VALUE;
1346 }
1347
1348 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1349 componentMask, maxFrames);
1350}
1351
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001352status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1353 uint64_t maxFrames, uint64_t timestamp,
1354 DisplayedFrameStats* outStats) const {
1355 const auto display = getDisplayDevice(displayToken);
1356 if (!display || !display->getId()) {
1357 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1358 return BAD_VALUE;
1359 }
1360
1361 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1362 outStats);
1363}
1364
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001365status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1366 if (!outSupported) {
1367 return BAD_VALUE;
1368 }
1369 *outSupported = getRenderEngine().supportsProtectedContent();
1370 return NO_ERROR;
1371}
1372
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001373status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1374 bool* outIsWideColorDisplay) const {
1375 if (!displayToken || !outIsWideColorDisplay) {
1376 return BAD_VALUE;
1377 }
1378 Mutex::Autolock _l(mStateLock);
1379 const auto display = getDisplayDeviceLocked(displayToken);
1380 if (!display) {
1381 return BAD_VALUE;
1382 }
Peiyong Linff84a152019-05-17 18:36:19 -07001383
1384 // Use hasWideColorDisplay to override built-in display.
1385 const auto displayId = display->getId();
1386 if (displayId && displayId == getInternalDisplayIdLocked()) {
1387 *outIsWideColorDisplay = hasWideColorDisplay;
1388 return NO_ERROR;
1389 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001390 *outIsWideColorDisplay = display->hasWideColorGamut();
1391 return NO_ERROR;
1392}
1393
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001394status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001395 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001396 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001397
Dominik Laskowski6505f792019-09-18 11:10:05 -07001398 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1399 mEventQueue->setEventConnection(
1400 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001401 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001402 }));
1403
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001404 return NO_ERROR;
1405}
1406
1407status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001408 Mutex::Autolock lock(mStateLock);
1409 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001410}
1411
Lloyd Pique755e3192018-01-31 16:46:15 -08001412status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1413 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001414 // Try to acquire a lock for 1s, fail gracefully
1415 const status_t err = mStateLock.timedLock(s2ns(1));
1416 const bool locked = (err == NO_ERROR);
1417 if (!locked) {
1418 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1419 return TIMED_OUT;
1420 }
1421
1422 outLayers->clear();
1423 mCurrentState.traverseInZOrder([&](Layer* layer) {
1424 outLayers->push_back(layer->getLayerDebugInfo());
1425 });
1426
1427 mStateLock.unlock();
1428 return NO_ERROR;
1429}
1430
Peiyong Linc6780972018-10-28 15:24:08 -07001431status_t SurfaceFlinger::getCompositionPreference(
1432 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1433 Dataspace* outWideColorGamutDataspace,
1434 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001435 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001436 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001437 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001438 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001439 return NO_ERROR;
1440}
1441
Dan Stozaec460082018-12-17 15:35:09 -08001442status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1443 const sp<IBinder>& stopLayerHandle,
1444 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001445 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001446 return BAD_VALUE;
1447 }
1448 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001449 return NO_ERROR;
1450}
1451
Dan Stozaec460082018-12-17 15:35:09 -08001452status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001453 if (!listener) {
1454 return BAD_VALUE;
1455 }
Dan Stozaec460082018-12-17 15:35:09 -08001456 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001457 return NO_ERROR;
1458}
Dan Gittik57e63c52019-01-18 16:37:54 +00001459
1460status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1461 bool* outSupport) const {
1462 if (!displayToken || !outSupport) {
1463 return BAD_VALUE;
1464 }
1465 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1466 if (!displayId) {
1467 return NAME_NOT_FOUND;
1468 }
1469 *outSupport =
1470 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1471 return NO_ERROR;
1472}
1473
1474status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1475 float brightness) const {
1476 if (!displayToken) {
1477 return BAD_VALUE;
1478 }
1479 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1480 if (!displayId) {
1481 return NAME_NOT_FOUND;
1482 }
1483 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1484}
1485
Ady Abraham8532d012019-05-08 14:50:56 -07001486status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1487 PowerHint powerHint = static_cast<PowerHint>(hintId);
1488
1489 if (powerHint == PowerHint::INTERACTION) {
1490 mScheduler->notifyTouchEvent();
1491 }
1492
1493 return NO_ERROR;
1494}
1495
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001496// ----------------------------------------------------------------------------
1497
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001498sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001499 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001500 const auto& handle =
1501 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001502
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001503 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001504}
1505
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001506// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001507
1508void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001509 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001510}
1511
1512void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001513 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001514 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001515 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001516}
1517
1518void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001519 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001520 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001521 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001522}
1523
1524void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001525 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001526 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001527}
1528
1529status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001530 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001531 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001532}
1533
1534status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001535 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001536 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001537 if (res == NO_ERROR) {
1538 msg->wait();
1539 }
1540 return res;
1541}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001542
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001543void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001544 do {
1545 waitForEvent();
1546 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001547}
1548
Dominik Laskowski83b88212018-12-11 13:34:06 -08001549nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001550 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001551 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1552 return 0;
1553 }
1554
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001555 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001556}
1557
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001558void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001559 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001560 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001561 ATRACE_NAME("SF onVsync");
1562
Steven Thomas3cfac282017-02-06 12:29:30 -08001563 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001564 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001565 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001566 return;
1567 }
1568
Dominik Laskowski075d3172018-05-24 15:50:06 -07001569 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001570 return;
1571 }
1572
Dominik Laskowski075d3172018-05-24 15:50:06 -07001573 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001574 // For now, we don't do anything with external display vsyncs.
1575 return;
1576 }
1577
Alec Mourif8e689c2019-05-20 18:32:22 -07001578 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001579 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001580 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001581 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001582 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001583}
1584
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001585void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001586 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1587 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001588}
1589
Ady Abraham2139f732019-11-13 18:56:40 -08001590bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001591 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001592}
1593
Ady Abraham2139f732019-11-13 18:56:40 -08001594void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1595 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001596 const auto display = getDefaultDisplayDeviceLocked();
1597 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001598 return;
1599 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001600 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001601
Ana Krulec7d1d6832018-12-27 11:10:09 -08001602 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001603 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1604 ALOGV("Skipping config %d as it is not part of allowed configs",
1605 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001606 return;
1607 }
1608
Ady Abraham2139f732019-11-13 18:56:40 -08001609 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001610}
1611
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001612void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001613 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001614 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001615 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001616
Lloyd Piqueba04e622017-12-14 17:11:26 -08001617 // Ignore events that do not have the right sequenceId.
1618 if (sequenceId != getBE().mComposerSequenceId) {
1619 return;
1620 }
1621
Steven Thomasb02664d2017-07-26 18:48:28 -07001622 // Only lock if we're not on the main thread. This function is normally
1623 // called on a hwbinder thread, but for the primary display it's called on
1624 // the main thread with the state lock already held, so don't attempt to
1625 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001626 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001627
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001628 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001629
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001630 if (std::this_thread::get_id() == mMainThreadId) {
1631 // Process all pending hot plug events immediately if we are on the main thread.
1632 processDisplayHotplugEventsLocked();
1633 }
1634
Lloyd Piqueba04e622017-12-14 17:11:26 -08001635 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001636}
1637
Ady Abraham7159f572019-10-11 11:10:18 -07001638void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001639 int32_t sequenceId, hwc2_display_t /*display*/,
1640 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1641 Mutex::Autolock lock(mStateLock);
1642 if (sequenceId != getBE().mComposerSequenceId) {
1643 return;
1644 }
1645 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001646}
1647
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001648void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1649 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1650 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1651}
1652
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001653void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001654 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001655 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001656 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001657 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001658 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001659}
1660
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001661void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001662 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001663
1664 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1665 // display power state.
1666 postMessageAsync(new LambdaMessage(
1667 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1668}
1669
1670void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1671 ATRACE_CALL();
1672
Ady Abraham27c70212019-06-11 10:52:26 -07001673 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1674
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001675 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001676 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1677 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001678 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001679 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001680 }
Mathias Agopian86303202012-07-24 22:46:10 -07001681}
1682
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001683// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001684void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001685 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001686 // Clear the drawing state so that the logic inside of
1687 // handleTransactionLocked will fire. It will determine the delta between
1688 // mCurrentState and mDrawingState and re-apply all changes when we make the
1689 // transition.
1690 mDrawingState.displays.clear();
1691 mDisplays.clear();
1692}
1693
Steven Thomas050b2c82017-03-06 11:45:16 -08001694void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001695 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001696 if (!mVrFlinger)
1697 return;
1698 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001699 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001700 return;
1701 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001702
Lloyd Pique441d5042018-10-18 16:49:51 -07001703 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001704 ALOGE("Vr flinger is only supported for remote hardware composer"
1705 " service connections. Ignoring request to transition to vr"
1706 " flinger.");
1707 mVrFlingerRequestsDisplay = false;
1708 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001709 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001710
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001711 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001712
Steven Thomas0123ac62018-07-12 11:32:34 -07001713 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001714 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001715
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001716 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001717
1718 // Clear out all the output layers from the composition engine for all
1719 // displays before destroying the hardware composer interface. This ensures
1720 // any HWC layers are destroyed through that interface before it becomes
1721 // invalid.
1722 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001723 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001724 }
1725
Steven Thomas0123ac62018-07-12 11:32:34 -07001726 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1727 // called below. Clear the reference now so we don't accidentally use it
1728 // later.
1729 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001730
Steven Thomasb02664d2017-07-26 18:48:28 -07001731 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001732 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001733 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001734
Steven Thomasb02664d2017-07-26 18:48:28 -07001735 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001736 // Delete the current instance before creating the new one
1737 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1738 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1739 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001740 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001741
Lloyd Pique441d5042018-10-18 16:49:51 -07001742 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001743 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001744
1745 if (vrFlingerRequestsDisplay) {
1746 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001747 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001748
1749 mVisibleRegionsDirty = true;
1750 invalidateHwcGeometry();
1751
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001752 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001753 display = getDefaultDisplayDeviceLocked();
1754 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001755 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001756
Steven Thomasb02664d2017-07-26 18:48:28 -07001757 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001758 const nsecs_t vsyncPeriod = getVsyncPeriod();
1759 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001760
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001761 // The present fences returned from vr_hwc are not an accurate
1762 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001763 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001764
Steven Thomasb02664d2017-07-26 18:48:28 -07001765 // Use phase of 0 since phase is not known.
1766 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001767 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001768 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001769
Ana Krulecc2870422019-01-29 19:00:58 -08001770 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001771
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001772 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001773 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001774}
1775
Ady Abraham11579302019-09-19 12:35:58 -07001776bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1777 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001778 // We are storing the last 2 present fences. If sf's phase offset is to be
1779 // woken up before the actual vsync but targeting the next vsync, we need to check
1780 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001781 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1782 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001783
Ady Abraham11579302019-09-19 12:35:58 -07001784 if (fence == Fence::NO_FENCE) {
1785 return false;
1786 }
1787
1788 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1789 fence->wait(graceTimeMs);
1790 }
1791
1792 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001793}
1794
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001795void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001796 DisplayStatInfo stats;
1797 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001798 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001799 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001800 mExpectedPresentTime.store(
1801 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001802}
1803
Dominik Laskowski22488f62019-03-28 09:53:04 -07001804void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001805 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001806 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001807 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001808 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001809 // calculate the expected present time once and use the cached
1810 // value throughout this frame to make sure all layers are
1811 // seeing this same value.
1812 populateExpectedPresentTime();
1813
Ady Abraham11579302019-09-19 12:35:58 -07001814 // When Backpressure propagation is enabled we want to give a small grace period
1815 // for the present fence to fire instead of just giving up on this frame to handle cases
1816 // where present fence is just about to get signaled.
1817 const int graceTimeForPresentFenceMs =
1818 (mPropagateBackpressure &&
1819 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1820 ? 1
1821 : 0;
1822 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1823 previousFrameMissed(
1824 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001825 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1826 mHadDeviceComposition && frameMissed};
1827 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1828 mHadClientComposition && frameMissed};
1829
Alec Mouricc0fc602019-02-26 21:45:19 -08001830 if (frameMissed) {
1831 mFrameMissedCount++;
1832 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001833 if (mMissedFrameJankCount == 0) {
1834 mMissedFrameJankStart = systemTime();
1835 }
1836 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001837 }
1838
Alec Mouri40189b02019-03-05 15:07:54 -08001839 if (hwcFrameMissed) {
1840 mHwcFrameMissedCount++;
1841 }
1842
1843 if (gpuFrameMissed) {
1844 mGpuFrameMissedCount++;
1845 }
1846
Ady Abrahamadb9a992019-09-19 21:21:55 +00001847 if (frameMissed && mPropagateBackpressure) {
1848 if ((hwcFrameMissed && !gpuFrameMissed) ||
1849 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001850 signalLayerUpdate();
1851 break;
1852 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001853 }
Dan Stoza50182882016-07-08 12:02:20 -07001854
Alec Mouri989ddbe2020-02-06 09:26:19 -08001855 // Our jank window is always at least 100ms since we missed a
1856 // frame...
1857 static constexpr nsecs_t kMinJankyDuration =
1858 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1859 // ...but if it's larger than 1s then we missed the trace cutoff.
1860 static constexpr nsecs_t kMaxJankyDuration =
1861 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1862 // If we're in a user build then don't push any atoms
1863 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1864 const auto displayDevice = getDefaultDisplayDeviceLocked();
1865 // Only report jank when the display is on, as displays in DOZE
1866 // power mode may operate at a different frame rate than is
1867 // reported in their config, which causes noticeable (but less
1868 // severe) jank.
1869 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1870 const nsecs_t currentTime = systemTime();
1871 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1872 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1873 ATRACE_NAME("Jank detected");
1874 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1875 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1876 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1877 jankyDurationMillis, mMissedFrameJankCount);
1878 }
1879
1880 // We either reported a jank event or we missed the trace
1881 // window, so clear counters here.
1882 if (jankDuration > kMinJankyDuration) {
1883 mMissedFrameJankCount = 0;
1884 mMissedFrameJankStart = 0;
1885 }
1886 }
1887 }
1888
Steven Thomas050b2c82017-03-06 11:45:16 -08001889 // Now that we're going to make it to the handleMessageTransaction()
1890 // call below it's safe to call updateVrFlinger(), which will
1891 // potentially trigger a display handoff.
1892 updateVrFlinger();
1893
Dan Stoza6b9454d2014-11-07 16:00:59 -08001894 bool refreshNeeded = handleMessageTransaction();
1895 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001896
Ana Krulecc84d09b2019-11-02 23:10:29 +01001897 // Layers need to get updated (in the previous line) before we can use them for
1898 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001899 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1900 // and may eventually call to ~Layer() if it holds the last reference
1901 {
1902 Mutex::Autolock _l(mStateLock);
1903 mScheduler->chooseRefreshRateForContent();
1904 }
1905
Ana Krulecc84d09b2019-11-02 23:10:29 +01001906 if (performSetActiveConfig()) {
1907 break;
1908 }
1909
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001910 updateCursorAsync();
1911 updateInputFlinger();
1912
Dan Stoza58784442014-12-02 16:58:17 -08001913 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001914 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001915 // Signal a refresh if a transaction modified the window state,
1916 // a new buffer was latched, or if HWC has requested a full
1917 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001918 if (mFrameStartTime <= 0) {
1919 // We should only use the time of the first invalidate
1920 // message that signals a refresh as the beginning of the
1921 // frame. Otherwise the real frame time will be
1922 // underestimated.
1923 mFrameStartTime = frameStart;
1924 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001925 signalRefresh();
1926 }
1927 break;
1928 }
1929 case MessageQueue::REFRESH: {
1930 handleMessageRefresh();
1931 break;
1932 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001933 }
1934}
1935
Dan Stoza6b9454d2014-11-07 16:00:59 -08001936bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001937 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001938 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001939
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001940 bool flushedATransaction = flushTransactionQueues();
1941
1942 bool runHandleTransaction = transactionFlags &&
1943 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1944
1945 if (runHandleTransaction) {
1946 handleTransaction(eTransactionMask);
1947 } else {
1948 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001949 }
1950
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001951 if (transactionFlushNeeded()) {
1952 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001953 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001954
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001955 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001956}
1957
Mathias Agopian4fec8732012-06-29 14:12:52 -07001958void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001959 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001960
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001961 mRefreshPending = false;
1962
Lloyd Piqueab039b52019-02-13 14:22:42 -08001963 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001964 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001965 for (const auto& [_, display] : mDisplays) {
1966 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1967 }
1968 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001969 if (auto layerFE = layer->getCompositionEngineLayerFE())
1970 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001971 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001972 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1973 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001974 if (auto layerFE = layer->getCompositionEngineLayerFE())
1975 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001976 }
1977
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001978 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001979 refreshArgs.outputColorSetting = useColorManagement
1980 ? mDisplayColorSetting
1981 : compositionengine::OutputColorSetting::kUnmanaged;
1982 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1983 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001984
1985 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1986 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001987 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001988
1989 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1990 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1991 mDrawingState.colorMatrixChanged = false;
1992 }
1993
1994 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1995
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001996 if (mDebugRegion != 0) {
1997 refreshArgs.devOptFlashDirtyRegionsDelay =
1998 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1999 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002000
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002001 mGeometryInvalid = false;
2002
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002003 // Store the present time just before calling to the composition engine so we could notify
2004 // the scheduler.
2005 const auto presentTime = systemTime();
2006
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002007 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002008 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2009 // Reset the frame start time now that we've recorded this frame.
2010 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002011
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002012 mScheduler->onDisplayRefreshed(presentTime);
2013
David Sodmanfa9b2af2017-12-24 13:28:59 -08002014 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002015 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002016
Lloyd Pique66d68602019-02-13 14:23:31 -08002017 mHadClientComposition =
2018 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2019 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002020 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2021 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002022 });
2023 mHadDeviceComposition =
2024 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2025 auto& displayDevice = tokenDisplayPair.second;
2026 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2027 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002028 mReusedClientComposition =
2029 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2030 auto& displayDevice = tokenDisplayPair.second;
2031 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2032 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002033
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002034 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002035
David Sodman7e4ae112018-02-09 15:02:28 -08002036 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002037 if (mVisibleRegionsDirty) {
2038 mVisibleRegionsDirty = false;
2039 if (mTracingEnabled) {
2040 mTracing.notify("visibleRegionsDirty");
2041 }
2042 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002043
2044 if (mCompositionEngine->needsAnotherUpdate()) {
2045 signalLayerUpdate();
2046 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002047}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002048
David Sodmanfa9b2af2017-12-24 13:28:59 -08002049
2050bool SurfaceFlinger::handleMessageInvalidate() {
2051 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002052 bool refreshNeeded = handlePageFlip();
2053
Vishnu Nair4351ad52019-02-11 14:13:02 -08002054 if (mVisibleRegionsDirty) {
2055 computeLayerBounds();
2056 }
2057
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002058 for (auto& layer : mLayersPendingRefresh) {
2059 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002060 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002061 invalidateLayerStack(layer, visibleReg);
2062 }
2063 mLayersPendingRefresh.clear();
2064 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002065}
2066
Ana Krulece588e312018-09-18 12:32:24 -07002067void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2068 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002069 // Update queue of past composite+present times and determine the
2070 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002071 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002072 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002073 while (!getBE().mCompositePresentTimes.empty()) {
2074 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075 // Cached values should have been updated before calling this method,
2076 // which helps avoid duplicate syscalls.
2077 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2078 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2079 break;
2080 }
2081 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002082 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002083 }
2084
2085 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002086 while (getBE().mCompositePresentTimes.size() > 16) {
2087 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002088 }
2089
Ana Krulece588e312018-09-18 12:32:24 -07002090 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002091}
2092
Ana Krulece588e312018-09-18 12:32:24 -07002093void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2094 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002095 // Integer division and modulo round toward 0 not -inf, so we need to
2096 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002097 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2098 ? (stats.vsyncPeriod -
2099 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2100 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002101
Ady Abraham9e16a482019-12-03 17:19:41 -08002102 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002103 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002104 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002105 }
2106
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002107 // Snap the latency to a value that removes scheduling jitter from the
2108 // composition and present times, which often have >1ms of jitter.
2109 // Reducing jitter is important if an app attempts to extrapolate
2110 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002111 // Snapping also allows an app to precisely calculate
2112 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002113 nsecs_t bias = stats.vsyncPeriod / 2;
2114 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2115 nsecs_t snappedCompositeToPresentLatency =
2116 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002117
David Sodman99974d22017-11-28 12:04:33 -08002118 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002119 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2120 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002121 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002122}
2123
David Sodman2b406362017-12-15 13:33:47 -08002124void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002125{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002126 ATRACE_CALL();
2127 ALOGV("postComposition");
2128
Brian Andersonf6386862016-10-31 16:34:13 -07002129 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002130 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002131 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002132 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002133 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002134 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002135
David Sodman73beded2017-11-15 11:56:06 -08002136 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002137 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002138 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002139 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002140 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2141 ->getRenderSurface()
2142 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002143 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002144 } else {
2145 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2146 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002147
David Sodman73beded2017-11-15 11:56:06 -08002148 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002149 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2150 mPreviousPresentFences[0] = displayDevice
2151 ? getHwComposer().getPresentFence(*displayDevice->getId())
2152 : Fence::NO_FENCE;
2153 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002154 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002155
Ana Krulece588e312018-09-18 12:32:24 -07002156 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002157 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002158
Lloyd Piqueab039b52019-02-13 14:22:42 -08002159 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2160 // be sampled a little later than when we started doing work for this frame,
2161 // but that should be okay since updateCompositorTiming has snapping logic.
2162 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2163 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002164 CompositorTiming compositorTiming;
2165 {
David Sodman99974d22017-11-28 12:04:33 -08002166 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2167 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002168 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002169
Edgar Arriaga844fa672020-01-16 14:21:42 -08002170 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002171 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2172 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002173 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002174 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002175 }
Robert Carr2047fae2016-11-28 14:09:09 -08002176 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002177
Ady Abraham92fa2f42020-02-11 15:33:56 -08002178 if (displayDevice && displayDevice->isPrimary() &&
2179 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002180 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002181 }
2182
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002183 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002184 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2185 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002186 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002187 }
2188 }
2189
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002190 if (mAnimCompositionPending) {
2191 mAnimCompositionPending = false;
2192
Brian Anderson4e606e32017-03-16 15:34:57 -07002193 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002194 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002195 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002196 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002197 // The HWC doesn't support present fences, so use the refresh
2198 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002199 const nsecs_t presentTime =
2200 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002201 mAnimFrameTracker.setActualPresentTime(presentTime);
2202 }
2203 mAnimFrameTracker.advanceFrame();
2204 }
Dan Stozab90cf072015-03-05 11:05:59 -08002205
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002206 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002207 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002208 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002209 }
2210
Vishnu Nair9b079a22020-01-21 14:36:08 -08002211 if (mReusedClientComposition) {
2212 mTimeStats->incrementClientCompositionReusedFrames();
2213 }
2214
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002215 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002216
Alec Mouri717bcb62020-02-10 17:07:19 -08002217 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2218 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2219 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2220
Lloyd Pique32cbe282018-10-19 13:09:22 -07002221 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2222 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002223 return;
2224 }
2225
2226 nsecs_t currentTime = systemTime();
2227 if (mHasPoweredOff) {
2228 mHasPoweredOff = false;
2229 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002230 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002231 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002232 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2233 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002234 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002235 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002236 }
David Sodman4a36e932017-11-07 14:29:47 -08002237 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002238 }
David Sodman4a36e932017-11-07 14:29:47 -08002239 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002240
2241 {
2242 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002243 if (mTexturePool.size() < mTexturePoolSize) {
2244 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002245 const size_t offset = mTexturePool.size();
2246 mTexturePool.resize(mTexturePoolSize);
2247 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2248 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002249 } else if (mTexturePool.size() > mTexturePoolSize) {
2250 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2251 const size_t offset = mTexturePoolSize;
2252 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2253 mTexturePool.resize(mTexturePoolSize);
2254 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002255 }
2256 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002257
Ady Abrahambe0f9482019-04-24 15:41:53 -07002258 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002259 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002260
Kevin DuBois413287f2019-02-25 08:46:47 -08002261 if (mLumaSampling && mRegionSamplingThread) {
2262 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002263 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002264
2265 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2266 // side-effect of getTotalSize(), so we check that again here
2267 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002268 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002269 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2270 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002271}
2272
Vishnu Nair4351ad52019-02-11 14:13:02 -08002273void SurfaceFlinger::computeLayerBounds() {
2274 for (const auto& pair : mDisplays) {
2275 const auto& displayDevice = pair.second;
2276 const auto display = displayDevice->getCompositionDisplay();
2277 for (const auto& layer : mDrawingState.layersSortedByZ) {
2278 // only consider the layers on the given layer stack
2279 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002280 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002281 }
2282
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002283 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2284 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002285 }
2286 }
2287}
2288
David Sodmanfa9b2af2017-12-24 13:28:59 -08002289void SurfaceFlinger::postFrame()
2290{
2291 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002292 const auto display = getDefaultDisplayDeviceLocked();
2293 if (display && getHwComposer().isConnected(*display->getId())) {
2294 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002295 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2296 logFrameStats();
2297 }
2298 }
2299}
2300
Mathias Agopian87baae12012-07-31 12:38:26 -07002301void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002302{
Mathias Agopian841cde52012-03-01 15:44:37 -08002303 ATRACE_CALL();
2304
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002305 // here we keep a copy of the drawing state (that is the state that's
2306 // going to be overwritten by handleTransactionLocked()) outside of
2307 // mStateLock so that the side-effects of the State assignment
2308 // don't happen with mStateLock held (which can cause deadlocks).
2309 State drawingState(mDrawingState);
2310
Mathias Agopianca4d3602011-05-19 15:38:14 -07002311 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002312 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313
Mathias Agopianca4d3602011-05-19 15:38:14 -07002314 // Here we're guaranteed that some transaction flags are set
2315 // so we can call handleTransactionLocked() unconditionally.
2316 // We call getTransactionFlags(), which will also clear the flags,
2317 // with mStateLock held to guarantee that mCurrentState won't change
2318 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002319
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002320 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002321 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002322 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002323
Mathias Agopianca4d3602011-05-19 15:38:14 -07002324 mDebugInTransaction = 0;
2325 invalidateHwcGeometry();
2326 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002327}
2328
Lloyd Piqueba04e622017-12-14 17:11:26 -08002329void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2330 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002331 const std::optional<DisplayIdentificationInfo> info =
2332 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002333
Dominik Laskowski075d3172018-05-24 15:50:06 -07002334 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002335 continue;
2336 }
2337
Dominik Laskowski55c85402020-01-21 16:25:47 -08002338 const DisplayId displayId = info->id;
2339 const auto it = mPhysicalDisplayTokens.find(displayId);
2340
Lloyd Piqueba04e622017-12-14 17:11:26 -08002341 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002342 if (it == mPhysicalDisplayTokens.end()) {
2343 ALOGV("Creating display %s", to_string(displayId).c_str());
2344
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002345 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002346 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002347 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002348
Dominik Laskowski075d3172018-05-24 15:50:06 -07002349 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002350 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002351 state.isSecure = true; // All physical displays are currently considered secure.
2352 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002353
2354 sp<IBinder> token = new BBinder();
2355 mCurrentState.displays.add(token, state);
2356 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2357
Dominik Laskowski075d3172018-05-24 15:50:06 -07002358 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002359 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002360 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002361 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002362
Dominik Laskowski55c85402020-01-21 16:25:47 -08002363 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002364 if (index >= 0) {
2365 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2366 mInterceptor->saveDisplayDeletion(state.sequenceId);
2367 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002368 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002369 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002370 }
2371
2372 processDisplayChangesLocked();
2373 }
2374
2375 mPendingHotplugEvents.clear();
2376}
2377
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002378void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002379 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2380 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002381}
2382
Lloyd Pique99d3da52018-01-22 17:48:03 -08002383sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002384 const wp<IBinder>& displayToken,
2385 std::shared_ptr<compositionengine::Display> compositionDisplay,
Lloyd Pique542307f2018-10-19 13:24:08 -07002386 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002387 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002388 auto displayId = compositionDisplay->getDisplayId();
2389 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002390 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002391 creationArgs.isSecure = state.isSecure;
2392 creationArgs.displaySurface = dispSurface;
2393 creationArgs.hasWideColorGamut = false;
2394 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002395
Dominik Laskowski55c85402020-01-21 16:25:47 -08002396 if (const auto& physical = state.physical) {
2397 creationArgs.connectionType = physical->type;
2398 }
2399
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002400 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002401 creationArgs.isPrimary = isInternalDisplay;
2402
2403 if (useColorManagement && displayId) {
2404 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002405 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002406 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002407 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002408 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002409
Dominik Laskowski7e045462018-05-30 13:02:02 -07002410 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002411 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002412 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002413 }
tangrobin6753a022018-08-10 10:58:54 +08002414 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415
Dominik Laskowski075d3172018-05-24 15:50:06 -07002416 if (displayId) {
2417 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002418 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002419 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002420 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002421
Lloyd Pique90c115d2018-09-18 21:39:42 -07002422 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002423 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002424 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002425
Lloyd Pique99d3da52018-01-22 17:48:03 -08002426 // Make sure that composition can never be stalled by a virtual display
2427 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002428 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002429 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002430 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2431 }
2432
Dominik Laskowski718f9602019-11-09 20:01:35 -08002433 creationArgs.physicalOrientation =
2434 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002435
Lloyd Pique99d3da52018-01-22 17:48:03 -08002436 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002437 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002438
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002439 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002440
2441 if (maxFrameBufferAcquiredBuffers >= 3) {
2442 nativeWindowSurface->preallocateBuffers();
2443 }
2444
2445 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002446 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002447 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002448 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002449 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002450 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002451 display->getCompositionDisplay()->setColorProfile(
2452 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2453 RenderIntent::COLORIMETRIC,
2454 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002455 if (!state.isVirtual()) {
2456 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002457 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2458 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002459 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002460
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002461 display->setLayerStack(state.layerStack);
2462 display->setProjection(state.orientation, state.viewport, state.frame);
2463 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002464
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002465 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002466}
2467
Lloyd Pique347200f2017-12-14 17:00:15 -08002468void SurfaceFlinger::processDisplayChangesLocked() {
2469 // here we take advantage of Vector's copy-on-write semantics to
2470 // improve performance by skipping the transaction entirely when
2471 // know that the lists are identical
2472 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2473 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2474 if (!curr.isIdenticalTo(draw)) {
2475 mVisibleRegionsDirty = true;
2476 const size_t cc = curr.size();
2477 size_t dc = draw.size();
2478
2479 // find the displays that were removed
2480 // (ie: in drawing state but not in current state)
2481 // also handle displays that changed
2482 // (ie: displays that are in both lists)
2483 for (size_t i = 0; i < dc;) {
2484 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2485 if (j < 0) {
2486 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002487 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002488 // Save display ID before disconnecting.
2489 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002490 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002491
2492 if (!display->isVirtual()) {
2493 LOG_ALWAYS_FATAL_IF(!displayId);
2494 dispatchDisplayHotplugEvent(displayId->value, false);
2495 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002496 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002497
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002498 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002499 } else {
2500 // this display is in both lists. see if something changed.
2501 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002502 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002503 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2504 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2505 if (state_binder != draw_binder) {
2506 // changing the surface is like destroying and
2507 // recreating the DisplayDevice, so we just remove it
2508 // from the drawing state, so that it get re-added
2509 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002510 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002511 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002512 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002513 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002514 mDrawingState.displays.removeItemsAt(i);
2515 dc--;
2516 // at this point we must loop to the next item
2517 continue;
2518 }
2519
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002520 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002521 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002522 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002523 }
2524 if ((state.orientation != draw[i].orientation) ||
2525 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002526 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002527 }
2528 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002529 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002530 if (display->isPrimary()) {
2531 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2532 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002533 }
2534 }
2535 }
2536 ++i;
2537 }
2538
2539 // find displays that were added
2540 // (ie: in current state but not in drawing state)
2541 for (size_t i = 0; i < cc; i++) {
2542 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2543 const DisplayDeviceState& state(curr[i]);
2544
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002545 int width = 0;
2546 int height = 0;
2547 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2548 if (state.physical) {
2549 const auto& activeConfig =
2550 getCompositionEngine().getHwComposer().getActiveConfig(
2551 state.physical->id);
2552 width = activeConfig->getWidth();
2553 height = activeConfig->getHeight();
2554 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2555 } else if (state.surface != nullptr) {
2556 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2557 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2558 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2559 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2560 int intPixelFormat;
2561 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2562 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2563 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2564 } else {
2565 // Virtual displays without a surface are dormant:
2566 // they have external state (layer stack, projection,
2567 // etc.) but no internal state (i.e. a DisplayDevice).
2568 continue;
2569 }
2570
2571 compositionengine::DisplayCreationArgsBuilder builder;
2572 if (const auto& physical = state.physical) {
2573 builder.setPhysical({physical->id, physical->type});
2574 }
2575 builder.setPixels(ui::Size(width, height));
2576 builder.setPixelFormat(pixelFormat);
2577 builder.setIsSecure(state.isSecure);
2578 builder.setLayerStackId(state.layerStack);
2579 builder.setPowerAdvisor(&mPowerAdvisor);
2580 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays ||
2581 getHwComposer().isUsingVrComposer());
2582 builder.setName(state.displayName);
2583 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2584
Lloyd Pique542307f2018-10-19 13:24:08 -07002585 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002586 sp<IGraphicBufferProducer> producer;
2587 sp<IGraphicBufferProducer> bqProducer;
2588 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002589 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002590
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002591 std::optional<DisplayId> displayId = compositionDisplay->getId();
2592
Dominik Laskowski663bd282018-04-19 15:26:54 -07002593 if (state.isVirtual()) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002594 sp<VirtualDisplaySurface> vds =
2595 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
2596 bqProducer, bqConsumer, state.displayName);
Lloyd Pique347200f2017-12-14 17:00:15 -08002597
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002598 dispSurface = vds;
2599 producer = vds;
Lloyd Pique347200f2017-12-14 17:00:15 -08002600 } else {
2601 ALOGE_IF(state.surface != nullptr,
2602 "adding a supported display, but rendering "
2603 "surface is provided (%p), ignoring it",
2604 state.surface.get());
2605
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002606 LOG_ALWAYS_FATAL_IF(!displayId);
Brian Lindahla13f2d52020-03-05 11:54:17 +01002607 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2608 maxGraphicsWidth, maxGraphicsHeight);
Lloyd Pique347200f2017-12-14 17:00:15 -08002609 producer = bqProducer;
2610 }
2611
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002612 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002613 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002614 mDisplays.emplace(displayToken,
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002615 setupNewDisplayDeviceInternal(displayToken,
2616 compositionDisplay, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002617 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002618 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002619 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002620 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002621 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002622
2623 const auto displayDevice = mDisplays[displayToken];
2624 if (displayDevice->isPrimary()) {
2625 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2626 displayDevice->getHeight());
2627 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002628 }
2629 }
2630 }
2631 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002632
2633 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002634}
2635
Mathias Agopian87baae12012-07-31 12:38:26 -07002636void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002637{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002638 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2639
Dan Stoza7dde5992015-05-22 09:51:44 -07002640 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002641 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002642 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002643 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002644
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 /*
2646 * Traversal of the children
2647 * (perform the transaction for each of them if needed)
2648 */
2649
Marissa Wall06255332019-03-27 13:48:27 -07002650 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002651 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002653 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654
2655 const uint32_t flags = layer->doTransaction(0);
2656 if (flags & Layer::eVisibleRegion)
2657 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002658
2659 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002660 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002661 }
Robert Carr2047fae2016-11-28 14:09:09 -08002662 });
Marissa Wall06255332019-03-27 13:48:27 -07002663 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664 }
2665
2666 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002667 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668 */
2669
Mathias Agopiane57f2922012-08-09 16:29:12 -07002670 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002671 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002672 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002673 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002675 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002676 // The transform hint might have changed for some layers
2677 // (either because a display has changed, or because a layer
2678 // as changed).
2679 //
2680 // Walk through all the layers in currentLayers,
2681 // and update their transform hint.
2682 //
2683 // If a layer is visible only on a single display, then that
2684 // display is used to calculate the hint, otherwise we use the
2685 // default display.
2686 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002687 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002688 // the hint is set before we acquire a buffer from the surface texture.
2689 //
2690 // NOTE: layer transactions have taken place already, so we use their
2691 // drawing state. However, SurfaceFlinger's own transaction has not
2692 // happened yet, so we must use the current state layer list
2693 // (soon to become the drawing state list).
2694 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002695 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002696 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002697 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002698 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002699 // NOTE: we rely on the fact that layers are sorted by
2700 // layerStack first (so we don't have to traverse the list
2701 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002702 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002703 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002704 currentlayerStack = layerStack;
2705 // figure out if this layerstack is mirrored
2706 // (more than one display) if so, pick the default display,
2707 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002708 hintDisplay = nullptr;
2709 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002710 if (display->getCompositionDisplay()
2711 ->belongsInOutput(layer->getLayerStack(),
2712 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002713 if (hintDisplay) {
2714 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002715 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002716 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002717 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002718 }
2719 }
2720 }
2721 }
Chet Haase91d25932013-04-11 15:24:55 -07002722
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002723 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002724 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2725 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002726
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002727 // could be null when this layer is using a layerStack
2728 // that is not visible on any display. Also can occur at
2729 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002730 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002731 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002732
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002733 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002734 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002735 if (hintDisplay) {
2736 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002737 }
Robert Carr2047fae2016-11-28 14:09:09 -08002738
2739 first = false;
2740 });
Mathias Agopian84300952012-11-21 16:02:13 -08002741 }
2742
2743
Mathias Agopian3559b072012-08-15 13:46:03 -07002744 /*
2745 * Perform our own transaction if needed
2746 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002747
2748 if (mLayersAdded) {
2749 mLayersAdded = false;
2750 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002751 mVisibleRegionsDirty = true;
2752 }
2753
2754 // some layers might have been removed, so
2755 // we need to update the regions they're exposing.
2756 if (mLayersRemoved) {
2757 mLayersRemoved = false;
2758 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002759 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002760 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002761 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002762 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002763 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002764 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002765 }
Robert Carr2047fae2016-11-28 14:09:09 -08002766 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767 }
2768
Vishnu Nairec0ab382019-02-13 15:32:56 -08002769 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002771}
2772
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002773void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002774 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002775 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002776 return;
2777 }
2778
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002779 if (mVisibleRegionsDirty || mInputInfoChanged) {
2780 mInputInfoChanged = false;
2781 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002782 } else if (mInputWindowCommands.syncInputWindows) {
2783 // If the caller requested to sync input windows, but there are no
2784 // changes to input windows, notify immediately.
2785 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002786 }
2787
Arthur Hung6cbb9752019-09-05 16:38:18 +08002788 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002789}
2790
2791void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002792 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002793
Robert Carra1257842020-01-31 13:48:28 -08002794 // We use a simple caching algorithm here. mInputDirty begins as true,
2795 // after we call setInputWindows we set it to false, so
2796 // in the future we wont call it again.. We set input dirty to true again
2797 // when any layer that hasInput() has a transaction performed on it
2798 // or when any parent or relative parent of such a layer has a transaction
2799 // performed on it. Not all of these transactions will really result in
2800 // input changes but all input changes will spring from these transactions
2801 // so the cache is safe but not optimal. It seems like it might be annoyingly
2802 // costly to cache and comapre the actual InputWindowHandle vector though.
2803 if (!mInputDirty) {
2804 return;
2805 }
2806
Robert Carr720e5062018-07-30 17:45:14 -07002807 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2808 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002809 // When calculating the screen bounds we ignore the transparent region since it may
2810 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002811 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002812 }
2813 });
chaviw291d88a2019-02-14 10:33:58 -08002814
2815 mInputFlinger->setInputWindows(inputHandles,
2816 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2817 : nullptr);
Robert Carra1257842020-01-31 13:48:28 -08002818
2819 mInputDirty = false;
Robert Carr720e5062018-07-30 17:45:14 -07002820}
2821
Vishnu Nairec0ab382019-02-13 15:32:56 -08002822void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002823 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002824 mPendingInputWindowCommands.clear();
2825}
2826
Riley Andrews03414a12014-07-01 14:22:59 -07002827void SurfaceFlinger::updateCursorAsync()
2828{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002829 compositionengine::CompositionRefreshArgs refreshArgs;
2830 for (const auto& [_, display] : mDisplays) {
2831 if (display->getId()) {
2832 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002833 }
2834 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002835
2836 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002837}
2838
Ady Abraham2139f732019-11-13 18:56:40 -08002839void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002840 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2841 // If this is called from the main thread mStateLock must be locked before
2842 // Currently the only way to call this function from the main thread is from
2843 // Sheduler::chooseRefreshRateForContent
2844
2845 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002846 changeRefreshRateLocked(refreshRate, event);
2847}
2848
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002849void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2850 if (mScheduler) {
2851 // In practice it's not allowed to hotplug in/out the primary display once it's been
2852 // connected during startup, but some tests do it, so just warn and return.
2853 ALOGW("Can't re-init scheduler");
2854 return;
2855 }
2856
Ady Abraham2139f732019-11-13 18:56:40 -08002857 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002858 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002859 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002860 primaryDisplayId),
2861 currentConfig);
2862 mRefreshRateStats =
2863 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2864 currentConfig, HWC_POWER_MODE_OFF);
2865 mRefreshRateStats->setConfigMode(currentConfig);
2866
Ady Abraham9e16a482019-12-03 17:19:41 -08002867 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2868
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002869 // start the EventThread
2870 mScheduler =
2871 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002872 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002873 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002874 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002875 impl::EventThread::InterceptVSyncsCallback());
2876 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002877 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002878 [this](nsecs_t timestamp) {
2879 mInterceptor->saveVSyncEvent(timestamp);
2880 });
2881
2882 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2883 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002884 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002885
2886 mRegionSamplingThread =
2887 new RegionSamplingThread(*this, *mScheduler,
2888 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002889 // Dispatch a config change request for the primary display on scheduler
2890 // initialization, so that the EventThreads always contain a reference to a
2891 // prior configuration.
2892 //
2893 // This is a bit hacky, but this avoids a back-pointer into the main SF
2894 // classes from EventThread, and there should be no run-time binder cost
2895 // anyway since there are no connected apps at this point.
2896 const nsecs_t vsyncPeriod =
2897 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2898 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2899 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002900}
2901
Mathias Agopian4fec8732012-06-29 14:12:52 -07002902void SurfaceFlinger::commitTransaction()
2903{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002904 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002905
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002906 mTransactionPending = false;
2907 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002908 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002909}
2910
Lloyd Pique58e24a32019-08-01 15:50:14 -07002911void SurfaceFlinger::commitTransactionLocked() {
2912 if (!mLayersPendingRemoval.isEmpty()) {
2913 // Notify removed layers now that they can't be drawn from
2914 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002915 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002916
2917 // Ensure any buffers set to display on any children are released.
2918 if (l->isRemovedFromCurrentState()) {
2919 l->latchAndReleaseBuffer();
2920 }
2921
2922 // If the layer has been removed and has no parent, then it will not be reachable
2923 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2924 // ensure we can copy its current to drawing state.
2925 if (!l->getParent()) {
2926 mOffscreenLayers.emplace(l.get());
2927 }
2928 }
2929 mLayersPendingRemoval.clear();
2930 }
2931
2932 // If this transaction is part of a window animation then the next frame
2933 // we composite should be considered an animation as well.
2934 mAnimCompositionPending = mAnimTransactionPending;
2935
2936 mDrawingState = mCurrentState;
2937 // clear the "changed" flags in current state
2938 mCurrentState.colorMatrixChanged = false;
2939
Edgar Arriaga844fa672020-01-16 14:21:42 -08002940 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002941 layer->commitChildList();
2942
2943 // If the layer can be reached when traversing mDrawingState, then the layer is no
2944 // longer offscreen. Remove the layer from the offscreenLayer set.
2945 if (mOffscreenLayers.count(layer)) {
2946 mOffscreenLayers.erase(layer);
2947 }
2948 });
2949
2950 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002951 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002952}
2953
Nataniel Borges2b796da2019-02-15 13:32:18 -08002954void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2955 if (mTracingEnabledChanged) {
2956 mTracingEnabled = mTracing.isEnabled();
2957 mTracingEnabledChanged = false;
2958 }
2959
2960 // Synchronize with Tracing thread
2961 std::unique_lock<std::mutex> lock;
2962 if (mTracingEnabled) {
2963 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2964 }
2965
2966 lockedOperation();
2967
2968 // Synchronize with Tracing thread
2969 if (mTracingEnabled) {
2970 lock.unlock();
2971 }
2972}
2973
chaviw74d90ad2019-04-26 14:45:26 -07002974void SurfaceFlinger::commitOffscreenLayers() {
2975 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002976 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002977 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2978 if (!trFlags) return;
2979
2980 layer->doTransaction(0);
2981 layer->commitChildList();
2982 });
2983 }
2984}
2985
Chia-I Wuab0c3192017-08-01 11:29:00 -07002986void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002987 for (const auto& [token, displayDevice] : mDisplays) {
2988 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002989 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002990 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002991 }
2992 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002993}
2994
Dan Stoza6b9454d2014-11-07 16:00:59 -08002995bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996{
Ady Abraham09bd3922019-04-08 10:44:56 -07002997 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002998 ALOGV("handlePageFlip");
2999
Brian Andersond6927fb2016-07-23 23:37:30 -07003000 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003001
Mathias Agopian4fec8732012-06-29 14:12:52 -07003002 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003003 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003004 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003005
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003006 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3007
Eric Penner51c59cd2014-07-28 19:51:58 -07003008 // Store the set of layers that need updates. This set must not change as
3009 // buffers are being latched, as this could result in a deadlock.
3010 // Example: Two producers share the same command stream and:
3011 // 1.) Layer 0 is latched
3012 // 2.) Layer 0 gets a new frame
3013 // 2.) Layer 1 gets a new frame
3014 // 3.) Layer 1 is latched.
3015 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3016 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003017 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003018 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003019 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003020 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003021 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003022 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003023 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003024 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003025 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003026 } else {
3027 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003028 }
Robert Carr2047fae2016-11-28 14:09:09 -08003029 });
3030
chaviw49a108c2019-08-12 11:23:06 -07003031 // The client can continue submitting buffers for offscreen layers, but they will not
3032 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3033 // layers to ensure dequeueBuffer doesn't block indefinitely.
3034 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003035 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003036 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3037 }
3038
Lloyd Piquef2c79392018-12-20 16:23:33 -08003039 if (!mLayersWithQueuedFrames.empty()) {
3040 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3041 // writes to Layer current state. See also b/119481871
3042 Mutex::Autolock lock(mStateLock);
3043
3044 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003045 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003046 mLayersPendingRefresh.push_back(layer);
3047 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003048 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003049 if (layer->isBufferLatched()) {
3050 newDataLatched = true;
3051 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003052 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003053 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003054
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003055 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003056
3057 // If we will need to wake up at some time in the future to deal with a
3058 // queued frame that shouldn't be displayed during this vsync period, wake
3059 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003060 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003061 signalLayerUpdate();
3062 }
3063
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003064 // enter boot animation on first buffer latch
3065 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3066 ALOGI("Enter boot animation");
3067 mBootStage = BootStage::BOOTANIMATION;
3068 }
3069
Edgar Arriaga844fa672020-01-16 14:21:42 -08003070 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003071
Dan Stoza6b9454d2014-11-07 16:00:59 -08003072 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003073 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074}
3075
Mathias Agopianad456f92011-01-13 17:53:01 -08003076void SurfaceFlinger::invalidateHwcGeometry()
3077{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003078 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003079}
3080
Robert Carrc0df3122019-04-11 13:18:21 -07003081status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3082 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3083 const sp<IBinder>& parentHandle,
3084 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003085 // add this layer to the current state list
3086 {
3087 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003088 sp<Layer> parent;
3089 if (parentHandle != nullptr) {
3090 parent = fromHandle(parentHandle);
3091 if (parent == nullptr) {
3092 return NAME_NOT_FOUND;
3093 }
3094 } else {
3095 parent = parentLayer;
3096 }
3097
Ady Abraham0a525092020-03-03 12:51:24 -08003098 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003099 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003100 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003101 return NO_MEMORY;
3102 }
Robert Carrc0df3122019-04-11 13:18:21 -07003103
3104 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3105
Robert Carrb89ea9d2018-12-10 13:01:14 -08003106 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003107 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003108 } else if (parent == nullptr) {
3109 lbc->onRemovedFromCurrentState();
3110 } else if (parent->isRemovedFromCurrentState()) {
3111 parent->addChild(lbc);
3112 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003113 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003114 parent->addChild(lbc);
3115 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003116
Yiwei Zhang243b3782018-05-15 17:40:04 -07003117 if (gbc != nullptr) {
3118 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3119 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3120 mMaxGraphicBufferProducerListSize,
3121 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3122 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003123 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003124 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003125 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003126 }
3127
Mathias Agopian96f08192010-06-02 23:28:45 -07003128 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003129 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003130
Dan Stoza7d89d062015-04-30 13:29:25 -07003131 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003132}
3133
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003134uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003135 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003136}
3137
Mathias Agopian3f844832013-08-07 21:24:32 -07003138uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003139 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140}
3141
Mathias Agopian3f844832013-08-07 21:24:32 -07003142uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003143 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003144}
3145
3146uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003147 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003148 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003149 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003151 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 }
3153 return old;
3154}
3155
Marissa Wall713b63f2018-10-17 15:42:43 -07003156bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003157 // to prevent onHandleDestroyed from being called while the lock is held,
3158 // we must keep a copy of the transactions (specifically the composer
3159 // states) around outside the scope of the lock
3160 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003161 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003162 {
3163 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003164
Valerie Haufce31b82019-04-30 16:41:14 -07003165 auto it = mTransactionQueues.begin();
3166 while (it != mTransactionQueues.end()) {
3167 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003168
Valerie Haufce31b82019-04-30 16:41:14 -07003169 while (!transactionQueue.empty()) {
3170 const auto& transaction = transactionQueue.front();
3171 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003172 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003173 transaction.states)) {
3174 setTransactionFlags(eTransactionFlushNeeded);
3175 break;
3176 }
3177 transactions.push_back(transaction);
3178 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3179 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003180 transaction.buffer, transaction.postTime,
3181 transaction.privileged, transaction.hasListenerCallbacks,
3182 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003183 transactionQueue.pop();
3184 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003185 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003186
Valerie Haufce31b82019-04-30 16:41:14 -07003187 if (transactionQueue.empty()) {
3188 it = mTransactionQueues.erase(it);
3189 mTransactionCV.broadcast();
3190 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003191 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003192 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003193 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003194 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003195 return flushedATransaction;
3196}
3197
3198bool SurfaceFlinger::transactionFlushNeeded() {
3199 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003200}
3201
chaviwca27f252018-02-06 16:46:39 -08003202
Marissa Wall17b4e452018-12-26 16:32:34 -08003203bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003204 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003205 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003206 if (!useCachedExpectedPresentTime)
3207 populateExpectedPresentTime();
3208
3209 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003210 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3211 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3212 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3213 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3214 return false;
3215 }
3216
Marissa Wall713b63f2018-10-17 15:42:43 -07003217 for (const ComposerState& state : states) {
3218 const layer_state_t& s = state.state;
3219 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3220 continue;
3221 }
3222 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003223 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003224 }
3225 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003226 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003227}
3228
Valerie Hau9dab9732019-08-20 09:29:25 -07003229void SurfaceFlinger::setTransactionState(
3230 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3231 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3232 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3233 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003234 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003235
Valerie Haubc6ddb12019-03-08 11:10:15 -08003236 const int64_t postTime = systemTime();
3237
Robert Carr14167e02019-02-13 13:50:55 -08003238 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3239
Mathias Agopian698c0872011-06-28 19:09:31 -07003240 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003241
Marissa Wall713b63f2018-10-17 15:42:43 -07003242 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003243 auto itr = mTransactionQueues.find(applyToken);
3244 // if this is an animation frame, wait until prior animation frame has
3245 // been applied by SF
3246 if (flags & eAnimation) {
3247 while (itr != mTransactionQueues.end()) {
3248 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3249 if (CC_UNLIKELY(err != NO_ERROR)) {
3250 ALOGW_IF(err == TIMED_OUT,
3251 "setTransactionState timed out "
3252 "waiting for animation frame to apply");
3253 break;
3254 }
3255 itr = mTransactionQueues.find(applyToken);
3256 }
3257 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003258
3259 // Expected present time is computed and cached on invalidate, so it may be stale.
3260 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3261 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003262 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003263 uncacheBuffer, postTime, privileged,
3264 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003265 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003266 return;
3267 }
3268
Valerie Haubc6ddb12019-03-08 11:10:15 -08003269 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003270 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3271 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003272}
3273
Valerie Hau9dab9732019-08-20 09:29:25 -07003274void SurfaceFlinger::applyTransactionState(
3275 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3276 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3277 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3278 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3279 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003280 uint32_t transactionFlags = 0;
3281
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003282 if (flags & eAnimation) {
3283 // For window updates that are part of an animation we must wait for
3284 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003285 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003286 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003287 if (CC_UNLIKELY(err != NO_ERROR)) {
3288 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003289 // caller after a few seconds.
3290 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3291 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003292 mAnimTransactionPending = false;
3293 break;
3294 }
3295 }
3296 }
3297
chaviwca27f252018-02-06 16:46:39 -08003298 for (const DisplayState& display : displays) {
3299 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003300 }
3301
Valerie Hau9dab9732019-08-20 09:29:25 -07003302 // start and end registration for listeners w/ no surface so they can get their callback. Note
3303 // that listeners with SurfaceControls will start registration during setClientStateLocked
3304 // below.
3305 for (const auto& listener : listenerCallbacks) {
3306 mTransactionCompletedThread.startRegistration(listener);
3307 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003308 }
3309
Valerie Hau9dab9732019-08-20 09:29:25 -07003310 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003311 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003312 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003313 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3314 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003315 }
3316
Valerie Hau9dab9732019-08-20 09:29:25 -07003317 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003318 mTransactionCompletedThread.endRegistration(listenerCallback);
3319 }
3320
Marissa Walle2ffb422018-10-12 11:33:52 -07003321 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003322 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003323 mTransactionCompletedThread.sendCallbacks();
3324 }
3325 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003326
chaviw273171b2018-12-26 11:46:30 -08003327 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3328
Marissa Wall947d34e2019-03-29 14:03:53 -07003329 if (uncacheBuffer.isValid()) {
3330 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003331 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003332 }
3333
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003334 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3335 // anyway. This can be used as a flush mechanism for previous async transactions.
3336 // Empty animation transaction can be used to simulate back-pressure, so also force a
3337 // transaction for empty animation transactions.
3338 if (transactionFlags == 0 &&
3339 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003340 transactionFlags = eTransactionNeeded;
3341 }
3342
Marissa Wall06255332019-03-27 13:48:27 -07003343 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3344 // so we don't have to wake up again next frame to preform an uneeded traversal.
3345 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3346 transactionFlags = transactionFlags & (~eTraversalNeeded);
3347 mTraversalNeededMainThread = true;
3348 }
3349
Mathias Agopian386aa982011-11-07 21:58:03 -08003350 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003351 if (mInterceptor->isEnabled()) {
3352 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003353 }
Irvel468051e2016-06-13 16:44:44 -07003354
Mathias Agopian386aa982011-11-07 21:58:03 -08003355 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003356 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3357 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003358 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003359
3360 // if this is a synchronous transaction, wait for it to take effect
3361 // before returning.
3362 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003363 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003364 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003365 if (flags & eAnimation) {
3366 mAnimTransactionPending = true;
3367 }
chaviw4fe36852019-04-15 16:25:49 -07003368 if (mPendingInputWindowCommands.syncInputWindows) {
3369 mPendingSyncInputWindows = true;
3370 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003371
3372 // applyTransactionState can be called by either the main SF thread or by
3373 // another process through setTransactionState. While a given process may wish
3374 // to wait on synchronous transactions, the main SF thread should never
3375 // be blocked. Therefore, we only wait if isMainThread is false.
3376 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003377 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3378 if (CC_UNLIKELY(err != NO_ERROR)) {
3379 // just in case something goes wrong in SF, return to the
3380 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003381 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3382 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003383 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003384 break;
3385 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003386 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003387 }
3388}
3389
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003390uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3391 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3392 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003393
Mathias Agopiane57f2922012-08-09 16:29:12 -07003394 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003395 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3396
3397 const uint32_t what = s.what;
3398 if (what & DisplayState::eSurfaceChanged) {
3399 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3400 state.surface = s.surface;
3401 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003402 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003403 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003404 if (what & DisplayState::eLayerStackChanged) {
3405 if (state.layerStack != s.layerStack) {
3406 state.layerStack = s.layerStack;
3407 flags |= eDisplayTransactionNeeded;
3408 }
3409 }
3410 if (what & DisplayState::eDisplayProjectionChanged) {
3411 if (state.orientation != s.orientation) {
3412 state.orientation = s.orientation;
3413 flags |= eDisplayTransactionNeeded;
3414 }
3415 if (state.frame != s.frame) {
3416 state.frame = s.frame;
3417 flags |= eDisplayTransactionNeeded;
3418 }
3419 if (state.viewport != s.viewport) {
3420 state.viewport = s.viewport;
3421 flags |= eDisplayTransactionNeeded;
3422 }
3423 }
3424 if (what & DisplayState::eDisplaySizeChanged) {
3425 if (state.width != s.width) {
3426 state.width = s.width;
3427 flags |= eDisplayTransactionNeeded;
3428 }
3429 if (state.height != s.height) {
3430 state.height = s.height;
3431 flags |= eDisplayTransactionNeeded;
3432 }
3433 }
3434
Mathias Agopiane57f2922012-08-09 16:29:12 -07003435 return flags;
3436}
3437
Robert Carr14167e02019-02-13 13:50:55 -08003438bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003439 IPCThreadState* ipc = IPCThreadState::self();
3440 const int pid = ipc->getCallingPid();
3441 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003442 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003443 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003444 return false;
3445 }
3446 return true;
3447}
3448
Marissa Wall3dad52d2019-03-22 14:03:19 -07003449uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003450 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3451 bool privileged,
3452 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003453 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003454
Valerie Hau9dab9732019-08-20 09:29:25 -07003455 for (auto& listener : s.listeners) {
3456 // note that startRegistration will not re-register if the listener has
3457 // already be registered for a prior surface control
3458 mTransactionCompletedThread.startRegistration(listener);
3459 listenerCallbacks.insert(listener);
3460 }
3461
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003462 sp<Layer> layer = nullptr;
3463 if (s.surface) {
3464 layer = fromHandle(s.surface);
3465 } else {
3466 // The client may provide us a null handle. Treat it as if the layer was removed.
3467 ALOGW("Attempt to set client state with a null layer handle");
3468 }
chaviw8b3871a2017-11-01 17:41:01 -07003469 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003470 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003471 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003472 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003473 }
chaviw8b3871a2017-11-01 17:41:01 -07003474 return 0;
3475 }
3476
chaviw8b3871a2017-11-01 17:41:01 -07003477 uint32_t flags = 0;
3478
Garfield Tan8a3083e2018-12-03 13:21:07 -08003479 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003480
3481 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3482 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003483 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003484 layer->pushPendingState();
3485 }
3486
Valerie Hau871d6352020-01-29 08:44:02 -08003487 // Only set by BLAST adapter layers
3488 if (what & layer_state_t::eProducerDisconnect) {
3489 layer->onDisconnect();
3490 }
3491
chaviw8b3871a2017-11-01 17:41:01 -07003492 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003493 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003494 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003495 }
chaviw8b3871a2017-11-01 17:41:01 -07003496 }
3497 if (what & layer_state_t::eLayerChanged) {
3498 // NOTE: index needs to be calculated before we update the state
3499 const auto& p = layer->getParent();
3500 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003501 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003502 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003503 mCurrentState.layersSortedByZ.removeAt(idx);
3504 mCurrentState.layersSortedByZ.add(layer);
3505 // we need traversal (state changed)
3506 // AND transaction (list changed)
3507 flags |= eTransactionNeeded|eTraversalNeeded;
3508 }
chaviw8b3871a2017-11-01 17:41:01 -07003509 } else {
3510 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003511 flags |= eTransactionNeeded|eTraversalNeeded;
3512 }
3513 }
chaviw8b3871a2017-11-01 17:41:01 -07003514 }
3515 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003516 // NOTE: index needs to be calculated before we update the state
3517 const auto& p = layer->getParent();
3518 if (p == nullptr) {
3519 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3520 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3521 mCurrentState.layersSortedByZ.removeAt(idx);
3522 mCurrentState.layersSortedByZ.add(layer);
3523 // we need traversal (state changed)
3524 // AND transaction (list changed)
3525 flags |= eTransactionNeeded|eTraversalNeeded;
3526 }
3527 } else {
3528 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3529 flags |= eTransactionNeeded|eTraversalNeeded;
3530 }
chaviw8b3871a2017-11-01 17:41:01 -07003531 }
3532 }
3533 if (what & layer_state_t::eSizeChanged) {
3534 if (layer->setSize(s.w, s.h)) {
3535 flags |= eTraversalNeeded;
3536 }
3537 }
3538 if (what & layer_state_t::eAlphaChanged) {
3539 if (layer->setAlpha(s.alpha))
3540 flags |= eTraversalNeeded;
3541 }
3542 if (what & layer_state_t::eColorChanged) {
3543 if (layer->setColor(s.color))
3544 flags |= eTraversalNeeded;
3545 }
Peiyong Lind3788632018-09-18 16:01:31 -07003546 if (what & layer_state_t::eColorTransformChanged) {
3547 if (layer->setColorTransform(s.colorTransform)) {
3548 flags |= eTraversalNeeded;
3549 }
3550 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003551 if (what & layer_state_t::eBackgroundColorChanged) {
3552 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3553 flags |= eTraversalNeeded;
3554 }
3555 }
chaviw8b3871a2017-11-01 17:41:01 -07003556 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003557 // TODO: b/109894387
3558 //
3559 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3560 // rotation. To see the problem observe that if we have a square parent, and a child
3561 // of the same size, then we rotate the child 45 degrees around it's center, the child
3562 // must now be cropped to a non rectangular 8 sided region.
3563 //
3564 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3565 // private API, and the WindowManager only uses rotation in one case, which is on a top
3566 // level layer in which cropping is not an issue.
3567 //
3568 // However given that abuse of rotation matrices could lead to surfaces extending outside
3569 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3570 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3571 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003572 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003573 flags |= eTraversalNeeded;
3574 }
3575 if (what & layer_state_t::eTransparentRegionChanged) {
3576 if (layer->setTransparentRegionHint(s.transparentRegion))
3577 flags |= eTraversalNeeded;
3578 }
3579 if (what & layer_state_t::eFlagsChanged) {
3580 if (layer->setFlags(s.flags, s.mask))
3581 flags |= eTraversalNeeded;
3582 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003583 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003584 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003585 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003586 if (what & layer_state_t::eCornerRadiusChanged) {
3587 if (layer->setCornerRadius(s.cornerRadius))
3588 flags |= eTraversalNeeded;
3589 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003590 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3591 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3592 }
chaviw8b3871a2017-11-01 17:41:01 -07003593 if (what & layer_state_t::eLayerStackChanged) {
3594 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3595 // We only allow setting layer stacks for top level layers,
3596 // everything else inherits layer stack from its parent.
3597 if (layer->hasParent()) {
3598 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003599 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003600 } else if (idx < 0) {
3601 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003602 "that also does not appear in the top level layer list. Something"
3603 " has gone wrong.",
3604 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003605 } else if (layer->setLayerStack(s.layerStack)) {
3606 mCurrentState.layersSortedByZ.removeAt(idx);
3607 mCurrentState.layersSortedByZ.add(layer);
3608 // we need traversal (state changed)
3609 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003610 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003611 }
3612 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003613 if (what & layer_state_t::eDeferTransaction_legacy) {
3614 if (s.barrierHandle_legacy != nullptr) {
3615 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3616 } else if (s.barrierGbp_legacy != nullptr) {
3617 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003618 if (authenticateSurfaceTextureLocked(gbp)) {
3619 const auto& otherLayer =
3620 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003621 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003622 } else {
3623 ALOGE("Attempt to defer transaction to to an"
3624 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003625 }
3626 }
chaviw8b3871a2017-11-01 17:41:01 -07003627 // We don't trigger a traversal here because if no other state is
3628 // changed, we don't want this to cause any more work
3629 }
chaviw8b3871a2017-11-01 17:41:01 -07003630 if (what & layer_state_t::eReparentChildren) {
3631 if (layer->reparentChildren(s.reparentHandle)) {
3632 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003633 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003634 }
chaviw8b3871a2017-11-01 17:41:01 -07003635 if (what & layer_state_t::eDetachChildren) {
3636 layer->detachChildren();
3637 }
3638 if (what & layer_state_t::eOverrideScalingModeChanged) {
3639 layer->setOverrideScalingMode(s.overrideScalingMode);
3640 // We don't trigger a traversal here because if no other state is
3641 // changed, we don't want this to cause any more work
3642 }
Marissa Wall61c58622018-07-18 10:12:20 -07003643 if (what & layer_state_t::eTransformChanged) {
3644 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3645 }
3646 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3647 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3648 flags |= eTraversalNeeded;
3649 }
3650 if (what & layer_state_t::eCropChanged) {
3651 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3652 }
Marissa Wall861616d2018-10-22 12:52:23 -07003653 if (what & layer_state_t::eFrameChanged) {
3654 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3655 }
Marissa Wall61c58622018-07-18 10:12:20 -07003656 if (what & layer_state_t::eAcquireFenceChanged) {
3657 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3658 }
3659 if (what & layer_state_t::eDataspaceChanged) {
3660 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3661 }
3662 if (what & layer_state_t::eHdrMetadataChanged) {
3663 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3664 }
3665 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3666 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3667 }
3668 if (what & layer_state_t::eApiChanged) {
3669 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3670 }
3671 if (what & layer_state_t::eSidebandStreamChanged) {
3672 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3673 }
Robert Carr720e5062018-07-30 17:45:14 -07003674 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003675 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003676 layer->setInputInfo(s.inputInfo);
3677 flags |= eTraversalNeeded;
3678 } else {
3679 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3680 }
Robert Carr720e5062018-07-30 17:45:14 -07003681 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003682 if (what & layer_state_t::eMetadataChanged) {
3683 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3684 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003685 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3686 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3687 flags |= eTraversalNeeded;
3688 }
3689 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003690 if (what & layer_state_t::eShadowRadiusChanged) {
3691 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3692 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003693 if (what & layer_state_t::eFrameRateSelectionPriority) {
3694 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3695 flags |= eTraversalNeeded;
3696 }
3697 }
Steven Thomas3172e202020-01-06 19:25:30 -08003698 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003699 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3700 "SurfaceFlinger::setClientStateLocked") &&
3701 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3702 Layer::FrameRate::convertCompatibility(
3703 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003704 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003705 }
Steven Thomas3172e202020-01-06 19:25:30 -08003706 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003707 // This has to happen after we reparent children because when we reparent to null we remove
3708 // child layers from current state and remove its relative z. If the children are reparented in
3709 // the same transaction, then we have to make sure we reparent the children first so we do not
3710 // lose its relative z order.
3711 if (what & layer_state_t::eReparent) {
3712 bool hadParent = layer->hasParent();
3713 if (layer->reparent(s.parentHandleForChild)) {
3714 if (!hadParent) {
3715 mCurrentState.layersSortedByZ.remove(layer);
3716 }
3717 flags |= eTransactionNeeded | eTraversalNeeded;
3718 }
3719 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003720 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003721 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3722 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003723 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3724 }
3725 }
Marissa Wall78b72202019-03-15 14:58:34 -07003726 bool bufferChanged = what & layer_state_t::eBufferChanged;
3727 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3728 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003729 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003730 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003731 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3732 if (success) {
3733 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3734 success = ClientCache::getInstance()
3735 .registerErasedRecipient(s.cachedBuffer,
3736 wp<ClientCache::ErasedRecipient>(this));
3737 if (!success) {
3738 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3739 }
3740 }
Marissa Wall78b72202019-03-15 14:58:34 -07003741 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003742 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003743 } else if (bufferChanged) {
3744 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003745 }
Marissa Wall78b72202019-03-15 14:58:34 -07003746 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003747 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3748 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003749 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003750 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003751 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003752 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3753 // Do not put anything that updates layer state or modifies flags after
3754 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003755 return flags;
3756}
3757
chaviw273171b2018-12-26 11:46:30 -08003758uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3759 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003760 if (inputWindowCommands.syncInputWindows) {
3761 flags |= eTraversalNeeded;
3762 }
3763
Vishnu Nairec0ab382019-02-13 15:32:56 -08003764 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003765 return flags;
3766}
3767
chaviwfe94a222019-08-21 13:52:59 -07003768status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3769 sp<IBinder>* outHandle) {
3770 if (!mirrorFromHandle) {
3771 return NAME_NOT_FOUND;
3772 }
3773
3774 sp<Layer> mirrorLayer;
3775 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003776 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003777
3778 {
3779 Mutex::Autolock _l(mStateLock);
3780 mirrorFrom = fromHandle(mirrorFromHandle);
3781 if (!mirrorFrom) {
3782 return NAME_NOT_FOUND;
3783 }
3784
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003785 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3786 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003787 if (result != NO_ERROR) {
3788 return result;
3789 }
3790
3791 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3792 }
3793
3794 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3795}
3796
Marissa Wall2d814fb2019-04-09 18:52:57 +00003797status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3798 uint32_t h, PixelFormat format, uint32_t flags,
3799 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003800 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003801 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3802 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003803 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003804 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003805 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003806 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003807 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003808
Robert Carrc0df3122019-04-11 13:18:21 -07003809 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3810 "Expected only one of parentLayer or parentHandle to be non-null. "
3811 "Programmer error?");
3812
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003813 status_t result = NO_ERROR;
3814
3815 sp<Layer> layer;
3816
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003817 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003818
Evan Roskya1f1e152019-01-24 16:17:46 -08003819 bool primaryDisplayOnly = false;
3820
3821 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3822 // TODO b/64227542
3823 if (metadata.has(METADATA_WINDOW_TYPE)) {
3824 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3825 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003826 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003827 primaryDisplayOnly = true;
3828 }
3829 }
3830
Mathias Agopian3165cc22012-08-08 19:42:09 -07003831 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003832 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003833 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3834 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003835
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003837 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003838 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003839 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003840 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003841 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003842 // check if buffer size is set for color layer.
3843 if (w > 0 || h > 0) {
3844 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3845 int(w), int(h));
3846 return BAD_VALUE;
3847 }
3848
Vishnu Nairfa247b12020-02-11 08:58:26 -08003849 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3850 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003851 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003852 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003853 // check if buffer size is set for container layer.
3854 if (w > 0 || h > 0) {
3855 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3856 int(w), int(h));
3857 return BAD_VALUE;
3858 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003859 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3860 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003861 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003862 default:
3863 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003864 break;
3865 }
3866
Dan Stoza7d89d062015-04-30 13:29:25 -07003867 if (result != NO_ERROR) {
3868 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003869 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003870
Evan Roskya1f1e152019-01-24 16:17:46 -08003871 if (primaryDisplayOnly) {
3872 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003873 }
3874
Robert Carrb89ea9d2018-12-10 13:01:14 -08003875 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003876 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3877 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003878 if (result != NO_ERROR) {
3879 return result;
3880 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003881 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003882
3883 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003884 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003885}
3886
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003887std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3888 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003889
3890 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003891 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003892
Dan Stoza436ccf32018-06-21 12:10:12 -07003893 // Grab the state lock since we're accessing mCurrentState
3894 Mutex::Autolock lock(mStateLock);
3895
Cody Northropbc755282017-03-31 12:00:08 -06003896 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003897 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003898 while (matchFound) {
3899 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003900 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003901 if (layer->getName() == uniqueName) {
3902 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003903 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003904 }
3905 });
3906 }
3907
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003908 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003909 return uniqueName;
3910}
3911
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003912status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003913 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003914 LayerMetadata metadata, PixelFormat& format,
3915 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003916 sp<IGraphicBufferProducer>* gbp,
3917 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003919 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003920 case PIXEL_FORMAT_TRANSPARENT:
3921 case PIXEL_FORMAT_TRANSLUCENT:
3922 format = PIXEL_FORMAT_RGBA_8888;
3923 break;
3924 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003925 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003926 break;
3927 }
3928
chaviwb4c6e582019-08-16 14:35:07 -07003929 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003930 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003931 args.textureName = getNewTexture();
3932 {
3933 // Grab the SF state lock during this since it's the only safe way to access
3934 // RenderEngine when creating a BufferLayerConsumer
3935 // TODO: Check if this lock is still needed here
3936 Mutex::Autolock lock(mStateLock);
3937 layer = getFactory().createBufferQueueLayer(args);
3938 }
3939
Marissa Wallfd668622018-05-10 10:21:13 -07003940 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003941 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003942 *handle = layer->getHandle();
3943 *gbp = layer->getProducer();
3944 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003945 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003946
Marissa Wallfd668622018-05-10 10:21:13 -07003947 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003948 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003949}
3950
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003951status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003952 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003953 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003954 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003955 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003956 args.displayDevice = getDefaultDisplayDevice();
3957 args.textureName = getNewTexture();
3958 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003959 if (outTransformHint) {
3960 *outTransformHint = layer->getTransformHint();
3961 }
Marissa Wall61c58622018-07-18 10:12:20 -07003962 *handle = layer->getHandle();
3963 *outLayer = layer;
3964
3965 return NO_ERROR;
3966}
3967
Vishnu Nairfa247b12020-02-11 08:58:26 -08003968status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3969 uint32_t h, uint32_t flags, LayerMetadata metadata,
3970 sp<IBinder>* handle, sp<Layer>* outLayer) {
3971 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003972 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003973 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003974 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003975}
3976
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003977status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003978 uint32_t w, uint32_t h, uint32_t flags,
3979 LayerMetadata metadata, sp<IBinder>* handle,
3980 sp<Layer>* outLayer) {
3981 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003982 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003983 *handle = (*outLayer)->getHandle();
3984 return NO_ERROR;
3985}
3986
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003987void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003988 mLayersPendingRemoval.add(layer);
3989 mLayersRemoved = true;
3990 setTransactionFlags(eTransactionNeeded);
3991}
3992
Robert Carr695d5282018-12-18 15:27:58 -08003993void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003994{
Robert Carr2e102c92018-10-23 12:11:15 -07003995 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003996 // If a layer has a parent, we allow it to out-live it's handle
3997 // with the idea that the parent holds a reference and will eventually
3998 // be cleaned up. However no one cleans up the top-level so we do so
3999 // here.
4000 if (layer->getParent() == nullptr) {
4001 mCurrentState.layersSortedByZ.remove(layer);
4002 }
4003 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004004
4005 auto it = mLayersByLocalBinderToken.begin();
4006 while (it != mLayersByLocalBinderToken.end()) {
4007 if (it->second == layer) {
4008 it = mLayersByLocalBinderToken.erase(it);
4009 } else {
4010 it++;
4011 }
4012 }
4013
Robert Carr695d5282018-12-18 15:27:58 -08004014 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004015}
4016
Mathias Agopianb60314a2012-04-10 22:09:54 -07004017// ---------------------------------------------------------------------------
4018
Andy McFadden13a082e2012-08-24 10:16:42 -07004019void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004020 const auto display = getDefaultDisplayDeviceLocked();
4021 if (!display) return;
4022
4023 const sp<IBinder> token = display->getDisplayToken().promote();
4024 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004025
Jesse Hall01e29052013-02-19 16:13:35 -08004026 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004027 Vector<ComposerState> state;
4028 Vector<DisplayState> displays;
4029 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004030 d.what = DisplayState::eDisplayProjectionChanged |
4031 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004032 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004033 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004034 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004035 d.frame.makeInvalid();
4036 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004037 d.width = 0;
4038 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004039 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004040 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4041 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004042
Dominik Laskowskie9774092018-12-11 10:04:24 -08004043 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004044
Dominik Laskowski83b88212018-12-11 13:34:06 -08004045 const nsecs_t vsyncPeriod = getVsyncPeriod();
4046 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004047
Brian Andersond0010582017-03-07 13:20:31 -08004048 // Use phase of 0 since phase is not known.
4049 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004050 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004051 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004052}
4053
4054void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004055 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004056 postMessageAsync(
4057 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004058}
4059
Ady Abraham27c70212019-06-11 10:52:26 -07004060void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4061 if (mHWCVsyncState != enabled) {
4062 getHwComposer().setVsyncEnabled(displayId, enabled);
4063 mHWCVsyncState = enabled;
4064 }
4065}
4066
Dominik Laskowskie9774092018-12-11 10:04:24 -08004067void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004068 if (display->isVirtual()) {
4069 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004070 return;
4071 }
4072
Dominik Laskowski075d3172018-05-24 15:50:06 -07004073 const auto displayId = display->getId();
4074 LOG_ALWAYS_FATAL_IF(!displayId);
4075
Dominik Laskowski34157762018-10-31 13:07:19 -07004076 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004077
4078 int currentMode = display->getPowerMode();
4079 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004080 return;
4081 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004083 display->setPowerMode(mode);
4084
Lloyd Pique4dccc412018-01-22 17:21:36 -08004085 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004086 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004087 }
4088
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004089 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004090 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004091 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004092 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004093 mScheduler->onScreenAcquired(mAppConnectionHandle);
4094 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004095 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004096
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004097 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004098 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004099 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004100
4101 struct sched_param param = {0};
4102 param.sched_priority = 1;
4103 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4104 ALOGW("Couldn't set SCHED_FIFO on display on");
4105 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004106 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004107 // Turn off the display
4108 struct sched_param param = {0};
4109 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4110 ALOGW("Couldn't set SCHED_OTHER on display off");
4111 }
4112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004113 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004114 mScheduler->disableHardwareVsync(true);
4115 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004116 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004117
Ady Abraham27c70212019-06-11 10:52:26 -07004118 // Make sure HWVsync is disabled before turning off the display
4119 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4120
Dominik Laskowski075d3172018-05-24 15:50:06 -07004121 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004122 mVisibleRegionsDirty = true;
4123 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004124 } else if (mode == HWC_POWER_MODE_DOZE ||
4125 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004126 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004127 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004128 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004129 mScheduler->onScreenAcquired(mAppConnectionHandle);
4130 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004131 }
4132 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4133 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004134 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004135 mScheduler->disableHardwareVsync(true);
4136 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004137 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004138 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004139 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004140 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004141 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004142 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004143
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004144 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004145 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004146 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004147 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004148 }
4149
Dominik Laskowski34157762018-10-31 13:07:19 -07004150 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004151}
4152
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004153void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004154 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004155 const auto display = getDisplayDevice(displayToken);
4156 if (!display) {
4157 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4158 displayToken.get());
4159 } else if (display->isVirtual()) {
4160 ALOGW("Attempt to set power mode %d for virtual display", mode);
4161 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004162 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004163 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004164 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004165}
4166
4167// ---------------------------------------------------------------------------
4168
Dominik Laskowskic2867142019-01-21 11:33:38 -08004169status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4170 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004171 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004172
Mathias Agopianbd115332013-04-18 16:41:04 -07004173 IPCThreadState* ipc = IPCThreadState::self();
4174 const int pid = ipc->getCallingPid();
4175 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004176
Mathias Agopianbd115332013-04-18 16:41:04 -07004177 if ((uid != AID_SHELL) &&
4178 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004179 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4180 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004181 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004182 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004183 // (this would indicate SF is stuck, but we want to be able to
4184 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004185 status_t err = mStateLock.timedLock(s2ns(1));
4186 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004187 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004188 StringAppendF(&result,
4189 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4190 "(no locks held)\n",
4191 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004192 }
4193
Dominik Laskowskic2867142019-01-21 11:33:38 -08004194 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004195 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004196 {"--dispsync"s,
4197 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004198 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004199 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4200 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4201 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4202 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4203 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4204 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004205 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004206 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4207 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004208
Dominik Laskowskic2867142019-01-21 11:33:38 -08004209 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004210
Dominik Laskowski46470112019-08-02 13:13:11 -07004211 const auto it = dumpers.find(flag);
4212 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004213 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004214 } else if (!asProto) {
4215 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004216 }
4217
Mathias Agopian9795c422009-08-26 16:36:26 -07004218 if (locked) {
4219 mStateLock.unlock();
4220 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004221
Dominik Laskowski46470112019-08-02 13:13:11 -07004222 if (it == dumpers.end()) {
4223 const LayersProto layersProto = dumpProtoFromMainThread();
4224 if (asProto) {
4225 result.append(layersProto.SerializeAsString());
4226 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004227 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004228 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4229 result.append(LayerProtoParser::layerTreeToString(layerTree));
4230 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004231 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004232 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004233 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004234 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004235 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004236 return NO_ERROR;
4237}
4238
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004239status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4240 if (asProto && mTracing.isEnabled()) {
4241 mTracing.writeToFileAsync();
4242 }
4243
4244 return doDump(fd, DumpArgs(), asProto);
4245}
4246
Dominik Laskowskic2867142019-01-21 11:33:38 -08004247void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004248 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004249 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004250}
4251
Dominik Laskowskic2867142019-01-21 11:33:38 -08004252void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004253 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004254
Dominik Laskowskic2867142019-01-21 11:33:38 -08004255 if (args.size() > 1) {
4256 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004257 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004258 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004259 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004260 }
Robert Carr2047fae2016-11-28 14:09:09 -08004261 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004262 } else {
4263 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004264 }
4265}
4266
Dominik Laskowskic2867142019-01-21 11:33:38 -08004267void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004268 const bool clearAll = args.size() < 2;
4269 const auto name = clearAll ? String8() : String8(args[1]);
4270
Edgar Arriaga844fa672020-01-16 14:21:42 -08004271 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004272 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004273 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004274 }
Robert Carr2047fae2016-11-28 14:09:09 -08004275 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004276
Svetoslavd85084b2014-03-20 10:28:31 -07004277 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004278}
4279
Dominik Laskowskic2867142019-01-21 11:33:38 -08004280void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4281 mTimeStats->parseArgs(asProto, args, result);
4282}
4283
Jamie Gennis6547ff42013-07-16 20:12:42 -07004284// This should only be called from the main thread. Otherwise it would need
4285// the lock and should use mCurrentState rather than mDrawingState.
4286void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004287 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004288 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004289 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004290
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004291 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004292}
4293
Yiwei Zhang5434a782018-12-05 18:06:32 -08004294void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004295 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004296
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004297 if (isLayerTripleBufferingDisabled())
4298 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004299
Yiwei Zhang5434a782018-12-05 18:06:32 -08004300 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4301 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4302 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4303 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4304 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4305 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004306 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004307}
4308
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004309void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004310 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004311
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004312 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004313 result.append("\n");
4314
Ady Abraham9e16a482019-12-03 17:19:41 -08004315 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004316 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004317 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004318 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004319
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004320 HwcConfigIndexType defaultConfig;
4321 float minFps, maxFps;
4322 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004323 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004324 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004325 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004326 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004327 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4328 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004329
Ana Krulecc2870422019-01-29 19:00:58 -08004330 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004331}
4332
Yiwei Zhang5434a782018-12-05 18:06:32 -08004333void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4334 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004335 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4336 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004337 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004338 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004339 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004340 }
David Sodman4a36e932017-11-07 14:29:47 -08004341 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004342 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004343 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004344 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4345 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004346}
4347
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004348void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4349 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004350 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4351 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004352 for (const auto& segment : history) {
4353 if (!segment.usedThirdBuffer) {
4354 stats.twoBufferTime += segment.totalTime;
4355 }
4356 if (segment.occupancyAverage < 1.0f) {
4357 stats.doubleBufferedTime += segment.totalTime;
4358 } else if (segment.occupancyAverage < 2.0f) {
4359 stats.tripleBufferedTime += segment.totalTime;
4360 }
4361 ++stats.numSegments;
4362 stats.totalTime += segment.totalTime;
4363 }
4364}
4365
Yiwei Zhang5434a782018-12-05 18:06:32 -08004366void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4367 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004368
4369 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4370 const size_t count = currentLayers.size();
4371 for (size_t i=0 ; i<count ; i++) {
4372 currentLayers[i]->dumpFrameEvents(result);
4373 }
4374}
4375
Yiwei Zhang5434a782018-12-05 18:06:32 -08004376void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004377 result.append("Buffering stats:\n");
4378 result.append(" [Layer name] <Active time> <Two buffer> "
4379 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004380 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004381 typedef std::tuple<std::string, float, float, float> BufferTuple;
4382 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004383 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004384 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004385 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004386 if (stats.numSegments == 0) {
4387 continue;
4388 }
4389 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4390 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4391 stats.totalTime;
4392 float doubleBufferRatio = static_cast<float>(
4393 stats.doubleBufferedTime) / stats.totalTime;
4394 float tripleBufferRatio = static_cast<float>(
4395 stats.tripleBufferedTime) / stats.totalTime;
4396 sorted.insert({activeTime, {name, twoBufferRatio,
4397 doubleBufferRatio, tripleBufferRatio}});
4398 }
4399 for (const auto& sortedPair : sorted) {
4400 float activeTime = sortedPair.first;
4401 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004402 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4403 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004404 }
4405 result.append("\n");
4406}
4407
Yiwei Zhang5434a782018-12-05 18:06:32 -08004408void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004409 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004410 const auto displayId = display->getId();
4411 if (!displayId) {
4412 continue;
4413 }
4414 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004415 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004416 continue;
4417 }
4418
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419 StringAppendF(&result,
4420 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4421 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004422 uint8_t port;
4423 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004424 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004425 result.append("no identification data\n");
4426 continue;
4427 }
4428
4429 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004430 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004431 continue;
4432 }
4433
4434 const auto edid = parseEdid(data);
4435 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004436 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004437 continue;
4438 }
4439
Yiwei Zhang5434a782018-12-05 18:06:32 -08004440 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004441 result.append(edid->displayName.data(), edid->displayName.length());
4442 result.append("\"\n");
4443 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004444}
4445
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004446void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4447 std::string& result) const {
4448 hwc2_display_t hwcDisplayId;
4449 uint8_t port;
4450 DisplayIdentificationData data;
4451
4452 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4453 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4454 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4455 }
4456}
4457
Yiwei Zhang5434a782018-12-05 18:06:32 -08004458void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004459 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004460 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4461 StringAppendF(&result, "DisplayColorSetting: %s\n",
4462 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004463
4464 // TODO: print out if wide-color mode is active or not
4465
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004466 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004467 const auto displayId = display->getId();
4468 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004469 continue;
4470 }
4471
Yiwei Zhang5434a782018-12-05 18:06:32 -08004472 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004473 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004474 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004476 }
4477
Lloyd Pique32cbe282018-10-19 13:09:22 -07004478 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004479 StringAppendF(&result, " Current color mode: %s (%d)\n",
4480 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004481 }
4482 result.append("\n");
4483}
4484
Vishnu Nair8406fd72019-07-30 11:29:31 -07004485LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -08004486 Mutex::Autolock _l(mStateLock);
4487 const auto device = getDefaultDisplayDeviceLocked();
chaviw1d044282017-09-27 12:19:28 -07004488 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004489 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri6b9e9912020-01-21 10:50:24 -08004490 layer->writeToProto(layersProto, traceFlags, device);
chaviw08f3cb22020-01-13 13:17:21 -08004491 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004492
chaviw1d044282017-09-27 12:19:28 -07004493 return layersProto;
4494}
4495
Alec Mouri6b9e9912020-01-21 10:50:24 -08004496void SurfaceFlinger::dumpHwc(std::string& result) const {
4497 getHwComposer().dump(result);
4498}
4499
Vishnu Nair0f085c62019-08-30 08:49:12 -07004500void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4501 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4502 // it.
4503 LayerProto* rootProto = layersProto.add_layers();
4504 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4505 rootProto->set_id(offscreenRootLayerId);
4506 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004507 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004508
4509 for (Layer* offscreenLayer : mOffscreenLayers) {
4510 // Add layer as child of the fake root
4511 rootProto->add_children(offscreenLayer->sequence);
4512
4513 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004514 LayerProto* layerProto =
4515 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004516 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004517 }
4518}
4519
Vishnu Nair8406fd72019-07-30 11:29:31 -07004520LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4521 LayersProto layersProto;
4522 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4523 return layersProto;
4524}
4525
Vishnu Nair0f085c62019-08-30 08:49:12 -07004526void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4527 result.append("Offscreen Layers:\n");
4528 postMessageSync(new LambdaMessage([&]() {
4529 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004530 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004531 layer->dumpCallingUidPid(result);
4532 });
4533 }
4534 }));
4535}
4536
Dominik Laskowskic2867142019-01-21 11:33:38 -08004537void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4538 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004539 Colorizer colorizer(colorize);
4540
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004541 // figure out if we're stuck somewhere
4542 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004543 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004544 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4545
4546 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004547 * Dump library configuration.
4548 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004549
4550 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004551 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004552 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004553 appendSfConfigString(result);
4554 appendUiConfigString(result);
4555 appendGuiConfigString(result);
4556 result.append("\n");
4557
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004558 result.append("\nDisplay identification data:\n");
4559 dumpDisplayIdentificationData(result);
4560
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004561 result.append("\nWide-Color information:\n");
4562 dumpWideColorInfo(result);
4563
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004564 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004565 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004566 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004567 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004568 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004569
Andy McFadden41d67d72014-04-25 16:58:34 -07004570 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004571 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004572 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004573 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004574 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004575
Dan Stozab90cf072015-03-05 11:05:59 -08004576 dumpStaticScreenStats(result);
4577 result.append("\n");
4578
Alec Mouri40189b02019-03-05 15:07:54 -08004579 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4580 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4581 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004582
Dan Stozae77c7662016-05-13 11:37:28 -07004583 dumpBufferingStats(result);
4584
Andy McFadden4803b742012-09-24 19:07:20 -07004585 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004586 * Dump the visible layer list
4587 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004588 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004589 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4591 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004592 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004593
Chia-I Wu2f884132018-09-13 15:17:58 -07004594 {
Lloyd Pique207def92019-02-28 16:09:52 -08004595 StringAppendF(&result, "Composition layers\n");
4596 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004597 auto* compositionState = layer->getCompositionState();
4598 if (!compositionState) return;
4599
4600 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4601 layer->getDebugName() ? layer->getDebugName()
4602 : "<unknown>");
4603 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004604 });
4605 }
4606
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004607 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004608 * Dump Display state
4609 */
4610
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004611 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004612 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004613 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004614 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004615 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004616 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004617 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004618
4619 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004620 * Dump CompositionEngine state
4621 */
4622
4623 mCompositionEngine->dump(result);
4624
4625 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004626 * Dump SurfaceFlinger global state
4627 */
4628
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004629 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004630 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004631 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004632
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004633 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004634
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004635 DebugEGLImageTracker::getInstance()->dump(result);
4636
Dominik Laskowski075d3172018-05-24 15:50:06 -07004637 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004638 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4639 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004640 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4641 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004642 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004643 StringAppendF(&result,
4644 " transaction-flags : %08x\n"
4645 " gpu_to_cpu_unsupported : %d\n",
4646 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004647
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004648 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004649 displayId && getHwComposer().isConnected(*displayId)) {
4650 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004651 StringAppendF(&result,
4652 " refresh-rate : %f fps\n"
4653 " x-dpi : %f\n"
4654 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004655 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4656 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004657 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004658
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004660
Dan Stozae22aec72016-08-01 13:20:59 -07004661 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004662 * Tracing state
4663 */
4664 mTracing.dump(result);
4665 result.append("\n");
4666
4667 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004668 * HWC layer minidump
4669 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004670 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004671 const auto displayId = display->getId();
4672 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004673 continue;
4674 }
4675
Yiwei Zhang5434a782018-12-05 18:06:32 -08004676 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004677 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004678 const sp<DisplayDevice> displayDevice = display;
4679 mCurrentState.traverseInZOrder(
4680 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004681 result.append("\n");
4682 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004683
4684 /*
4685 * Dump HWComposer state
4686 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004687 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004688 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004689 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004690 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004691 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004692 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004693
4694 /*
4695 * Dump gralloc state
4696 */
4697 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4698 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004699
4700 /*
4701 * Dump VrFlinger state if in use.
4702 */
4703 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4704 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004705 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004706 result.append("\n");
4707 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004708
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004709 result.append(mTimeStats->miniDump());
4710 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004711}
4712
Chia-I Wu28f320b2018-05-03 11:02:56 -07004713void SurfaceFlinger::updateColorMatrixLocked() {
4714 mat4 colorMatrix;
4715 if (mGlobalSaturationFactor != 1.0f) {
4716 // Rec.709 luma coefficients
4717 float3 luminance{0.213f, 0.715f, 0.072f};
4718 luminance *= 1.0f - mGlobalSaturationFactor;
4719 mat4 saturationMatrix = mat4(
4720 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4721 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4722 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4723 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4724 );
4725 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4726 } else {
4727 colorMatrix = mClientColorMatrix * mDaltonizer();
4728 }
4729
4730 if (mCurrentState.colorMatrix != colorMatrix) {
4731 mCurrentState.colorMatrix = colorMatrix;
4732 mCurrentState.colorMatrixChanged = true;
4733 setTransactionFlags(eTransactionNeeded);
4734 }
4735}
4736
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004737status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004738#pragma clang diagnostic push
4739#pragma clang diagnostic error "-Wswitch-enum"
4740 switch (static_cast<ISurfaceComposerTag>(code)) {
4741 // These methods should at minimum make sure that the client requested
4742 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004743 case BOOT_FINISHED:
4744 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004745 case CREATE_DISPLAY:
4746 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004747 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004748 case GET_ANIMATION_FRAME_STATS:
4749 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004750 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004751 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004752 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004753 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4754 case SET_AUTO_LOW_LATENCY_MODE:
4755 case GET_GAME_CONTENT_TYPE_SUPPORT:
4756 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004757 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004758 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004759 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004760 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004761 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004762 case NOTIFY_POWER_HINT:
4763 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004764 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4765 IPCThreadState* ipc = IPCThreadState::self();
4766 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4767 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004768 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004769 }
Robert Carr1db73f62016-12-21 12:58:51 -08004770 return OK;
4771 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004772 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004773 IPCThreadState* ipc = IPCThreadState::self();
4774 const int pid = ipc->getCallingPid();
4775 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004776 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4777 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004778 return PERMISSION_DENIED;
4779 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004780 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004781 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004782 // Used by apps to hook Choreographer to SurfaceFlinger.
4783 case CREATE_DISPLAY_EVENT_CONNECTION:
4784 // The following calls are currently used by clients that do not
4785 // request necessary permissions. However, they do not expose any secret
4786 // information, so it is OK to pass them.
4787 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004788 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004789 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004790 case GET_PHYSICAL_DISPLAY_IDS:
4791 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004792 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004793 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004794 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004795 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004796 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004797 case GET_DISPLAY_STATS:
4798 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4799 // Calling setTransactionState is safe, because you need to have been
4800 // granted a reference to Client* and Handle* to do anything with it.
4801 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004802 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004803 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004804 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004805 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004806 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004807 // setFrameRate() is deliberately available for apps to call without any
4808 // special permissions.
4809 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004810 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4811 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004812 return OK;
4813 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004814 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004815 case CAPTURE_SCREEN:
4816 case ADD_REGION_SAMPLING_LISTENER:
4817 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004818 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004819 IPCThreadState* ipc = IPCThreadState::self();
4820 const int pid = ipc->getCallingPid();
4821 const int uid = ipc->getCallingUid();
4822 if ((uid != AID_GRAPHICS) &&
4823 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4824 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4825 return PERMISSION_DENIED;
4826 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004827 return OK;
4828 }
chaviw93df2ea2019-04-30 16:45:12 -07004829 case CAPTURE_SCREEN_BY_ID: {
4830 IPCThreadState* ipc = IPCThreadState::self();
4831 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004832 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004833 return OK;
4834 }
4835 return PERMISSION_DENIED;
4836 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004837 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004838
4839 // These codes are used for the IBinder protocol to either interrogate the recipient
4840 // side of the transaction for its canonical interface descriptor or to dump its state.
4841 // We let them pass by default.
4842 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4843 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4844 code == IBinder::SYSPROPS_TRANSACTION) {
4845 return OK;
4846 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004847 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004848 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004849 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004850 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4851 return OK;
4852 }
4853 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4854 return PERMISSION_DENIED;
4855#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004856}
4857
Ana Krulec13be8ad2018-08-21 02:43:56 +00004858status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4859 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004860 status_t credentialCheck = CheckTransactCodeCredentials(code);
4861 if (credentialCheck != OK) {
4862 return credentialCheck;
4863 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004864
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004865 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4866 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004867 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004868 IPCThreadState* ipc = IPCThreadState::self();
4869 const int uid = ipc->getCallingUid();
4870 if (CC_UNLIKELY(uid != AID_SYSTEM
4871 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004872 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004873 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004874 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004875 return PERMISSION_DENIED;
4876 }
4877 int n;
4878 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004879 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004880 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004881 return NO_ERROR;
4882 case 1002: // SHOW_UPDATES
4883 n = data.readInt32();
4884 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004885 invalidateHwcGeometry();
4886 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004887 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004888 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004889 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004890 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004891 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004892 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004893 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004894 setTransactionFlags(
4895 eTransactionNeeded|
4896 eDisplayTransactionNeeded|
4897 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004898 return NO_ERROR;
4899 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004900 case 1006:{ // send empty update
4901 signalRefresh();
4902 return NO_ERROR;
4903 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004904 case 1008: // toggle use of hw composer
4905 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004906 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004907 invalidateHwcGeometry();
4908 repaintEverything();
4909 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004910 case 1009: // toggle use of transform hint
4911 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004912 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004913 invalidateHwcGeometry();
4914 repaintEverything();
4915 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004916 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004917 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004918 reply->writeInt32(0);
4919 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004920 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004921 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004922 return NO_ERROR;
4923 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004924 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004925 if (!display) {
4926 return NAME_NOT_FOUND;
4927 }
4928
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004929 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004930 return NO_ERROR;
4931 }
4932 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004933 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004934 // daltonize
4935 n = data.readInt32();
4936 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004937 case 1:
4938 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4939 break;
4940 case 2:
4941 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4942 break;
4943 case 3:
4944 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4945 break;
4946 default:
4947 mDaltonizer.setType(ColorBlindnessType::None);
4948 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004949 }
4950 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004951 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004952 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004953 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004954 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004955
4956 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004957 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004958 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004959 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004960 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004961 // apply a color matrix
4962 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004963 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004964 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004965 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004966 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004967 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004968 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004969 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004970 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004971 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004972 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004973
4974 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4975 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004976 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004977 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4978 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4979 }
4980
Chia-I Wu28f320b2018-05-03 11:02:56 -07004981 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004982 return NO_ERROR;
4983 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004984 case 1016: { // Unused.
4985 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004986 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004987 case 1017: {
4988 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004989 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004990 return NO_ERROR;
4991 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004992 case 1018: { // Modify Choreographer's phase offset
4993 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004994 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004995 return NO_ERROR;
4996 }
4997 case 1019: { // Modify SurfaceFlinger's phase offset
4998 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004999 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005000 return NO_ERROR;
5001 }
Irvel468051e2016-06-13 16:44:44 -07005002 case 1020: { // Layer updates interceptor
5003 n = data.readInt32();
5004 if (n) {
5005 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005006 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005007 }
5008 else{
5009 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005010 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005011 }
5012 return NO_ERROR;
5013 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005014 case 1021: { // Disable HWC virtual displays
5015 n = data.readInt32();
5016 mUseHwcVirtualDisplays = !n;
5017 return NO_ERROR;
5018 }
Romain Guy0147a172017-06-01 13:53:56 -07005019 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005020 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005021 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005022
Chia-I Wu28f320b2018-05-03 11:02:56 -07005023 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005024 return NO_ERROR;
5025 }
Romain Guy54f154a2017-10-24 21:40:32 +01005026 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005027 int32_t colorMode;
5028
Chia-I Wu0d711262018-05-21 15:19:35 -07005029 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005030 if (data.readInt32(&colorMode) == NO_ERROR) {
5031 mForceColorMode = static_cast<ColorMode>(colorMode);
5032 }
Romain Guy54f154a2017-10-24 21:40:32 +01005033 invalidateHwcGeometry();
5034 repaintEverything();
5035 return NO_ERROR;
5036 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005037 // Deprecate, use 1030 to check whether the device is color managed.
5038 case 1024: {
5039 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005040 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005041 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005042 n = data.readInt32();
5043 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005044 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005045 Mutex::Autolock lock(mStateLock);
5046 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005047 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005048 reply->writeInt32(NO_ERROR);
5049 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005050 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005051 bool writeFile = false;
5052 {
5053 Mutex::Autolock lock(mStateLock);
5054 mTracingEnabledChanged = true;
5055 writeFile = mTracing.disable();
5056 }
5057
5058 if (writeFile) {
5059 reply->writeInt32(mTracing.writeToFile());
5060 } else {
5061 reply->writeInt32(NO_ERROR);
5062 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005063 }
5064 return NO_ERROR;
5065 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005066 case 1026: { // Get layer tracing status
5067 reply->writeBool(mTracing.isEnabled());
5068 return NO_ERROR;
5069 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005070 // Is a DisplayColorSetting supported?
5071 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005072 const auto display = getDefaultDisplayDevice();
5073 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005074 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005075 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005076
5077 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5078 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005079 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005080 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005081 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005082 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005083 reply->writeBool(true);
5084 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005085 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005086 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005087 break;
5088 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005089 reply->writeBool(
5090 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005091 break;
5092 }
5093 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005094 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005095 // Is VrFlinger active?
5096 case 1028: {
5097 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005098 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005099 return NO_ERROR;
5100 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005101 // Set buffer size for SF tracing (value in KB)
5102 case 1029: {
5103 n = data.readInt32();
5104 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5105 ALOGW("Invalid buffer size: %d KB", n);
5106 reply->writeInt32(BAD_VALUE);
5107 return BAD_VALUE;
5108 }
5109
5110 ALOGD("Updating trace buffer to %d KB", n);
5111 mTracing.setBufferSize(n * 1024);
5112 reply->writeInt32(NO_ERROR);
5113 return NO_ERROR;
5114 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005115 // Is device color managed?
5116 case 1030: {
5117 reply->writeBool(useColorManagement);
5118 return NO_ERROR;
5119 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005120 // Override default composition data space
5121 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5122 // && adb shell stop zygote && adb shell start zygote
5123 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5124 // adb shell stop zygote && adb shell start zygote
5125 case 1031: {
5126 Mutex::Autolock _l(mStateLock);
5127 n = data.readInt32();
5128 if (n) {
5129 n = data.readInt32();
5130 if (n) {
5131 Dataspace dataspace = static_cast<Dataspace>(n);
5132 if (!validateCompositionDataspace(dataspace)) {
5133 return BAD_VALUE;
5134 }
5135 mDefaultCompositionDataspace = dataspace;
5136 }
5137 n = data.readInt32();
5138 if (n) {
5139 Dataspace dataspace = static_cast<Dataspace>(n);
5140 if (!validateCompositionDataspace(dataspace)) {
5141 return BAD_VALUE;
5142 }
5143 mWideColorGamutCompositionDataspace = dataspace;
5144 }
5145 } else {
5146 // restore composition data space.
5147 mDefaultCompositionDataspace = defaultCompositionDataspace;
5148 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5149 }
5150 return NO_ERROR;
5151 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005152 // Set trace flags
5153 case 1033: {
5154 n = data.readUint32();
5155 ALOGD("Updating trace flags to 0x%x", n);
5156 mTracing.setTraceFlags(n);
5157 reply->writeInt32(NO_ERROR);
5158 return NO_ERROR;
5159 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005160 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005161 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005162 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005163 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005164 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005165 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005166 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005167 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005168 } else {
5169 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005170 }
5171 return NO_ERROR;
5172 }
Ady Abraham34392f72019-04-10 11:29:27 -07005173 case 1035: {
5174 n = data.readInt32();
5175 mDebugDisplayConfigSetByBackdoor = false;
5176 if (n >= 0) {
5177 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005178 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005179 if (result != NO_ERROR) {
5180 return result;
5181 }
5182 mDebugDisplayConfigSetByBackdoor = true;
5183 }
5184 return NO_ERROR;
5185 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005186 }
5187 }
5188 return err;
5189}
5190
Steven Thomas6d8110b2017-08-31 18:24:21 -07005191void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005192 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005193 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005194}
5195
Ana Krulec7d1d6832018-12-27 11:10:09 -08005196void SurfaceFlinger::repaintEverythingForHWC() {
5197 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005198 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005199 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005200}
5201
Ady Abrahama09852a2020-02-20 14:23:42 -08005202void SurfaceFlinger::kernelTimerChanged(bool expired) {
5203 static bool updateOverlay =
5204 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5205 if (!updateOverlay || !mRefreshRateOverlay) return;
5206
5207 // Update the overlay on the main thread to avoid race conditions with
5208 // mRefreshRateConfigs->getCurrentRefreshRate()
5209 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5210 if (mRefreshRateOverlay) {
5211 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5212 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005213 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005214 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5215 if (mDesiredActiveConfigChanged) {
5216 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5217 mDesiredActiveConfig.configId);
5218 }
5219
5220 return mRefreshRateConfigs->getCurrentRefreshRate();
5221 }();
5222 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5223
5224 if (current != min) {
5225 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5226 mEventQueue->invalidate();
5227 }
5228 }
5229 }));
5230}
5231
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005232// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5233class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005234public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005235 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5236 ~WindowDisconnector() {
5237 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005238 }
5239
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005240private:
5241 ANativeWindow* mWindow;
5242 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005243};
5244
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005245status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005246 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005247 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5248 const Rect& sourceCrop, uint32_t reqWidth,
5249 uint32_t reqHeight, bool useIdentityTransform,
5250 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005251 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005252
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005253 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005254
Dominik Laskowski718f9602019-11-09 20:01:35 -08005255 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5256 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5257 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5258 renderAreaRotation = ui::Transform::ROT_0;
5259 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005260
Chia-I Wu20261cb2018-08-23 12:55:44 -07005261 sp<DisplayDevice> display;
5262 {
5263 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005264
Chia-I Wu20261cb2018-08-23 12:55:44 -07005265 display = getDisplayDeviceLocked(displayToken);
5266 if (!display) return BAD_VALUE;
5267
Chia-I Wucb023152018-08-28 12:57:23 -07005268 // set the requested width/height to the logical display viewport size
5269 // by default
5270 if (reqWidth == 0 || reqHeight == 0) {
5271 reqWidth = uint32_t(display->getViewport().width());
5272 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005273 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005274 }
5275
Peiyong Lin0e003c92018-09-17 11:09:51 -07005276 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005277 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005278
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005279 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5280 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005281 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005282 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005283}
5284
chaviw93df2ea2019-04-30 16:45:12 -07005285static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5286 switch (colorMode) {
5287 case ColorMode::DISPLAY_P3:
5288 case ColorMode::BT2100_PQ:
5289 case ColorMode::BT2100_HLG:
5290 case ColorMode::DISPLAY_BT2020:
5291 return Dataspace::DISPLAY_P3;
5292 default:
5293 return Dataspace::V0_SRGB;
5294 }
5295}
5296
5297const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5298 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5299 if (displayToken) {
5300 return getDisplayDeviceLocked(displayToken);
5301 }
5302 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5303 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005304 return getDisplayByLayerStack(displayOrLayerStack);
5305}
5306
5307const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005308 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005309 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005310 return display;
5311 }
5312 }
5313 return nullptr;
5314}
5315
5316status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5317 sp<GraphicBuffer>* outBuffer) {
5318 sp<DisplayDevice> display;
5319 uint32_t width;
5320 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005321 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005322 {
5323 Mutex::Autolock _l(mStateLock);
5324 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5325 if (!display) {
5326 return BAD_VALUE;
5327 }
5328
5329 width = uint32_t(display->getViewport().width());
5330 height = uint32_t(display->getViewport().height());
5331
Dominik Laskowski718f9602019-11-09 20:01:35 -08005332 const auto orientation = display->getOrientation();
5333 captureOrientation = ui::Transform::toRotationFlags(orientation);
5334
5335 switch (captureOrientation) {
5336 case ui::Transform::ROT_90:
5337 captureOrientation = ui::Transform::ROT_270;
5338 break;
5339
5340 case ui::Transform::ROT_270:
5341 captureOrientation = ui::Transform::ROT_90;
5342 break;
5343
5344 case ui::Transform::ROT_INVALID:
5345 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5346 captureOrientation = ui::Transform::ROT_0;
5347 break;
5348
5349 default:
5350 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005351 }
chaviw93df2ea2019-04-30 16:45:12 -07005352 *outDataspace =
5353 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5354 }
5355
5356 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5357 false /* captureSecureLayers */);
5358
5359 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5360 std::placeholders::_1);
5361 bool ignored = false;
5362 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5363 false /* useIdentityTransform */,
5364 ignored /* outCapturedSecureLayers */);
5365}
5366
Robert Carr866455f2019-04-02 16:28:26 -07005367status_t SurfaceFlinger::captureLayers(
5368 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5369 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5370 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5371 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005372 ATRACE_CALL();
5373
5374 class LayerRenderArea : public RenderArea {
5375 public:
Robert Carr578038f2018-03-09 12:25:24 -08005376 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005377 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005378 bool childrenOnly, const Rect& displayViewport)
5379 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005380 mLayer(layer),
5381 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005382 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005383 mFlinger(flinger),
5384 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005385 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005386 Rect getBounds() const override {
5387 const Layer::State& layerState(mLayer->getDrawingState());
5388 return mLayer->getBufferSize(layerState);
5389 }
Marissa Wall61c58622018-07-18 10:12:20 -07005390 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005391 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005392 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005393 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005394 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005395 }
chaviwa76b2712017-09-20 12:02:26 -07005396 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005397 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005398 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005399 Rect getSourceCrop() const override {
5400 if (mCrop.isEmpty()) {
5401 return getBounds();
5402 } else {
5403 return mCrop;
5404 }
5405 }
Robert Carr578038f2018-03-09 12:25:24 -08005406 class ReparentForDrawing {
5407 public:
5408 const sp<Layer>& oldParent;
5409 const sp<Layer>& newParent;
5410
Vishnu Nair4351ad52019-02-11 14:13:02 -08005411 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5412 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005413 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005414 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005415 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5416 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005417 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005418 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005419 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005420 };
5421
5422 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005423 const Rect sourceCrop = getSourceCrop();
5424 // no need to check rotation because there is none
5425 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5426 sourceCrop.height() != getReqHeight();
5427
Robert Carr578038f2018-03-09 12:25:24 -08005428 if (!mChildrenOnly) {
5429 mTransform = mLayer->getTransform().inverse();
5430 drawLayers();
5431 } else {
5432 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005433 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5434 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005435 // In the "childrenOnly" case we reparent the children to a screenshot
5436 // layer which has no properties set and which does not draw.
5437 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005438 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5439 "Screenshot Parent"s, w, h, 0,
5440 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005441
Vishnu Nair4351ad52019-02-11 14:13:02 -08005442 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005443 drawLayers();
5444 }
5445 }
chaviwa76b2712017-09-20 12:02:26 -07005446
chaviwa76b2712017-09-20 12:02:26 -07005447 private:
chaviw7206d492017-11-10 16:16:12 -08005448 const sp<Layer> mLayer;
5449 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005450
Peiyong Linefefaac2018-08-17 12:27:51 -07005451 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005452 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005453
5454 SurfaceFlinger* mFlinger;
5455 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005456 };
5457
Robert Carrc0df3122019-04-11 13:18:21 -07005458 int reqWidth = 0;
5459 int reqHeight = 0;
5460 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005461 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005462 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005463 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005464 {
5465 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005466
Robert Carrc0df3122019-04-11 13:18:21 -07005467 parent = fromHandle(layerHandleBinder);
5468 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5469 ALOGE("captureLayers called with an invalid or removed parent");
5470 return NAME_NOT_FOUND;
5471 }
5472
5473 const int uid = IPCThreadState::self()->getCallingUid();
5474 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5475 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5476 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5477 return PERMISSION_DENIED;
5478 }
5479
Vishnu Nairefc42e22019-12-03 17:36:12 -08005480 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005481 if (sourceCrop.width() <= 0) {
5482 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005483 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005484 }
5485
5486 if (sourceCrop.height() <= 0) {
5487 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005488 crop.bottom = parentSourceBounds.getHeight();
5489 }
5490
5491 if (crop.isEmpty() || frameScale <= 0.0f) {
5492 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5493 // crop was not specified, or an invalid frame scale was provided.
5494 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005495 }
5496 reqWidth = crop.width() * frameScale;
5497 reqHeight = crop.height() * frameScale;
5498
5499 for (const auto& handle : excludeHandles) {
5500 sp<Layer> excludeLayer = fromHandle(handle);
5501 if (excludeLayer != nullptr) {
5502 excludeLayers.emplace(excludeLayer);
5503 } else {
5504 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5505 return NAME_NOT_FOUND;
5506 }
5507 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005508
5509 auto display = getDisplayByLayerStack(parent->getLayerStack());
5510 if (!display) {
5511 return BAD_VALUE;
5512 }
5513
5514 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005515 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005516
Chia-I Wu20261cb2018-08-23 12:55:44 -07005517 // really small crop or frameScale
5518 if (reqWidth <= 0) {
5519 reqWidth = 1;
5520 }
5521 if (reqHeight <= 0) {
5522 reqHeight = 1;
5523 }
5524
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005525 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5526 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005527 auto traverseLayers = [parent, childrenOnly,
5528 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005529 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5530 if (!layer->isVisible()) {
5531 return;
Robert Carr578038f2018-03-09 12:25:24 -08005532 } else if (childrenOnly && layer == parent.get()) {
5533 return;
chaviwa76b2712017-09-20 12:02:26 -07005534 }
Robert Carr866455f2019-04-02 16:28:26 -07005535
5536 sp<Layer> p = layer;
5537 while (p != nullptr) {
5538 if (excludeLayers.count(p) != 0) {
5539 return;
5540 }
5541 p = p->getParent();
5542 }
5543
chaviwa76b2712017-09-20 12:02:26 -07005544 visitor(layer);
5545 });
5546 };
Robert Carr108b2c72019-04-02 16:32:58 -07005547
5548 bool outCapturedSecureLayers = false;
5549 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5550 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005551}
5552
5553status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5554 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005555 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005556 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005557 bool useIdentityTransform,
5558 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005559 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005560
Peiyong Lin0e003c92018-09-17 11:09:51 -07005561 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005562 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5563 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005564 *outBuffer =
5565 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5566 static_cast<android_pixel_format>(reqPixelFormat), 1,
5567 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005568
Robert Carr108b2c72019-04-02 16:32:58 -07005569 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5570 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005571}
5572
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005573status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5574 TraverseLayersFunction traverseLayers,
5575 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005576 bool useIdentityTransform,
5577 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005578 // This mutex protects syncFd and captureResult for communication of the return values from the
5579 // main thread back to this Binder thread
5580 std::mutex captureMutex;
5581 std::condition_variable captureCondition;
5582 std::unique_lock<std::mutex> captureLock(captureMutex);
5583 int syncFd = -1;
5584 std::optional<status_t> captureResult;
5585
Robert Carr03480e22018-01-04 16:02:06 -08005586 const int uid = IPCThreadState::self()->getCallingUid();
5587 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5588
Dominik Laskowski8c001672018-05-30 16:52:06 -07005589 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005590 // If there is a refresh pending, bug out early and tell the binder thread to try again
5591 // after the refresh.
5592 if (mRefreshPending) {
5593 ATRACE_NAME("Skipping screenshot for now");
5594 std::unique_lock<std::mutex> captureLock(captureMutex);
5595 captureResult = std::make_optional<status_t>(EAGAIN);
5596 captureCondition.notify_one();
5597 return;
5598 }
5599
5600 status_t result = NO_ERROR;
5601 int fd = -1;
5602 {
5603 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005604 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005605 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005606 useIdentityTransform, forSystem, &fd,
5607 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005608 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005609 }
5610
5611 {
5612 std::unique_lock<std::mutex> captureLock(captureMutex);
5613 syncFd = fd;
5614 captureResult = std::make_optional<status_t>(result);
5615 captureCondition.notify_one();
5616 }
5617 });
5618
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005619 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005620 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005621 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005622 while (*captureResult == EAGAIN) {
5623 captureResult.reset();
5624 result = postMessageAsync(message);
5625 if (result != NO_ERROR) {
5626 return result;
5627 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005628 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005629 }
5630 result = *captureResult;
5631 }
5632
5633 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005634 sync_wait(syncFd, -1);
5635 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005636 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005637
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005638 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005639}
5640
chaviwa76b2712017-09-20 12:02:26 -07005641void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005642 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005643 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5644 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005645 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005646
chaviwa76b2712017-09-20 12:02:26 -07005647 const auto reqWidth = renderArea.getReqWidth();
5648 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005649 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005650 const auto transform = renderArea.getTransform();
5651 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005652 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005653
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005654 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005655 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005656
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005657 // assume that bounds are never offset, and that they are the same as the
5658 // buffer bounds.
5659 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005660 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005661 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005662
5663 // Now take into account the rotation flag. We append a transform that
5664 // rotates the layer stack about the origin, then translate by buffer
5665 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005666 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005667 int displacementX = 0;
5668 int displacementY = 0;
5669 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5670 switch (rotation) {
5671 case ui::Transform::ROT_90:
5672 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005673 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005674 break;
5675 case ui::Transform::ROT_180:
5676 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005677 displacementY = renderArea.getBounds().getWidth();
5678 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005679 break;
5680 case ui::Transform::ROT_270:
5681 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005682 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005683 break;
5684 default:
5685 break;
5686 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005687
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005688 // We need to transform the clipping window into the right spot.
5689 // First, rotate the clipping rectangle by the rotation hint to get the
5690 // right orientation
5691 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5692 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5693 const vec4 rotClipTL = rotMatrix * clipTL;
5694 const vec4 rotClipBR = rotMatrix * clipBR;
5695 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5696 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5697 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5698 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5699
5700 // Now reposition the clipping rectangle with the displacement vector
5701 // computed above.
5702 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005703 clientCompositionDisplay.clip =
5704 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5705 newClipRight + displacementX, newClipBottom + displacementY);
5706
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005707 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005708 clientCompositionDisplay.globalTransform =
5709 clipTransform * clientCompositionDisplay.globalTransform;
5710
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005711 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5712 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005713
chaviw50da5042018-04-09 13:49:37 -07005714 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005715
Vishnu Nair9b079a22020-01-21 14:36:08 -08005716 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005717 fillLayer.source.buffer.buffer = nullptr;
5718 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5719 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5720 fillLayer.alpha = half(alpha);
5721 clientCompositionLayers.push_back(fillLayer);
5722
5723 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005724 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005725 const bool supportProtectedContent = false;
5726 Region clip(renderArea.getBounds());
5727 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5728 clip,
5729 useIdentityTransform,
5730 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5731 renderArea.isSecure(),
5732 supportProtectedContent,
5733 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005734 displayViewport,
5735 clientCompositionDisplay.outputDataspace,
5736 true, /* realContentIsVisible */
5737 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005738 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005739 std::vector<compositionengine::LayerFE::LayerSettings> results =
5740 layer->prepareClientCompositionList(targetSettings);
5741 clientCompositionLayers.insert(clientCompositionLayers.end(),
5742 std::make_move_iterator(results.begin()),
5743 std::make_move_iterator(results.end()));
5744 results.clear();
5745
chaviwa76b2712017-09-20 12:02:26 -07005746 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005747
Vishnu Nair9b079a22020-01-21 14:36:08 -08005748 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5749 clientCompositionLayers.reserve(clientCompositionLayers.size());
5750 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5751 std::back_inserter(clientCompositionLayerPointers),
5752 [](compositionengine::LayerFE::LayerSettings& settings)
5753 -> renderengine::LayerSettings* { return &settings; });
5754
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005755 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005756 // Use an empty fence for the buffer fence, since we just created the buffer so
5757 // there is no need for synchronization with the GPU.
5758 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005759 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005760 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005761 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005762 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005763
5764 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005765}
5766
chaviwa76b2712017-09-20 12:02:26 -07005767status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5768 TraverseLayersFunction traverseLayers,
5769 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005770 bool useIdentityTransform, bool forSystem,
5771 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005772 ATRACE_CALL();
5773
chaviwa76b2712017-09-20 12:02:26 -07005774 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005775 outCapturedSecureLayers =
5776 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005777 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005778
Robert Carr03480e22018-01-04 16:02:06 -08005779 // We allow the system server to take screenshots of secure layers for
5780 // use in situations like the Screen-rotation animation and place
5781 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005782 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005783 ALOGW("FB is protected: PERMISSION_DENIED");
5784 return PERMISSION_DENIED;
5785 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005786 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005787 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005788}
5789
chaviw95ef3c42019-02-14 10:55:09 -08005790void SurfaceFlinger::setInputWindowsFinished() {
5791 Mutex::Autolock _l(mStateLock);
5792
5793 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005794
chaviw95ef3c42019-02-14 10:55:09 -08005795 mTransactionCV.broadcast();
5796}
chaviw5f21a5e2019-02-14 10:00:34 -08005797
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005798// ---------------------------------------------------------------------------
5799
Edgar Arriaga844fa672020-01-16 14:21:42 -08005800void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5801 layersSortedByZ.traverse(visitor);
5802}
5803
Dan Stoza412903f2017-04-27 13:42:17 -07005804void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5805 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005806}
5807
Dan Stoza412903f2017-04-27 13:42:17 -07005808void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5809 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005810}
5811
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005812void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005813 const LayerVector::Visitor& visitor) {
5814 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005815 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005816 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005817 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005818 continue;
5819 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005820 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005821 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005822 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005823 return;
5824 }
chaviwa76b2712017-09-20 12:02:26 -07005825 if (!layer->isVisible()) {
5826 return;
5827 }
5828 visitor(layer);
5829 });
5830 }
5831}
5832
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005833status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5834 HwcConfigIndexType defaultConfig,
5835 float minRefreshRate,
5836 float maxRefreshRate) {
5837 Mutex::Autolock lock(mStateLock);
5838
Dominik Laskowski22488f62019-03-28 09:53:04 -07005839 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005840 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5841 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5842 // it should go thru setDesiredActiveConfig, similar to primary display.
5843 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5844 const auto displayId = display->getId();
5845 LOG_ALWAYS_FATAL_IF(!displayId);
5846
5847 HWC2::VsyncPeriodChangeConstraints constraints;
5848 constraints.desiredTimeNanos = systemTime();
5849 constraints.seamlessRequired = false;
5850
5851 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005852 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5853 constraints, &timeline) < 0) {
5854 return BAD_VALUE;
5855 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005856 if (timeline.refreshRequired) {
5857 repaintEverythingForHWC();
5858 }
5859
Ady Abrahamdfa37362020-01-21 18:02:39 -08005860 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005861 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005862 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5863 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005864 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005865 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005866 }
5867
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005868 if (mDebugDisplayConfigSetByBackdoor) {
5869 // ignore this request as config is overridden by backdoor
5870 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005871 }
5872
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005873 bool policyChanged;
5874 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5875 &policyChanged) < 0) {
5876 return BAD_VALUE;
5877 }
5878 if (!policyChanged) {
5879 return NO_ERROR;
5880 }
5881
5882 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5883 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005884
5885 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5886 // that listeners that care about a change in allowed configs can get the notification.
5887 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005888 const nsecs_t vsyncPeriod =
5889 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005890 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005891 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005892
Ana Krulec3f6a2062020-01-23 15:48:01 -08005893 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005894 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005895 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5896 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5897 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5898 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5899 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5900
5901 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5902 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5903 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005904 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005905 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005906 }
5907
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005908 return NO_ERROR;
5909}
5910
Ana Krulec0782b882019-10-15 17:34:54 -07005911status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005912 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005913 float maxRefreshRate) {
5914 ATRACE_CALL();
5915
5916 if (!displayToken) {
5917 return BAD_VALUE;
5918 }
5919
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005920 status_t result = NO_ERROR;
5921
Ana Krulec234bb162019-11-10 22:55:55 +01005922 postMessageSync(new LambdaMessage([&]() {
5923 const auto display = getDisplayDeviceLocked(displayToken);
5924 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005925 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005926 ALOGE("Attempt to set desired display configs for invalid display token %p",
5927 displayToken.get());
5928 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005929 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005930 ALOGW("Attempt to set desired display configs for virtual display");
5931 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005932 result =
5933 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5934 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005935 }
5936 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005937
5938 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005939}
5940
5941status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005942 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005943 float* outMinRefreshRate,
5944 float* outMaxRefreshRate) {
5945 ATRACE_CALL();
5946
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005947 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005948 return BAD_VALUE;
5949 }
5950
5951 Mutex::Autolock lock(mStateLock);
5952 const auto display = getDisplayDeviceLocked(displayToken);
5953 if (!display) {
5954 return NAME_NOT_FOUND;
5955 }
5956
5957 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005958 HwcConfigIndexType defaultConfig;
5959 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5960 *outDefaultConfig = defaultConfig.value();
5961 return NO_ERROR;
5962 } else if (display->isVirtual()) {
5963 return BAD_VALUE;
5964 } else {
5965 const auto displayId = display->getId();
5966 if (!displayId) {
5967 return BAD_VALUE;
5968 }
5969 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5970 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5971 *outMinRefreshRate = 1e9f / vsyncPeriod;
5972 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5973 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005974 }
Ana Krulec0782b882019-10-15 17:34:54 -07005975}
5976
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005977void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005978 mFlinger->setInputWindowsFinished();
5979}
5980
Robert Carrc0df3122019-04-11 13:18:21 -07005981sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005982 BBinder* b = nullptr;
5983 if (handle) {
5984 b = handle->localBinder();
5985 }
Robert Carrc0df3122019-04-11 13:18:21 -07005986 if (b == nullptr) {
5987 return nullptr;
5988 }
5989 auto it = mLayersByLocalBinderToken.find(b);
5990 if (it != mLayersByLocalBinderToken.end()) {
5991 return it->second.promote();
5992 }
5993 return nullptr;
5994}
5995
Dominik Laskowski75848362019-11-11 17:57:20 -08005996void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005997 mNumLayers++;
5998 mScheduler->registerLayer(layer);
5999}
6000
6001void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6002 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006003 removeFromOffscreenLayers(layer);
6004}
6005
6006// WARNING: ONLY CALL THIS FROM LAYER DTOR
6007// Here we add children in the current state to offscreen layers and remove the
6008// layer itself from the offscreen layer list. Since
6009// this is the dtor, it is safe to access the current state. This keeps us
6010// from dangling children layers such that they are not reachable from the
6011// Drawing state nor the offscreen layer list
6012// See b/141111965
6013void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6014 for (auto& child : layer->getCurrentChildren()) {
6015 mOffscreenLayers.emplace(child.get());
6016 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006017 mOffscreenLayers.erase(layer);
6018}
6019
Alec Mouri4545a8a2019-08-08 20:05:32 -07006020void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6021 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6022}
6023
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006024status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6025 float lightPosY, float lightPosZ,
6026 float lightRadius) {
6027 Mutex::Autolock _l(mStateLock);
6028 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6029 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6030 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6031 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6032 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6033
6034 // these values are overridden when calculating the shadow settings for a layer.
6035 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6036 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006037 return NO_ERROR;
6038}
6039
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006040const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6041 const {
6042 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6043 // on the work to remove the table in that bug rather than adding more to
6044 // it.
6045 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6046 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6047 // supported, and exposed via the
6048 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6049 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6050 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6051 };
6052 return genericLayerMetadataKeyMap;
6053}
6054
Steven Thomas62a4cf82020-01-31 12:04:03 -08006055status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6056 int8_t compatibility) {
6057 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6058 return BAD_VALUE;
6059 }
6060
6061 Mutex::Autolock lock(mStateLock);
6062 if (authenticateSurfaceTextureLocked(surface)) {
6063 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6064 if (layer->setFrameRate(
6065 Layer::FrameRate(frameRate,
6066 Layer::FrameRate::convertCompatibility(compatibility)))) {
6067 setTransactionFlags(eTraversalNeeded);
6068 }
6069 } else {
6070 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6071 return BAD_VALUE;
6072 }
6073 return NO_ERROR;
6074}
6075
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006076} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006077
Mathias Agopian3f844832013-08-07 21:24:32 -07006078#if defined(__gl_h_)
6079#error "don't include gl/gl.h in this file"
6080#endif
6081
6082#if defined(__gl2_h_)
6083#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006084#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006085
6086// TODO(b/129481165): remove the #pragma below and fix conversion issues
6087#pragma clang diagnostic pop // ignored "-Wconversion"